babylon.no-module.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346
  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. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. this.x = x;
  2190. this.y = y;
  2191. }
  2192. /**
  2193. * Gets a string with the Vector2 coordinates
  2194. * @returns a string with the Vector2 coordinates
  2195. */
  2196. Vector2.prototype.toString = function () {
  2197. return "{X: " + this.x + " Y:" + this.y + "}";
  2198. };
  2199. /**
  2200. * Gets class name
  2201. * @returns the string "Vector2"
  2202. */
  2203. Vector2.prototype.getClassName = function () {
  2204. return "Vector2";
  2205. };
  2206. /**
  2207. * Gets current vector hash code
  2208. * @returns the Vector2 hash code as a number
  2209. */
  2210. Vector2.prototype.getHashCode = function () {
  2211. var hash = this.x || 0;
  2212. hash = (hash * 397) ^ (this.y || 0);
  2213. return hash;
  2214. };
  2215. // Operators
  2216. /**
  2217. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2218. * @param array defines the source array
  2219. * @param index defines the offset in source array
  2220. * @returns the current Vector2
  2221. */
  2222. Vector2.prototype.toArray = function (array, index) {
  2223. if (index === void 0) { index = 0; }
  2224. array[index] = this.x;
  2225. array[index + 1] = this.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Copy the current vector to an array
  2230. * @returns a new array with 2 elements: the Vector2 coordinates.
  2231. */
  2232. Vector2.prototype.asArray = function () {
  2233. var result = new Array();
  2234. this.toArray(result, 0);
  2235. return result;
  2236. };
  2237. /**
  2238. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2239. * @param source defines the source Vector2
  2240. * @returns the current updated Vector2
  2241. */
  2242. Vector2.prototype.copyFrom = function (source) {
  2243. this.x = source.x;
  2244. this.y = source.y;
  2245. return this;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the given floats
  2249. * @param x defines the first coordinate
  2250. * @param y defines the second coordinate
  2251. * @returns the current updated Vector2
  2252. */
  2253. Vector2.prototype.copyFromFloats = function (x, y) {
  2254. this.x = x;
  2255. this.y = y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the Vector2 coordinates with the given floats
  2260. * @param x defines the first coordinate
  2261. * @param y defines the second coordinate
  2262. * @returns the current updated Vector2
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Add another vector with the current one
  2269. * @param otherVector defines the other vector
  2270. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2271. */
  2272. Vector2.prototype.add = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2277. * @param otherVector defines the other vector
  2278. * @param result defines the target vector
  2279. * @returns the unmodified current Vector2
  2280. */
  2281. Vector2.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2288. * @param otherVector defines the other vector
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2
  2300. */
  2301. Vector2.prototype.addVector3 = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2306. * @param otherVector defines the other vector
  2307. * @returns a new Vector2
  2308. */
  2309. Vector2.prototype.subtract = function (otherVector) {
  2310. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2311. };
  2312. /**
  2313. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2314. * @param otherVector defines the other vector
  2315. * @param result defines the target vector
  2316. * @returns the unmodified current Vector2
  2317. */
  2318. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2319. result.x = this.x - otherVector.x;
  2320. result.y = this.y - otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns the current updated Vector2
  2327. */
  2328. Vector2.prototype.subtractInPlace = function (otherVector) {
  2329. this.x -= otherVector.x;
  2330. this.y -= otherVector.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Multiplies in place the current Vector2 coordinates by the given ones
  2335. * @param otherVector defines the other vector
  2336. * @returns the current updated Vector2
  2337. */
  2338. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2339. this.x *= otherVector.x;
  2340. this.y *= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2358. result.x = this.x * otherVector.x;
  2359. result.y = this.y * otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2364. * @param x defines the first coordinate
  2365. * @param y defines the second coordinate
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.divideToRef = function (otherVector, result) {
  2386. result.x = this.x / otherVector.x;
  2387. result.y = this.y / otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Divides the current Vector3 coordinates by the given ones
  2392. * @param otherVector defines the other vector
  2393. * @returns the current updated Vector2
  2394. */
  2395. Vector2.prototype.divideInPlace = function (otherVector) {
  2396. return this.divideToRef(otherVector, this);
  2397. };
  2398. /**
  2399. * Gets a new Vector2 with current Vector2 negated coordinates
  2400. * @returns a new Vector2
  2401. */
  2402. Vector2.prototype.negate = function () {
  2403. return new Vector2(-this.x, -this.y);
  2404. };
  2405. /**
  2406. * Multiply the Vector2 coordinates by scale
  2407. * @param scale defines the scaling factor
  2408. * @returns the current updated Vector2
  2409. */
  2410. Vector2.prototype.scaleInPlace = function (scale) {
  2411. this.x *= scale;
  2412. this.y *= scale;
  2413. return this;
  2414. };
  2415. /**
  2416. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2417. * @param scale defines the scaling factor
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.scale = function (scale) {
  2421. var result = new Vector2(0, 0);
  2422. this.scaleToRef(scale, result);
  2423. return result;
  2424. };
  2425. /**
  2426. * Scale the current Vector2 values by a factor to a given Vector2
  2427. * @param scale defines the scale factor
  2428. * @param result defines the Vector2 object where to store the result
  2429. * @returns the unmodified current Vector2
  2430. */
  2431. Vector2.prototype.scaleToRef = function (scale, result) {
  2432. result.x = this.x * scale;
  2433. result.y = this.y * scale;
  2434. return this;
  2435. };
  2436. /**
  2437. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2438. * @param scale defines the scale factor
  2439. * @param result defines the Vector2 object where to store the result
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2443. result.x += this.x * scale;
  2444. result.y += this.y * scale;
  2445. return this;
  2446. };
  2447. /**
  2448. * Gets a boolean if two vectors are equals
  2449. * @param otherVector defines the other vector
  2450. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2451. */
  2452. Vector2.prototype.equals = function (otherVector) {
  2453. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2454. };
  2455. /**
  2456. * Gets a boolean if two vectors are equals (using an epsilon value)
  2457. * @param otherVector defines the other vector
  2458. * @param epsilon defines the minimal distance to consider equality
  2459. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2460. */
  2461. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2462. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2463. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2464. };
  2465. // Properties
  2466. /**
  2467. * Gets the length of the vector
  2468. * @returns the vector length (float)
  2469. */
  2470. Vector2.prototype.length = function () {
  2471. return Math.sqrt(this.x * this.x + this.y * this.y);
  2472. };
  2473. /**
  2474. * Gets the vector squared length
  2475. * @returns the vector squared length (float)
  2476. */
  2477. Vector2.prototype.lengthSquared = function () {
  2478. return (this.x * this.x + this.y * this.y);
  2479. };
  2480. // Methods
  2481. /**
  2482. * Normalize the vector
  2483. * @returns the current updated Vector2
  2484. */
  2485. Vector2.prototype.normalize = function () {
  2486. var len = this.length();
  2487. if (len === 0)
  2488. return this;
  2489. var num = 1.0 / len;
  2490. this.x *= num;
  2491. this.y *= num;
  2492. return this;
  2493. };
  2494. /**
  2495. * Gets a new Vector2 copied from the Vector2
  2496. * @returns a new Vector2
  2497. */
  2498. Vector2.prototype.clone = function () {
  2499. return new Vector2(this.x, this.y);
  2500. };
  2501. // Statics
  2502. /**
  2503. * Gets a new Vector2(0, 0)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.Zero = function () {
  2507. return new Vector2(0, 0);
  2508. };
  2509. /**
  2510. * Gets a new Vector2(1, 1)
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.One = function () {
  2514. return new Vector2(1, 1);
  2515. };
  2516. /**
  2517. * Gets a new Vector2 set from the given index element of the given array
  2518. * @param array defines the data source
  2519. * @param offset defines the offset in the data source
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.FromArray = function (array, offset) {
  2523. if (offset === void 0) { offset = 0; }
  2524. return new Vector2(array[offset], array[offset + 1]);
  2525. };
  2526. /**
  2527. * Sets "result" from the given index element of the given array
  2528. * @param array defines the data source
  2529. * @param offset defines the offset in the data source
  2530. * @param result defines the target vector
  2531. */
  2532. Vector2.FromArrayToRef = function (array, offset, result) {
  2533. result.x = array[offset];
  2534. result.y = array[offset + 1];
  2535. };
  2536. /**
  2537. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2538. * @param value1 defines 1st point of control
  2539. * @param value2 defines 2nd point of control
  2540. * @param value3 defines 3rd point of control
  2541. * @param value4 defines 4th point of control
  2542. * @param amount defines the interpolation factor
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2546. var squared = amount * amount;
  2547. var cubed = amount * squared;
  2548. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2549. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2550. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2551. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2552. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2553. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2554. return new Vector2(x, y);
  2555. };
  2556. /**
  2557. * 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".
  2558. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2559. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2560. * @param value defines the value to clamp
  2561. * @param min defines the lower limit
  2562. * @param max defines the upper limit
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.Clamp = function (value, min, max) {
  2566. var x = value.x;
  2567. x = (x > max.x) ? max.x : x;
  2568. x = (x < min.x) ? min.x : x;
  2569. var y = value.y;
  2570. y = (y > max.y) ? max.y : y;
  2571. y = (y < min.y) ? min.y : y;
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2576. * @param value1 defines the 1st control point
  2577. * @param tangent1 defines the outgoing tangent
  2578. * @param value2 defines the 2nd control point
  2579. * @param tangent2 defines the incoming tangent
  2580. * @param amount defines the interpolation factor
  2581. * @returns a new Vector2
  2582. */
  2583. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2584. var squared = amount * amount;
  2585. var cubed = amount * squared;
  2586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2588. var part3 = (cubed - (2.0 * squared)) + amount;
  2589. var part4 = cubed - squared;
  2590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2596. * @param start defines the start vector
  2597. * @param end defines the end vector
  2598. * @param amount defines the interpolation factor
  2599. * @returns a new Vector2
  2600. */
  2601. Vector2.Lerp = function (start, end, amount) {
  2602. var x = start.x + ((end.x - start.x) * amount);
  2603. var y = start.y + ((end.y - start.y) * amount);
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Gets the dot product of the vector "left" and the vector "right"
  2608. * @param left defines first vector
  2609. * @param right defines second vector
  2610. * @returns the dot product (float)
  2611. */
  2612. Vector2.Dot = function (left, right) {
  2613. return left.x * right.x + left.y * right.y;
  2614. };
  2615. /**
  2616. * Returns a new Vector2 equal to the normalized given vector
  2617. * @param vector defines the vector to normalize
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Normalize = function (vector) {
  2621. var newVector = vector.clone();
  2622. newVector.normalize();
  2623. return newVector;
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2627. * @param left defines 1st vector
  2628. * @param right defines 2nd vector
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Minimize = function (left, right) {
  2632. var x = (left.x < right.x) ? left.x : right.x;
  2633. var y = (left.y < right.y) ? left.y : right.y;
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2638. * @param left defines 1st vector
  2639. * @param right defines 2nd vector
  2640. * @returns a new Vector2
  2641. */
  2642. Vector2.Maximize = function (left, right) {
  2643. var x = (left.x > right.x) ? left.x : right.x;
  2644. var y = (left.y > right.y) ? left.y : right.y;
  2645. return new Vector2(x, y);
  2646. };
  2647. /**
  2648. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2649. * @param vector defines the vector to transform
  2650. * @param transformation defines the matrix to apply
  2651. * @returns a new Vector2
  2652. */
  2653. Vector2.Transform = function (vector, transformation) {
  2654. var r = Vector2.Zero();
  2655. Vector2.TransformToRef(vector, transformation, r);
  2656. return r;
  2657. };
  2658. /**
  2659. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2660. * @param vector defines the vector to transform
  2661. * @param transformation defines the matrix to apply
  2662. * @param result defines the target vector
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Determines if a given vector is included in a triangle
  2672. * @param p defines the vector to test
  2673. * @param p0 defines 1st triangle point
  2674. * @param p1 defines 2nd triangle point
  2675. * @param p2 defines 3rd triangle point
  2676. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Gets the distance between the vectors "value1" and "value2"
  2687. * @param value1 defines first vector
  2688. * @param value2 defines second vector
  2689. * @returns the distance between vectors
  2690. */
  2691. Vector2.Distance = function (value1, value2) {
  2692. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2693. };
  2694. /**
  2695. * Returns the squared distance between the vectors "value1" and "value2"
  2696. * @param value1 defines first vector
  2697. * @param value2 defines second vector
  2698. * @returns the squared distance between vectors
  2699. */
  2700. Vector2.DistanceSquared = function (value1, value2) {
  2701. var x = value1.x - value2.x;
  2702. var y = value1.y - value2.y;
  2703. return (x * x) + (y * y);
  2704. };
  2705. /**
  2706. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Center = function (value1, value2) {
  2712. var center = value1.add(value2);
  2713. center.scaleInPlace(0.5);
  2714. return center;
  2715. };
  2716. /**
  2717. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2718. * @param p defines the middle point
  2719. * @param segA defines one point of the segment
  2720. * @param segB defines the other point of the segment
  2721. * @returns the shortest distance
  2722. */
  2723. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2724. var l2 = Vector2.DistanceSquared(segA, segB);
  2725. if (l2 === 0.0) {
  2726. return Vector2.Distance(p, segA);
  2727. }
  2728. var v = segB.subtract(segA);
  2729. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2730. var proj = segA.add(v.multiplyByFloats(t, t));
  2731. return Vector2.Distance(p, proj);
  2732. };
  2733. return Vector2;
  2734. }());
  2735. BABYLON.Vector2 = Vector2;
  2736. /**
  2737. * Classed used to store (x,y,z) vector representation
  2738. * A Vector3 is the main object used in 3D geometry
  2739. * It can represent etiher the coordinates of a point the space, either a direction
  2740. * Reminder: Babylon.js uses a left handed forward facing system
  2741. */
  2742. var Vector3 = /** @class */ (function () {
  2743. /**
  2744. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2745. * @param x defines the first coordinates (on X axis)
  2746. * @param y defines the second coordinates (on Y axis)
  2747. * @param z defines the third coordinates (on Z axis)
  2748. */
  2749. function Vector3(
  2750. /**
  2751. * Defines the first coordinates (on X axis)
  2752. */
  2753. x,
  2754. /**
  2755. * Defines the second coordinates (on Y axis)
  2756. */
  2757. y,
  2758. /**
  2759. * Defines the third coordinates (on Z axis)
  2760. */
  2761. z) {
  2762. this.x = x;
  2763. this.y = y;
  2764. this.z = z;
  2765. }
  2766. /**
  2767. * Creates a string representation of the Vector3
  2768. * @returns a string with the Vector3 coordinates.
  2769. */
  2770. Vector3.prototype.toString = function () {
  2771. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2772. };
  2773. /**
  2774. * Gets the class name
  2775. * @returns the string "Vector3"
  2776. */
  2777. Vector3.prototype.getClassName = function () {
  2778. return "Vector3";
  2779. };
  2780. /**
  2781. * Creates the Vector3 hash code
  2782. * @returns a number which tends to be unique between Vector3 instances
  2783. */
  2784. Vector3.prototype.getHashCode = function () {
  2785. var hash = this.x || 0;
  2786. hash = (hash * 397) ^ (this.y || 0);
  2787. hash = (hash * 397) ^ (this.z || 0);
  2788. return hash;
  2789. };
  2790. // Operators
  2791. /**
  2792. * Creates an array containing three elements : the coordinates of the Vector3
  2793. * @returns a new array of numbers
  2794. */
  2795. Vector3.prototype.asArray = function () {
  2796. var result = [];
  2797. this.toArray(result, 0);
  2798. return result;
  2799. };
  2800. /**
  2801. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2802. * @param array defines the destination array
  2803. * @param index defines the offset in the destination array
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.toArray = function (array, index) {
  2807. if (index === void 0) { index = 0; }
  2808. array[index] = this.x;
  2809. array[index + 1] = this.y;
  2810. array[index + 2] = this.z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2815. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2816. */
  2817. Vector3.prototype.toQuaternion = function () {
  2818. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2819. };
  2820. /**
  2821. * Adds the given vector to the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.addInPlace = function (otherVector) {
  2826. this.x += otherVector.x;
  2827. this.y += otherVector.y;
  2828. this.z += otherVector.z;
  2829. return this;
  2830. };
  2831. /**
  2832. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2833. * @param otherVector defines the second operand
  2834. * @returns the resulting Vector3
  2835. */
  2836. Vector3.prototype.add = function (otherVector) {
  2837. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2838. };
  2839. /**
  2840. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2841. * @param otherVector defines the second operand
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.addToRef = function (otherVector, result) {
  2846. result.x = this.x + otherVector.x;
  2847. result.y = this.y + otherVector.y;
  2848. result.z = this.z + otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Subtract the given vector from the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.subtractInPlace = function (otherVector) {
  2857. this.x -= otherVector.x;
  2858. this.y -= otherVector.y;
  2859. this.z -= otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.subtract = function (otherVector) {
  2868. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2869. };
  2870. /**
  2871. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2877. result.x = this.x - otherVector.x;
  2878. result.y = this.y - otherVector.y;
  2879. result.z = this.z - otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2884. * @param x defines the x coordinate of the operand
  2885. * @param y defines the y coordinate of the operand
  2886. * @param z defines the z coordinate of the operand
  2887. * @returns the resulting Vector3
  2888. */
  2889. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2890. return new Vector3(this.x - x, this.y - y, this.z - z);
  2891. };
  2892. /**
  2893. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2894. * @param x defines the x coordinate of the operand
  2895. * @param y defines the y coordinate of the operand
  2896. * @param z defines the z coordinate of the operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2901. result.x = this.x - x;
  2902. result.y = this.y - y;
  2903. result.z = this.z - z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2908. * @returns a new Vector3
  2909. */
  2910. Vector3.prototype.negate = function () {
  2911. return new Vector3(-this.x, -this.y, -this.z);
  2912. };
  2913. /**
  2914. * Multiplies the Vector3 coordinates by the float "scale"
  2915. * @param scale defines the multiplier factor
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.scaleInPlace = function (scale) {
  2919. this.x *= scale;
  2920. this.y *= scale;
  2921. this.z *= scale;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2926. * @param scale defines the multiplier factor
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.scale = function (scale) {
  2930. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2931. };
  2932. /**
  2933. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2934. * @param scale defines the multiplier factor
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.scaleToRef = function (scale, result) {
  2939. result.x = this.x * scale;
  2940. result.y = this.y * scale;
  2941. result.z = this.z * scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2946. * @param scale defines the scale factor
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the unmodified current Vector3
  2949. */
  2950. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2951. result.x += this.x * scale;
  2952. result.y += this.y * scale;
  2953. result.z += this.z * scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2958. * @param otherVector defines the second operand
  2959. * @returns true if both vectors are equals
  2960. */
  2961. Vector3.prototype.equals = function (otherVector) {
  2962. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2963. };
  2964. /**
  2965. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2966. * @param otherVector defines the second operand
  2967. * @param epsilon defines the minimal distance to define values as equals
  2968. * @returns true if both vectors are distant less than epsilon
  2969. */
  2970. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2971. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2972. 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);
  2973. };
  2974. /**
  2975. * Returns true if the current Vector3 coordinates equals the given floats
  2976. * @param x defines the x coordinate of the operand
  2977. * @param y defines the y coordinate of the operand
  2978. * @param z defines the z coordinate of the operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2982. return this.x === x && this.y === y && this.z === z;
  2983. };
  2984. /**
  2985. * Multiplies the current Vector3 coordinates by the given ones
  2986. * @param otherVector defines the second operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2990. this.x *= otherVector.x;
  2991. this.y *= otherVector.y;
  2992. this.z *= otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2997. * @param otherVector defines the second operand
  2998. * @returns the new Vector3
  2999. */
  3000. Vector3.prototype.multiply = function (otherVector) {
  3001. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3005. * @param otherVector defines the second operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3010. result.x = this.x * otherVector.x;
  3011. result.y = this.y * otherVector.y;
  3012. result.z = this.z * otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3017. * @param x defines the x coordinate of the operand
  3018. * @param y defines the y coordinate of the operand
  3019. * @param z defines the z coordinate of the operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3023. return new Vector3(this.x * x, this.y * y, this.z * z);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3027. * @param otherVector defines the second operand
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.prototype.divide = function (otherVector) {
  3031. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3032. };
  3033. /**
  3034. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3035. * @param otherVector defines the second operand
  3036. * @param result defines the Vector3 object where to store the result
  3037. * @returns the current Vector3
  3038. */
  3039. Vector3.prototype.divideToRef = function (otherVector, result) {
  3040. result.x = this.x / otherVector.x;
  3041. result.y = this.y / otherVector.y;
  3042. result.z = this.z / otherVector.z;
  3043. return this;
  3044. };
  3045. /**
  3046. * Divides the current Vector3 coordinates by the given ones.
  3047. * @param otherVector defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.divideInPlace = function (otherVector) {
  3051. return this.divideToRef(otherVector, this);
  3052. };
  3053. /**
  3054. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3055. * @param other defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.minimizeInPlace = function (other) {
  3059. if (other.x < this.x)
  3060. this.x = other.x;
  3061. if (other.y < this.y)
  3062. this.y = other.y;
  3063. if (other.z < this.z)
  3064. this.z = other.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3069. * @param other defines the second operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.maximizeInPlace = function (other) {
  3073. if (other.x > this.x)
  3074. this.x = other.x;
  3075. if (other.y > this.y)
  3076. this.y = other.y;
  3077. if (other.z > this.z)
  3078. this.z = other.z;
  3079. return this;
  3080. };
  3081. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3082. /**
  3083. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3084. */
  3085. get: function () {
  3086. var absX = Math.abs(this.x);
  3087. var absY = Math.abs(this.y);
  3088. if (absX !== absY) {
  3089. return true;
  3090. }
  3091. var absZ = Math.abs(this.z);
  3092. if (absX !== absZ) {
  3093. return true;
  3094. }
  3095. if (absY !== absZ) {
  3096. return true;
  3097. }
  3098. return false;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. // Properties
  3104. /**
  3105. * Gets the length of the Vector3
  3106. * @returns the length of the Vecto3
  3107. */
  3108. Vector3.prototype.length = function () {
  3109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Gets the squared length of the Vector3
  3113. * @returns squared length of the Vector3
  3114. */
  3115. Vector3.prototype.lengthSquared = function () {
  3116. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3117. };
  3118. /**
  3119. * Normalize the current Vector3.
  3120. * Please note that this is an in place operation.
  3121. * @returns the current updated Vector3
  3122. */
  3123. Vector3.prototype.normalize = function () {
  3124. var len = this.length();
  3125. if (len === 0 || len === 1.0)
  3126. return this;
  3127. var num = 1.0 / len;
  3128. this.x *= num;
  3129. this.y *= num;
  3130. this.z *= num;
  3131. return this;
  3132. };
  3133. /**
  3134. * Normalize the current Vector3 to a new vector
  3135. * @returns the new Vector3
  3136. */
  3137. Vector3.prototype.normalizeToNew = function () {
  3138. var normalized = new Vector3(0, 0, 0);
  3139. this.normalizeToRef(normalized);
  3140. return normalized;
  3141. };
  3142. /**
  3143. * Normalize the current Vector3 to the reference
  3144. * @param reference define the Vector3 to update
  3145. * @returns the updated Vector3
  3146. */
  3147. Vector3.prototype.normalizeToRef = function (reference) {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0) {
  3150. reference.set(this.x, this.y, this.z);
  3151. return reference;
  3152. }
  3153. var scale = 1.0 / len;
  3154. this.scaleToRef(scale, reference);
  3155. return reference;
  3156. };
  3157. /**
  3158. * Creates a new Vector3 copied from the current Vector3
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.clone = function () {
  3162. return new Vector3(this.x, this.y, this.z);
  3163. };
  3164. /**
  3165. * Copies the given vector coordinates to the current Vector3 ones
  3166. * @param source defines the source Vector3
  3167. * @returns the current updated Vector3
  3168. */
  3169. Vector3.prototype.copyFrom = function (source) {
  3170. this.x = source.x;
  3171. this.y = source.y;
  3172. this.z = source.z;
  3173. return this;
  3174. };
  3175. /**
  3176. * Copies the given floats to the current Vector3 coordinates
  3177. * @param x defines the x coordinate of the operand
  3178. * @param y defines the y coordinate of the operand
  3179. * @param z defines the z coordinate of the operand
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3183. this.x = x;
  3184. this.y = y;
  3185. this.z = z;
  3186. return this;
  3187. };
  3188. /**
  3189. * Copies the given floats to the current Vector3 coordinates
  3190. * @param x defines the x coordinate of the operand
  3191. * @param y defines the y coordinate of the operand
  3192. * @param z defines the z coordinate of the operand
  3193. * @returns the current updated Vector3
  3194. */
  3195. Vector3.prototype.set = function (x, y, z) {
  3196. return this.copyFromFloats(x, y, z);
  3197. };
  3198. // Statics
  3199. /**
  3200. * Get the clip factor between two vectors
  3201. * @param vector0 defines the first operand
  3202. * @param vector1 defines the second operand
  3203. * @param axis defines the axis to use
  3204. * @param size defines the size along the axis
  3205. * @returns the clip factor
  3206. */
  3207. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3208. var d0 = Vector3.Dot(vector0, axis) - size;
  3209. var d1 = Vector3.Dot(vector1, axis) - size;
  3210. var s = d0 / (d0 - d1);
  3211. return s;
  3212. };
  3213. /**
  3214. * Get angle between two vectors
  3215. * @param vector0 angle between vector0 and vector1
  3216. * @param vector1 angle between vector0 and vector1
  3217. * @param normal direction of the normal
  3218. * @return the angle between vector0 and vector1
  3219. */
  3220. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3221. var v0 = vector0.clone().normalize();
  3222. var v1 = vector1.clone().normalize();
  3223. var dot = Vector3.Dot(v0, v1);
  3224. var n = Vector3.Cross(v0, v1);
  3225. if (Vector3.Dot(n, normal) > 0) {
  3226. return Math.acos(dot);
  3227. }
  3228. return -Math.acos(dot);
  3229. };
  3230. /**
  3231. * Returns a new Vector3 set from the index "offset" of the given array
  3232. * @param array defines the source array
  3233. * @param offset defines the offset in the source array
  3234. * @returns the new Vector3
  3235. */
  3236. Vector3.FromArray = function (array, offset) {
  3237. if (!offset) {
  3238. offset = 0;
  3239. }
  3240. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3241. };
  3242. /**
  3243. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3244. * This function is deprecated. Use FromArray instead
  3245. * @param array defines the source array
  3246. * @param offset defines the offset in the source array
  3247. * @returns the new Vector3
  3248. */
  3249. Vector3.FromFloatArray = function (array, offset) {
  3250. return Vector3.FromArray(array, offset);
  3251. };
  3252. /**
  3253. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3254. * @param array defines the source array
  3255. * @param offset defines the offset in the source array
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.FromArrayToRef = function (array, offset, result) {
  3259. result.x = array[offset];
  3260. result.y = array[offset + 1];
  3261. result.z = array[offset + 2];
  3262. };
  3263. /**
  3264. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3265. * This function is deprecated. Use FromArrayToRef instead.
  3266. * @param array defines the source array
  3267. * @param offset defines the offset in the source array
  3268. * @param result defines the Vector3 where to store the result
  3269. */
  3270. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3271. return Vector3.FromArrayToRef(array, offset, result);
  3272. };
  3273. /**
  3274. * Sets the given vector "result" with the given floats.
  3275. * @param x defines the x coordinate of the source
  3276. * @param y defines the y coordinate of the source
  3277. * @param z defines the z coordinate of the source
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3281. result.x = x;
  3282. result.y = y;
  3283. result.z = z;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3287. * @returns a new empty Vector3
  3288. */
  3289. Vector3.Zero = function () {
  3290. return new Vector3(0.0, 0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3294. * @returns a new unit Vector3
  3295. */
  3296. Vector3.One = function () {
  3297. return new Vector3(1.0, 1.0, 1.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3301. * @returns a new up Vector3
  3302. */
  3303. Vector3.Up = function () {
  3304. return new Vector3(0.0, 1.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3308. * @returns a new down Vector3
  3309. */
  3310. Vector3.Down = function () {
  3311. return new Vector3(0.0, -1.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3315. * @returns a new forward Vector3
  3316. */
  3317. Vector3.Forward = function () {
  3318. return new Vector3(0.0, 0.0, 1.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3322. * @returns a new right Vector3
  3323. */
  3324. Vector3.Right = function () {
  3325. return new Vector3(1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3329. * @returns a new left Vector3
  3330. */
  3331. Vector3.Left = function () {
  3332. return new Vector3(-1.0, 0.0, 0.0);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3336. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3337. * @param vector defines the Vector3 to transform
  3338. * @param transformation defines the transformation matrix
  3339. * @returns the transformed Vector3
  3340. */
  3341. Vector3.TransformCoordinates = function (vector, transformation) {
  3342. var result = Vector3.Zero();
  3343. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3344. return result;
  3345. };
  3346. /**
  3347. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3348. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3349. * @param vector defines the Vector3 to transform
  3350. * @param transformation defines the transformation matrix
  3351. * @param result defines the Vector3 where to store the result
  3352. */
  3353. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3354. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3355. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3356. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3357. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3358. result.x = x / w;
  3359. result.y = y / w;
  3360. result.z = z / w;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3364. * This method computes tranformed coordinates only, not transformed direction vectors
  3365. * @param x define the x coordinate of the source vector
  3366. * @param y define the y coordinate of the source vector
  3367. * @param z define the z coordinate of the source vector
  3368. * @param transformation defines the transformation matrix
  3369. * @param result defines the Vector3 where to store the result
  3370. */
  3371. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3372. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3373. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3374. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3375. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3376. result.x = rx / rw;
  3377. result.y = ry / rw;
  3378. result.z = rz / rw;
  3379. };
  3380. /**
  3381. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3382. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3383. * @param vector defines the Vector3 to transform
  3384. * @param transformation defines the transformation matrix
  3385. * @returns the new Vector3
  3386. */
  3387. Vector3.TransformNormal = function (vector, transformation) {
  3388. var result = Vector3.Zero();
  3389. Vector3.TransformNormalToRef(vector, transformation, result);
  3390. return result;
  3391. };
  3392. /**
  3393. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3394. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3395. * @param vector defines the Vector3 to transform
  3396. * @param transformation defines the transformation matrix
  3397. * @param result defines the Vector3 where to store the result
  3398. */
  3399. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3400. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3401. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3402. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3403. result.x = x;
  3404. result.y = y;
  3405. result.z = z;
  3406. };
  3407. /**
  3408. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3409. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3410. * @param x define the x coordinate of the source vector
  3411. * @param y define the y coordinate of the source vector
  3412. * @param z define the z coordinate of the source vector
  3413. * @param transformation defines the transformation matrix
  3414. * @param result defines the Vector3 where to store the result
  3415. */
  3416. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3417. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3418. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3419. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3423. * @param value1 defines the first control point
  3424. * @param value2 defines the second control point
  3425. * @param value3 defines the third control point
  3426. * @param value4 defines the fourth control point
  3427. * @param amount defines the amount on the spline to use
  3428. * @returns the new Vector3
  3429. */
  3430. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3431. var squared = amount * amount;
  3432. var cubed = amount * squared;
  3433. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3434. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3435. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3436. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3437. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3438. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3439. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3440. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3441. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3442. return new Vector3(x, y, z);
  3443. };
  3444. /**
  3445. * 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"
  3446. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3447. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3448. * @param value defines the current value
  3449. * @param min defines the lower range value
  3450. * @param max defines the upper range value
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Clamp = function (value, min, max) {
  3454. var x = value.x;
  3455. x = (x > max.x) ? max.x : x;
  3456. x = (x < min.x) ? min.x : x;
  3457. var y = value.y;
  3458. y = (y > max.y) ? max.y : y;
  3459. y = (y < min.y) ? min.y : y;
  3460. var z = value.z;
  3461. z = (z > max.z) ? max.z : z;
  3462. z = (z < min.z) ? min.z : z;
  3463. return new Vector3(x, y, z);
  3464. };
  3465. /**
  3466. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3467. * @param value1 defines the first control point
  3468. * @param tangent1 defines the first tangent vector
  3469. * @param value2 defines the second control point
  3470. * @param tangent2 defines the second tangent vector
  3471. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3475. var squared = amount * amount;
  3476. var cubed = amount * squared;
  3477. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3478. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3479. var part3 = (cubed - (2.0 * squared)) + amount;
  3480. var part4 = cubed - squared;
  3481. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3482. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3483. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3484. return new Vector3(x, y, z);
  3485. };
  3486. /**
  3487. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3488. * @param start defines the start value
  3489. * @param end defines the end value
  3490. * @param amount max defines amount between both (between 0 and 1)
  3491. * @returns the new Vector3
  3492. */
  3493. Vector3.Lerp = function (start, end, amount) {
  3494. var result = new Vector3(0, 0, 0);
  3495. Vector3.LerpToRef(start, end, amount, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3500. * @param start defines the start value
  3501. * @param end defines the end value
  3502. * @param amount max defines amount between both (between 0 and 1)
  3503. * @param result defines the Vector3 where to store the result
  3504. */
  3505. Vector3.LerpToRef = function (start, end, amount, result) {
  3506. result.x = start.x + ((end.x - start.x) * amount);
  3507. result.y = start.y + ((end.y - start.y) * amount);
  3508. result.z = start.z + ((end.z - start.z) * amount);
  3509. };
  3510. /**
  3511. * Returns the dot product (float) between the vectors "left" and "right"
  3512. * @param left defines the left operand
  3513. * @param right defines the right operand
  3514. * @returns the dot product
  3515. */
  3516. Vector3.Dot = function (left, right) {
  3517. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3518. };
  3519. /**
  3520. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3521. * The cross product is then orthogonal to both "left" and "right"
  3522. * @param left defines the left operand
  3523. * @param right defines the right operand
  3524. * @returns the cross product
  3525. */
  3526. Vector3.Cross = function (left, right) {
  3527. var result = Vector3.Zero();
  3528. Vector3.CrossToRef(left, right, result);
  3529. return result;
  3530. };
  3531. /**
  3532. * Sets the given vector "result" with the cross product of "left" and "right"
  3533. * The cross product is then orthogonal to both "left" and "right"
  3534. * @param left defines the left operand
  3535. * @param right defines the right operand
  3536. * @param result defines the Vector3 where to store the result
  3537. */
  3538. Vector3.CrossToRef = function (left, right, result) {
  3539. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3540. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3541. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3542. result.copyFrom(MathTmp.Vector3[0]);
  3543. };
  3544. /**
  3545. * Returns a new Vector3 as the normalization of the given vector
  3546. * @param vector defines the Vector3 to normalize
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.Normalize = function (vector) {
  3550. var result = Vector3.Zero();
  3551. Vector3.NormalizeToRef(vector, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the normalization of the given first vector
  3556. * @param vector defines the Vector3 to normalize
  3557. * @param result defines the Vector3 where to store the result
  3558. */
  3559. Vector3.NormalizeToRef = function (vector, result) {
  3560. result.copyFrom(vector);
  3561. result.normalize();
  3562. };
  3563. /**
  3564. * Project a Vector3 onto screen space
  3565. * @param vector defines the Vector3 to project
  3566. * @param world defines the world matrix to use
  3567. * @param transform defines the transform (view x projection) matrix to use
  3568. * @param viewport defines the screen viewport to use
  3569. * @returns the new Vector3
  3570. */
  3571. Vector3.Project = function (vector, world, transform, viewport) {
  3572. var cw = viewport.width;
  3573. var ch = viewport.height;
  3574. var cx = viewport.x;
  3575. var cy = viewport.y;
  3576. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3577. 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);
  3578. var matrix = MathTmp.Matrix[0];
  3579. world.multiplyToRef(transform, matrix);
  3580. matrix.multiplyToRef(viewportMatrix, matrix);
  3581. return Vector3.TransformCoordinates(vector, matrix);
  3582. };
  3583. /**
  3584. * Unproject from screen space to object space
  3585. * @param source defines the screen space Vector3 to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param transform defines the transform (view x projection) matrix to use
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3593. var matrix = MathTmp.Matrix[0];
  3594. world.multiplyToRef(transform, matrix);
  3595. matrix.invert();
  3596. source.x = source.x / viewportWidth * 2 - 1;
  3597. source.y = -(source.y / viewportHeight * 2 - 1);
  3598. var vector = Vector3.TransformCoordinates(source, matrix);
  3599. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3600. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3601. vector = vector.scale(1.0 / num);
  3602. }
  3603. return vector;
  3604. };
  3605. /**
  3606. * Unproject from screen space to object space
  3607. * @param source defines the screen space Vector3 to use
  3608. * @param viewportWidth defines the current width of the viewport
  3609. * @param viewportHeight defines the current height of the viewport
  3610. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3611. * @param view defines the view matrix to use
  3612. * @param projection defines the projection matrix to use
  3613. * @returns the new Vector3
  3614. */
  3615. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3616. var result = Vector3.Zero();
  3617. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3618. return result;
  3619. };
  3620. /**
  3621. * Unproject from screen space to object space
  3622. * @param source defines the screen space Vector3 to use
  3623. * @param viewportWidth defines the current width of the viewport
  3624. * @param viewportHeight defines the current height of the viewport
  3625. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3626. * @param view defines the view matrix to use
  3627. * @param projection defines the projection matrix to use
  3628. * @param result defines the Vector3 where to store the result
  3629. */
  3630. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3631. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3632. };
  3633. /**
  3634. * Unproject from screen space to object space
  3635. * @param sourceX defines the screen space x coordinate to use
  3636. * @param sourceY defines the screen space y coordinate to use
  3637. * @param sourceZ defines the screen space z coordinate to use
  3638. * @param viewportWidth defines the current width of the viewport
  3639. * @param viewportHeight defines the current height of the viewport
  3640. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3641. * @param view defines the view matrix to use
  3642. * @param projection defines the projection matrix to use
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3646. var matrix = MathTmp.Matrix[0];
  3647. world.multiplyToRef(view, matrix);
  3648. matrix.multiplyToRef(projection, matrix);
  3649. matrix.invert();
  3650. var screenSource = MathTmp.Vector3[0];
  3651. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3652. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3653. screenSource.z = 2 * sourceZ - 1.0;
  3654. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3655. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3656. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3657. result.scaleInPlace(1.0 / num);
  3658. }
  3659. };
  3660. /**
  3661. * Gets the minimal 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.Minimize = function (left, right) {
  3667. var min = left.clone();
  3668. min.minimizeInPlace(right);
  3669. return min;
  3670. };
  3671. /**
  3672. * Gets the maximal coordinate values between two Vector3
  3673. * @param left defines the first operand
  3674. * @param right defines the second operand
  3675. * @returns the new Vector3
  3676. */
  3677. Vector3.Maximize = function (left, right) {
  3678. var max = left.clone();
  3679. max.maximizeInPlace(right);
  3680. return max;
  3681. };
  3682. /**
  3683. * Returns the distance between the vectors "value1" and "value2"
  3684. * @param value1 defines the first operand
  3685. * @param value2 defines the second operand
  3686. * @returns the distance
  3687. */
  3688. Vector3.Distance = function (value1, value2) {
  3689. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3690. };
  3691. /**
  3692. * Returns the squared distance between the vectors "value1" and "value2"
  3693. * @param value1 defines the first operand
  3694. * @param value2 defines the second operand
  3695. * @returns the squared distance
  3696. */
  3697. Vector3.DistanceSquared = function (value1, value2) {
  3698. var x = value1.x - value2.x;
  3699. var y = value1.y - value2.y;
  3700. var z = value1.z - value2.z;
  3701. return (x * x) + (y * y) + (z * z);
  3702. };
  3703. /**
  3704. * Returns a new Vector3 located at the center between "value1" and "value2"
  3705. * @param value1 defines the first operand
  3706. * @param value2 defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Center = function (value1, value2) {
  3710. var center = value1.add(value2);
  3711. center.scaleInPlace(0.5);
  3712. return center;
  3713. };
  3714. /**
  3715. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3716. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3717. * to something in order to rotate it from its local system to the given target system
  3718. * Note: axis1, axis2 and axis3 are normalized during this operation
  3719. * @param axis1 defines the first axis
  3720. * @param axis2 defines the second axis
  3721. * @param axis3 defines the third axis
  3722. * @returns a new Vector3
  3723. */
  3724. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3725. var rotation = Vector3.Zero();
  3726. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3727. return rotation;
  3728. };
  3729. /**
  3730. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3731. * @param axis1 defines the first axis
  3732. * @param axis2 defines the second axis
  3733. * @param axis3 defines the third axis
  3734. * @param ref defines the Vector3 where to store the result
  3735. */
  3736. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3737. var quat = MathTmp.Quaternion[0];
  3738. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3739. quat.toEulerAnglesToRef(ref);
  3740. };
  3741. return Vector3;
  3742. }());
  3743. BABYLON.Vector3 = Vector3;
  3744. //Vector4 class created for EulerAngle class conversion to Quaternion
  3745. var Vector4 = /** @class */ (function () {
  3746. /**
  3747. * Creates a Vector4 object from the given floats.
  3748. */
  3749. function Vector4(x, y, z, w) {
  3750. this.x = x;
  3751. this.y = y;
  3752. this.z = z;
  3753. this.w = w;
  3754. }
  3755. /**
  3756. * Returns the string with the Vector4 coordinates.
  3757. */
  3758. Vector4.prototype.toString = function () {
  3759. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3760. };
  3761. /**
  3762. * Returns the string "Vector4".
  3763. */
  3764. Vector4.prototype.getClassName = function () {
  3765. return "Vector4";
  3766. };
  3767. /**
  3768. * Returns the Vector4 hash code.
  3769. */
  3770. Vector4.prototype.getHashCode = function () {
  3771. var hash = this.x || 0;
  3772. hash = (hash * 397) ^ (this.y || 0);
  3773. hash = (hash * 397) ^ (this.z || 0);
  3774. hash = (hash * 397) ^ (this.w || 0);
  3775. return hash;
  3776. };
  3777. // Operators
  3778. /**
  3779. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3780. */
  3781. Vector4.prototype.asArray = function () {
  3782. var result = new Array();
  3783. this.toArray(result, 0);
  3784. return result;
  3785. };
  3786. /**
  3787. * Populates the given array from the given index with the Vector4 coordinates.
  3788. * Returns the Vector4.
  3789. */
  3790. Vector4.prototype.toArray = function (array, index) {
  3791. if (index === undefined) {
  3792. index = 0;
  3793. }
  3794. array[index] = this.x;
  3795. array[index + 1] = this.y;
  3796. array[index + 2] = this.z;
  3797. array[index + 3] = this.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Adds the given vector to the current Vector4.
  3802. * Returns the updated Vector4.
  3803. */
  3804. Vector4.prototype.addInPlace = function (otherVector) {
  3805. this.x += otherVector.x;
  3806. this.y += otherVector.y;
  3807. this.z += otherVector.z;
  3808. this.w += otherVector.w;
  3809. return this;
  3810. };
  3811. /**
  3812. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3813. */
  3814. Vector4.prototype.add = function (otherVector) {
  3815. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3816. };
  3817. /**
  3818. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3819. * Returns the current Vector4.
  3820. */
  3821. Vector4.prototype.addToRef = function (otherVector, result) {
  3822. result.x = this.x + otherVector.x;
  3823. result.y = this.y + otherVector.y;
  3824. result.z = this.z + otherVector.z;
  3825. result.w = this.w + otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Subtract in place the given vector from the current Vector4.
  3830. * Returns the updated Vector4.
  3831. */
  3832. Vector4.prototype.subtractInPlace = function (otherVector) {
  3833. this.x -= otherVector.x;
  3834. this.y -= otherVector.y;
  3835. this.z -= otherVector.z;
  3836. this.w -= otherVector.w;
  3837. return this;
  3838. };
  3839. /**
  3840. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3841. */
  3842. Vector4.prototype.subtract = function (otherVector) {
  3843. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3844. };
  3845. /**
  3846. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3847. * Returns the current Vector4.
  3848. */
  3849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3850. result.x = this.x - otherVector.x;
  3851. result.y = this.y - otherVector.y;
  3852. result.z = this.z - otherVector.z;
  3853. result.w = this.w - otherVector.w;
  3854. return this;
  3855. };
  3856. /**
  3857. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3858. */
  3859. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3860. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3861. };
  3862. /**
  3863. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3864. * Returns the current Vector4.
  3865. */
  3866. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3867. result.x = this.x - x;
  3868. result.y = this.y - y;
  3869. result.z = this.z - z;
  3870. result.w = this.w - w;
  3871. return this;
  3872. };
  3873. /**
  3874. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3875. */
  3876. Vector4.prototype.negate = function () {
  3877. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3878. };
  3879. /**
  3880. * Multiplies the current Vector4 coordinates by scale (float).
  3881. * Returns the updated Vector4.
  3882. */
  3883. Vector4.prototype.scaleInPlace = function (scale) {
  3884. this.x *= scale;
  3885. this.y *= scale;
  3886. this.z *= scale;
  3887. this.w *= scale;
  3888. return this;
  3889. };
  3890. /**
  3891. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3892. */
  3893. Vector4.prototype.scale = function (scale) {
  3894. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3895. };
  3896. /**
  3897. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3898. * Returns the current Vector4.
  3899. */
  3900. Vector4.prototype.scaleToRef = function (scale, result) {
  3901. result.x = this.x * scale;
  3902. result.y = this.y * scale;
  3903. result.z = this.z * scale;
  3904. result.w = this.w * scale;
  3905. return this;
  3906. };
  3907. /**
  3908. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3909. * @param scale defines the scale factor
  3910. * @param result defines the Vector4 object where to store the result
  3911. * @returns the unmodified current Vector4
  3912. */
  3913. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3914. result.x += this.x * scale;
  3915. result.y += this.y * scale;
  3916. result.z += this.z * scale;
  3917. result.w += this.w * scale;
  3918. return this;
  3919. };
  3920. /**
  3921. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3922. */
  3923. Vector4.prototype.equals = function (otherVector) {
  3924. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3925. };
  3926. /**
  3927. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3928. */
  3929. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3930. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3931. return otherVector
  3932. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3933. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3934. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3935. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3936. };
  3937. /**
  3938. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3939. */
  3940. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3941. return this.x === x && this.y === y && this.z === z && this.w === w;
  3942. };
  3943. /**
  3944. * Multiplies in place the current Vector4 by the given one.
  3945. * Returns the updated Vector4.
  3946. */
  3947. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3948. this.x *= otherVector.x;
  3949. this.y *= otherVector.y;
  3950. this.z *= otherVector.z;
  3951. this.w *= otherVector.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3956. */
  3957. Vector4.prototype.multiply = function (otherVector) {
  3958. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3959. };
  3960. /**
  3961. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3962. * Returns the current Vector4.
  3963. */
  3964. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3965. result.x = this.x * otherVector.x;
  3966. result.y = this.y * otherVector.y;
  3967. result.z = this.z * otherVector.z;
  3968. result.w = this.w * otherVector.w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3973. */
  3974. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3975. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3979. */
  3980. Vector4.prototype.divide = function (otherVector) {
  3981. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3982. };
  3983. /**
  3984. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3985. * Returns the current Vector4.
  3986. */
  3987. Vector4.prototype.divideToRef = function (otherVector, result) {
  3988. result.x = this.x / otherVector.x;
  3989. result.y = this.y / otherVector.y;
  3990. result.z = this.z / otherVector.z;
  3991. result.w = this.w / otherVector.w;
  3992. return this;
  3993. };
  3994. /**
  3995. * Divides the current Vector3 coordinates by the given ones.
  3996. * @returns the updated Vector3.
  3997. */
  3998. Vector4.prototype.divideInPlace = function (otherVector) {
  3999. return this.divideToRef(otherVector, this);
  4000. };
  4001. /**
  4002. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4003. * @param other defines the second operand
  4004. * @returns the current updated Vector4
  4005. */
  4006. Vector4.prototype.minimizeInPlace = function (other) {
  4007. if (other.x < this.x)
  4008. this.x = other.x;
  4009. if (other.y < this.y)
  4010. this.y = other.y;
  4011. if (other.z < this.z)
  4012. this.z = other.z;
  4013. if (other.w < this.w)
  4014. this.w = other.w;
  4015. return this;
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.maximizeInPlace = function (other) {
  4023. if (other.x > this.x)
  4024. this.x = other.x;
  4025. if (other.y > this.y)
  4026. this.y = other.y;
  4027. if (other.z > this.z)
  4028. this.z = other.z;
  4029. if (other.w > this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. // Properties
  4034. /**
  4035. * Returns the Vector4 length (float).
  4036. */
  4037. Vector4.prototype.length = function () {
  4038. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4039. };
  4040. /**
  4041. * Returns the Vector4 squared length (float).
  4042. */
  4043. Vector4.prototype.lengthSquared = function () {
  4044. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4045. };
  4046. // Methods
  4047. /**
  4048. * Normalizes in place the Vector4.
  4049. * Returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.normalize = function () {
  4052. var len = this.length();
  4053. if (len === 0)
  4054. return this;
  4055. var num = 1.0 / len;
  4056. this.x *= num;
  4057. this.y *= num;
  4058. this.z *= num;
  4059. this.w *= num;
  4060. return this;
  4061. };
  4062. /**
  4063. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4064. */
  4065. Vector4.prototype.toVector3 = function () {
  4066. return new Vector3(this.x, this.y, this.z);
  4067. };
  4068. /**
  4069. * Returns a new Vector4 copied from the current one.
  4070. */
  4071. Vector4.prototype.clone = function () {
  4072. return new Vector4(this.x, this.y, this.z, this.w);
  4073. };
  4074. /**
  4075. * Updates the current Vector4 with the given one coordinates.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFrom = function (source) {
  4079. this.x = source.x;
  4080. this.y = source.y;
  4081. this.z = source.z;
  4082. this.w = source.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.copyFromFloats = function (x, y, z, w) {
  4090. this.x = x;
  4091. this.y = y;
  4092. this.z = z;
  4093. this.w = w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Updates the current Vector4 coordinates with the given floats.
  4098. * Returns the updated Vector4.
  4099. */
  4100. Vector4.prototype.set = function (x, y, z, w) {
  4101. return this.copyFromFloats(x, y, z, w);
  4102. };
  4103. // Statics
  4104. /**
  4105. * Returns a new Vector4 set from the starting index of the given array.
  4106. */
  4107. Vector4.FromArray = function (array, offset) {
  4108. if (!offset) {
  4109. offset = 0;
  4110. }
  4111. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4112. };
  4113. /**
  4114. * Updates the given vector "result" from the starting index of the given array.
  4115. */
  4116. Vector4.FromArrayToRef = function (array, offset, result) {
  4117. result.x = array[offset];
  4118. result.y = array[offset + 1];
  4119. result.z = array[offset + 2];
  4120. result.w = array[offset + 3];
  4121. };
  4122. /**
  4123. * Updates the given vector "result" from the starting index of the given Float32Array.
  4124. */
  4125. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4126. Vector4.FromArrayToRef(array, offset, result);
  4127. };
  4128. /**
  4129. * Updates the given vector "result" coordinates from the given floats.
  4130. */
  4131. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4132. result.x = x;
  4133. result.y = y;
  4134. result.z = z;
  4135. result.w = w;
  4136. };
  4137. /**
  4138. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4139. */
  4140. Vector4.Zero = function () {
  4141. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4142. };
  4143. /**
  4144. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4145. */
  4146. Vector4.One = function () {
  4147. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4148. };
  4149. /**
  4150. * Returns a new normalized Vector4 from the given one.
  4151. */
  4152. Vector4.Normalize = function (vector) {
  4153. var result = Vector4.Zero();
  4154. Vector4.NormalizeToRef(vector, result);
  4155. return result;
  4156. };
  4157. /**
  4158. * Updates the given vector "result" from the normalization of the given one.
  4159. */
  4160. Vector4.NormalizeToRef = function (vector, result) {
  4161. result.copyFrom(vector);
  4162. result.normalize();
  4163. };
  4164. Vector4.Minimize = function (left, right) {
  4165. var min = left.clone();
  4166. min.minimizeInPlace(right);
  4167. return min;
  4168. };
  4169. Vector4.Maximize = function (left, right) {
  4170. var max = left.clone();
  4171. max.maximizeInPlace(right);
  4172. return max;
  4173. };
  4174. /**
  4175. * Returns the distance (float) between the vectors "value1" and "value2".
  4176. */
  4177. Vector4.Distance = function (value1, value2) {
  4178. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4179. };
  4180. /**
  4181. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4182. */
  4183. Vector4.DistanceSquared = function (value1, value2) {
  4184. var x = value1.x - value2.x;
  4185. var y = value1.y - value2.y;
  4186. var z = value1.z - value2.z;
  4187. var w = value1.w - value2.w;
  4188. return (x * x) + (y * y) + (z * z) + (w * w);
  4189. };
  4190. /**
  4191. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Center = function (value1, value2) {
  4194. var center = value1.add(value2);
  4195. center.scaleInPlace(0.5);
  4196. return center;
  4197. };
  4198. /**
  4199. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4200. * This methods computes transformed normalized direction vectors only.
  4201. */
  4202. Vector4.TransformNormal = function (vector, transformation) {
  4203. var result = Vector4.Zero();
  4204. Vector4.TransformNormalToRef(vector, transformation, result);
  4205. return result;
  4206. };
  4207. /**
  4208. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4209. * This methods computes transformed normalized direction vectors only.
  4210. */
  4211. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4212. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4213. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4214. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4215. result.x = x;
  4216. result.y = y;
  4217. result.z = z;
  4218. result.w = vector.w;
  4219. };
  4220. /**
  4221. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4222. * This methods computes transformed normalized direction vectors only.
  4223. */
  4224. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4225. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4226. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4227. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4228. result.w = w;
  4229. };
  4230. return Vector4;
  4231. }());
  4232. BABYLON.Vector4 = Vector4;
  4233. var Size = /** @class */ (function () {
  4234. /**
  4235. * Creates a Size object from the given width and height (floats).
  4236. */
  4237. function Size(width, height) {
  4238. this.width = width;
  4239. this.height = height;
  4240. }
  4241. // Returns a string with the Size width and height.
  4242. Size.prototype.toString = function () {
  4243. return "{W: " + this.width + ", H: " + this.height + "}";
  4244. };
  4245. /**
  4246. * Returns the string "Size"
  4247. */
  4248. Size.prototype.getClassName = function () {
  4249. return "Size";
  4250. };
  4251. /**
  4252. * Returns the Size hash code.
  4253. */
  4254. Size.prototype.getHashCode = function () {
  4255. var hash = this.width || 0;
  4256. hash = (hash * 397) ^ (this.height || 0);
  4257. return hash;
  4258. };
  4259. /**
  4260. * Updates the current size from the given one.
  4261. * Returns the updated Size.
  4262. */
  4263. Size.prototype.copyFrom = function (src) {
  4264. this.width = src.width;
  4265. this.height = src.height;
  4266. };
  4267. /**
  4268. * Updates in place the current Size from the given floats.
  4269. * Returns the updated Size.
  4270. */
  4271. Size.prototype.copyFromFloats = function (width, height) {
  4272. this.width = width;
  4273. this.height = height;
  4274. return this;
  4275. };
  4276. /**
  4277. * Updates in place the current Size from the given floats.
  4278. * Returns the updated Size.
  4279. */
  4280. Size.prototype.set = function (width, height) {
  4281. return this.copyFromFloats(width, height);
  4282. };
  4283. /**
  4284. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4285. */
  4286. Size.prototype.multiplyByFloats = function (w, h) {
  4287. return new Size(this.width * w, this.height * h);
  4288. };
  4289. /**
  4290. * Returns a new Size copied from the given one.
  4291. */
  4292. Size.prototype.clone = function () {
  4293. return new Size(this.width, this.height);
  4294. };
  4295. /**
  4296. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4297. */
  4298. Size.prototype.equals = function (other) {
  4299. if (!other) {
  4300. return false;
  4301. }
  4302. return (this.width === other.width) && (this.height === other.height);
  4303. };
  4304. Object.defineProperty(Size.prototype, "surface", {
  4305. /**
  4306. * Returns the surface of the Size : width * height (float).
  4307. */
  4308. get: function () {
  4309. return this.width * this.height;
  4310. },
  4311. enumerable: true,
  4312. configurable: true
  4313. });
  4314. /**
  4315. * Returns a new Size set to (0.0, 0.0)
  4316. */
  4317. Size.Zero = function () {
  4318. return new Size(0.0, 0.0);
  4319. };
  4320. /**
  4321. * Returns a new Size set as the addition result of the current Size and the given one.
  4322. */
  4323. Size.prototype.add = function (otherSize) {
  4324. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4325. return r;
  4326. };
  4327. /**
  4328. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4329. */
  4330. Size.prototype.subtract = function (otherSize) {
  4331. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4332. return r;
  4333. };
  4334. /**
  4335. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4336. */
  4337. Size.Lerp = function (start, end, amount) {
  4338. var w = start.width + ((end.width - start.width) * amount);
  4339. var h = start.height + ((end.height - start.height) * amount);
  4340. return new Size(w, h);
  4341. };
  4342. return Size;
  4343. }());
  4344. BABYLON.Size = Size;
  4345. /**
  4346. * Class used to store quaternion data
  4347. * @see https://en.wikipedia.org/wiki/Quaternion
  4348. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4349. */
  4350. var Quaternion = /** @class */ (function () {
  4351. /**
  4352. * Creates a new Quaternion from the given floats
  4353. * @param x defines the first component (0 by default)
  4354. * @param y defines the second component (0 by default)
  4355. * @param z defines the third component (0 by default)
  4356. * @param w defines the fourth component (1.0 by default)
  4357. */
  4358. function Quaternion(
  4359. /** defines the first component (0 by default) */
  4360. x,
  4361. /** defines the second component (0 by default) */
  4362. y,
  4363. /** defines the third component (0 by default) */
  4364. z,
  4365. /** defines the fourth component (1.0 by default) */
  4366. w) {
  4367. if (x === void 0) { x = 0.0; }
  4368. if (y === void 0) { y = 0.0; }
  4369. if (z === void 0) { z = 0.0; }
  4370. if (w === void 0) { w = 1.0; }
  4371. this.x = x;
  4372. this.y = y;
  4373. this.z = z;
  4374. this.w = w;
  4375. }
  4376. /**
  4377. * Gets a string representation for the current quaternion
  4378. * @returns a string with the Quaternion coordinates
  4379. */
  4380. Quaternion.prototype.toString = function () {
  4381. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4382. };
  4383. /**
  4384. * Gets the class name of the quaternion
  4385. * @returns the string "Quaternion"
  4386. */
  4387. Quaternion.prototype.getClassName = function () {
  4388. return "Quaternion";
  4389. };
  4390. /**
  4391. * Gets a hash code for this quaternion
  4392. * @returns the quaternion hash code
  4393. */
  4394. Quaternion.prototype.getHashCode = function () {
  4395. var hash = this.x || 0;
  4396. hash = (hash * 397) ^ (this.y || 0);
  4397. hash = (hash * 397) ^ (this.z || 0);
  4398. hash = (hash * 397) ^ (this.w || 0);
  4399. return hash;
  4400. };
  4401. /**
  4402. * Copy the quaternion to an array
  4403. * @returns a new array populated with 4 elements from the quaternion coordinates
  4404. */
  4405. Quaternion.prototype.asArray = function () {
  4406. return [this.x, this.y, this.z, this.w];
  4407. };
  4408. /**
  4409. * Check if two quaternions are equals
  4410. * @param otherQuaternion defines the second operand
  4411. * @return true if the current quaternion and the given one coordinates are strictly equals
  4412. */
  4413. Quaternion.prototype.equals = function (otherQuaternion) {
  4414. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4415. };
  4416. /**
  4417. * Clone the current quaternion
  4418. * @returns a new quaternion copied from the current one
  4419. */
  4420. Quaternion.prototype.clone = function () {
  4421. return new Quaternion(this.x, this.y, this.z, this.w);
  4422. };
  4423. /**
  4424. * Copy a quaternion to the current one
  4425. * @param other defines the other quaternion
  4426. * @returns the updated current quaternion
  4427. */
  4428. Quaternion.prototype.copyFrom = function (other) {
  4429. this.x = other.x;
  4430. this.y = other.y;
  4431. this.z = other.z;
  4432. this.w = other.w;
  4433. return this;
  4434. };
  4435. /**
  4436. * Updates the current quaternion with the given float coordinates
  4437. * @param x defines the x coordinate
  4438. * @param y defines the y coordinate
  4439. * @param z defines the z coordinate
  4440. * @param w defines the w coordinate
  4441. * @returns the updated current quaternion
  4442. */
  4443. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. return this;
  4449. };
  4450. /**
  4451. * Updates the current quaternion from the given float coordinates
  4452. * @param x defines the x coordinate
  4453. * @param y defines the y coordinate
  4454. * @param z defines the z coordinate
  4455. * @param w defines the w coordinate
  4456. * @returns the updated current quaternion
  4457. */
  4458. Quaternion.prototype.set = function (x, y, z, w) {
  4459. return this.copyFromFloats(x, y, z, w);
  4460. };
  4461. /**
  4462. * Adds two quaternions
  4463. * @param other defines the second operand
  4464. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4465. */
  4466. Quaternion.prototype.add = function (other) {
  4467. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4468. };
  4469. /**
  4470. * Add a quaternion to the current one
  4471. * @param other defines the quaternion to add
  4472. * @returns the current quaternion
  4473. */
  4474. Quaternion.prototype.addInPlace = function (other) {
  4475. this.x += other.x;
  4476. this.y += other.y;
  4477. this.z += other.z;
  4478. this.w += other.w;
  4479. return this;
  4480. };
  4481. /**
  4482. * Subtract two quaternions
  4483. * @param other defines the second operand
  4484. * @returns a new quaternion as the subtraction result of the given one from the current one
  4485. */
  4486. Quaternion.prototype.subtract = function (other) {
  4487. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4488. };
  4489. /**
  4490. * Multiplies the current quaternion by a scale factor
  4491. * @param value defines the scale factor
  4492. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4493. */
  4494. Quaternion.prototype.scale = function (value) {
  4495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4496. };
  4497. /**
  4498. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4499. * @param scale defines the scale factor
  4500. * @param result defines the Quaternion object where to store the result
  4501. * @returns the unmodified current quaternion
  4502. */
  4503. Quaternion.prototype.scaleToRef = function (scale, result) {
  4504. result.x = this.x * scale;
  4505. result.y = this.y * scale;
  4506. result.z = this.z * scale;
  4507. result.w = this.w * scale;
  4508. return this;
  4509. };
  4510. /**
  4511. * Multiplies in place the current quaternion by a scale factor
  4512. * @param value defines the scale factor
  4513. * @returns the current modified quaternion
  4514. */
  4515. Quaternion.prototype.scaleInPlace = function (value) {
  4516. this.x *= value;
  4517. this.y *= value;
  4518. this.z *= value;
  4519. this.w *= value;
  4520. return this;
  4521. };
  4522. /**
  4523. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4524. * @param scale defines the scale factor
  4525. * @param result defines the Quaternion object where to store the result
  4526. * @returns the unmodified current quaternion
  4527. */
  4528. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4529. result.x += this.x * scale;
  4530. result.y += this.y * scale;
  4531. result.z += this.z * scale;
  4532. result.w += this.w * scale;
  4533. return this;
  4534. };
  4535. /**
  4536. * Multiplies two quaternions
  4537. * @param q1 defines the second operand
  4538. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4539. */
  4540. Quaternion.prototype.multiply = function (q1) {
  4541. var result = new Quaternion(0, 0, 0, 1.0);
  4542. this.multiplyToRef(q1, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @param result defines the target quaternion
  4549. * @returns the current quaternion
  4550. */
  4551. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4552. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4553. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4554. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4555. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4556. result.copyFromFloats(x, y, z, w);
  4557. return this;
  4558. };
  4559. /**
  4560. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4561. * @param q1 defines the second operand
  4562. * @returns the currentupdated quaternion
  4563. */
  4564. Quaternion.prototype.multiplyInPlace = function (q1) {
  4565. this.multiplyToRef(q1, this);
  4566. return this;
  4567. };
  4568. /**
  4569. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4570. * @param ref defines the target quaternion
  4571. * @returns the current quaternion
  4572. */
  4573. Quaternion.prototype.conjugateToRef = function (ref) {
  4574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4575. return this;
  4576. };
  4577. /**
  4578. * Conjugates in place (1-q) the current quaternion
  4579. * @returns the current updated quaternion
  4580. */
  4581. Quaternion.prototype.conjugateInPlace = function () {
  4582. this.x *= -1;
  4583. this.y *= -1;
  4584. this.z *= -1;
  4585. return this;
  4586. };
  4587. /**
  4588. * Conjugates in place (1-q) the current quaternion
  4589. * @returns a new quaternion
  4590. */
  4591. Quaternion.prototype.conjugate = function () {
  4592. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4593. return result;
  4594. };
  4595. /**
  4596. * Gets length of current quaternion
  4597. * @returns the quaternion length (float)
  4598. */
  4599. Quaternion.prototype.length = function () {
  4600. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4601. };
  4602. /**
  4603. * Normalize in place the current quaternion
  4604. * @returns the current updated quaternion
  4605. */
  4606. Quaternion.prototype.normalize = function () {
  4607. var length = 1.0 / this.length();
  4608. this.x *= length;
  4609. this.y *= length;
  4610. this.z *= length;
  4611. this.w *= length;
  4612. return this;
  4613. };
  4614. /**
  4615. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4616. * @param order is a reserved parameter and is ignore for now
  4617. * @returns a new Vector3 containing the Euler angles
  4618. */
  4619. Quaternion.prototype.toEulerAngles = function (order) {
  4620. if (order === void 0) { order = "YZX"; }
  4621. var result = Vector3.Zero();
  4622. this.toEulerAnglesToRef(result, order);
  4623. return result;
  4624. };
  4625. /**
  4626. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4627. * @param result defines the vector which will be filled with the Euler angles
  4628. * @param order is a reserved parameter and is ignore for now
  4629. * @returns the current unchanged quaternion
  4630. */
  4631. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4632. if (order === void 0) { order = "YZX"; }
  4633. var qz = this.z;
  4634. var qx = this.x;
  4635. var qy = this.y;
  4636. var qw = this.w;
  4637. var sqw = qw * qw;
  4638. var sqz = qz * qz;
  4639. var sqx = qx * qx;
  4640. var sqy = qy * qy;
  4641. var zAxisY = qy * qz - qx * qw;
  4642. var limit = .4999999;
  4643. if (zAxisY < -limit) {
  4644. result.y = 2 * Math.atan2(qy, qw);
  4645. result.x = Math.PI / 2;
  4646. result.z = 0;
  4647. }
  4648. else if (zAxisY > limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = -Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else {
  4654. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4655. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4656. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4657. }
  4658. return this;
  4659. };
  4660. /**
  4661. * Updates the given rotation matrix with the current quaternion values
  4662. * @param result defines the target matrix
  4663. * @returns the current unchanged quaternion
  4664. */
  4665. Quaternion.prototype.toRotationMatrix = function (result) {
  4666. var xx = this.x * this.x;
  4667. var yy = this.y * this.y;
  4668. var zz = this.z * this.z;
  4669. var xy = this.x * this.y;
  4670. var zw = this.z * this.w;
  4671. var zx = this.z * this.x;
  4672. var yw = this.y * this.w;
  4673. var yz = this.y * this.z;
  4674. var xw = this.x * this.w;
  4675. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4676. result.m[1] = 2.0 * (xy + zw);
  4677. result.m[2] = 2.0 * (zx - yw);
  4678. result.m[3] = 0;
  4679. result.m[4] = 2.0 * (xy - zw);
  4680. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4681. result.m[6] = 2.0 * (yz + xw);
  4682. result.m[7] = 0;
  4683. result.m[8] = 2.0 * (zx + yw);
  4684. result.m[9] = 2.0 * (yz - xw);
  4685. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4686. result.m[11] = 0;
  4687. result.m[12] = 0;
  4688. result.m[13] = 0;
  4689. result.m[14] = 0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. return this;
  4693. };
  4694. /**
  4695. * Updates the current quaternion from the given rotation matrix values
  4696. * @param matrix defines the source matrix
  4697. * @returns the current updated quaternion
  4698. */
  4699. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4700. Quaternion.FromRotationMatrixToRef(matrix, this);
  4701. return this;
  4702. };
  4703. // Statics
  4704. /**
  4705. * Creates a new quaternion from a rotation matrix
  4706. * @param matrix defines the source matrix
  4707. * @returns a new quaternion created from the given rotation matrix values
  4708. */
  4709. Quaternion.FromRotationMatrix = function (matrix) {
  4710. var result = new Quaternion();
  4711. Quaternion.FromRotationMatrixToRef(matrix, result);
  4712. return result;
  4713. };
  4714. /**
  4715. * Updates the given quaternion with the given rotation matrix values
  4716. * @param matrix defines the source matrix
  4717. * @param result defines the target quaternion
  4718. */
  4719. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4720. var data = matrix.m;
  4721. var m11 = data[0], m12 = data[4], m13 = data[8];
  4722. var m21 = data[1], m22 = data[5], m23 = data[9];
  4723. var m31 = data[2], m32 = data[6], m33 = data[10];
  4724. var trace = m11 + m22 + m33;
  4725. var s;
  4726. if (trace > 0) {
  4727. s = 0.5 / Math.sqrt(trace + 1.0);
  4728. result.w = 0.25 / s;
  4729. result.x = (m32 - m23) * s;
  4730. result.y = (m13 - m31) * s;
  4731. result.z = (m21 - m12) * s;
  4732. }
  4733. else if (m11 > m22 && m11 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4735. result.w = (m32 - m23) / s;
  4736. result.x = 0.25 * s;
  4737. result.y = (m12 + m21) / s;
  4738. result.z = (m13 + m31) / s;
  4739. }
  4740. else if (m22 > m33) {
  4741. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4742. result.w = (m13 - m31) / s;
  4743. result.x = (m12 + m21) / s;
  4744. result.y = 0.25 * s;
  4745. result.z = (m23 + m32) / s;
  4746. }
  4747. else {
  4748. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4749. result.w = (m21 - m12) / s;
  4750. result.x = (m13 + m31) / s;
  4751. result.y = (m23 + m32) / s;
  4752. result.z = 0.25 * s;
  4753. }
  4754. };
  4755. /**
  4756. * Returns the dot product (float) between the quaternions "left" and "right"
  4757. * @param left defines the left operand
  4758. * @param right defines the right operand
  4759. * @returns the dot product
  4760. */
  4761. Quaternion.Dot = function (left, right) {
  4762. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4763. };
  4764. /**
  4765. * Checks if the two quaternions are close to each other
  4766. * @param quat0 defines the first quaternion to check
  4767. * @param quat1 defines the second quaternion to check
  4768. * @returns true if the two quaternions are close to each other
  4769. */
  4770. Quaternion.AreClose = function (quat0, quat1) {
  4771. var dot = Quaternion.Dot(quat0, quat1);
  4772. return dot >= 0;
  4773. };
  4774. /**
  4775. * Creates an empty quaternion
  4776. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4777. */
  4778. Quaternion.Zero = function () {
  4779. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4780. };
  4781. /**
  4782. * Inverse a given quaternion
  4783. * @param q defines the source quaternion
  4784. * @returns a new quaternion as the inverted current quaternion
  4785. */
  4786. Quaternion.Inverse = function (q) {
  4787. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4788. };
  4789. /**
  4790. * Creates an identity quaternion
  4791. * @returns the identity quaternion
  4792. */
  4793. Quaternion.Identity = function () {
  4794. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4795. };
  4796. /**
  4797. * Gets a boolean indicating if the given quaternion is identity
  4798. * @param quaternion defines the quaternion to check
  4799. * @returns true if the quaternion is identity
  4800. */
  4801. Quaternion.IsIdentity = function (quaternion) {
  4802. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4803. };
  4804. /**
  4805. * Creates a quaternion from a rotation around an axis
  4806. * @param axis defines the axis to use
  4807. * @param angle defines the angle to use
  4808. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4809. */
  4810. Quaternion.RotationAxis = function (axis, angle) {
  4811. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4812. };
  4813. /**
  4814. * Creates a rotation around an axis and stores it into the given quaternion
  4815. * @param axis defines the axis to use
  4816. * @param angle defines the angle to use
  4817. * @param result defines the target quaternion
  4818. * @returns the target quaternion
  4819. */
  4820. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4821. var sin = Math.sin(angle / 2);
  4822. axis.normalize();
  4823. result.w = Math.cos(angle / 2);
  4824. result.x = axis.x * sin;
  4825. result.y = axis.y * sin;
  4826. result.z = axis.z * sin;
  4827. return result;
  4828. };
  4829. /**
  4830. * Creates a new quaternion from data stored into an array
  4831. * @param array defines the data source
  4832. * @param offset defines the offset in the source array where the data starts
  4833. * @returns a new quaternion
  4834. */
  4835. Quaternion.FromArray = function (array, offset) {
  4836. if (!offset) {
  4837. offset = 0;
  4838. }
  4839. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4840. };
  4841. /**
  4842. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4843. * @param yaw defines the rotation around Y axis
  4844. * @param pitch defines the rotation around X axis
  4845. * @param roll defines the rotation around Z axis
  4846. * @returns the new quaternion
  4847. */
  4848. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4849. var q = new Quaternion();
  4850. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4851. return q;
  4852. };
  4853. /**
  4854. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4855. * @param yaw defines the rotation around Y axis
  4856. * @param pitch defines the rotation around X axis
  4857. * @param roll defines the rotation around Z axis
  4858. * @param result defines the target quaternion
  4859. */
  4860. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4861. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4862. var halfRoll = roll * 0.5;
  4863. var halfPitch = pitch * 0.5;
  4864. var halfYaw = yaw * 0.5;
  4865. var sinRoll = Math.sin(halfRoll);
  4866. var cosRoll = Math.cos(halfRoll);
  4867. var sinPitch = Math.sin(halfPitch);
  4868. var cosPitch = Math.cos(halfPitch);
  4869. var sinYaw = Math.sin(halfYaw);
  4870. var cosYaw = Math.cos(halfYaw);
  4871. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4872. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4873. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4874. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4875. };
  4876. /**
  4877. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4878. * @param alpha defines the rotation around first axis
  4879. * @param beta defines the rotation around second axis
  4880. * @param gamma defines the rotation around third axis
  4881. * @returns the new quaternion
  4882. */
  4883. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4884. var result = new Quaternion();
  4885. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4886. return result;
  4887. };
  4888. /**
  4889. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4890. * @param alpha defines the rotation around first axis
  4891. * @param beta defines the rotation around second axis
  4892. * @param gamma defines the rotation around third axis
  4893. * @param result defines the target quaternion
  4894. */
  4895. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4896. // Produces a quaternion from Euler angles in the z-x-z orientation
  4897. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4898. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4899. var halfBeta = beta * 0.5;
  4900. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4901. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4902. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4903. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4904. };
  4905. /**
  4906. * 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)
  4907. * @param axis1 defines the first axis
  4908. * @param axis2 defines the second axis
  4909. * @param axis3 defines the third axis
  4910. * @returns the new quaternion
  4911. */
  4912. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4913. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4914. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4915. return quat;
  4916. };
  4917. /**
  4918. * 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
  4919. * @param axis1 defines the first axis
  4920. * @param axis2 defines the second axis
  4921. * @param axis3 defines the third axis
  4922. * @param ref defines the target quaternion
  4923. */
  4924. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4925. var rotMat = MathTmp.Matrix[0];
  4926. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4927. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4928. };
  4929. /**
  4930. * Interpolates between two quaternions
  4931. * @param left defines first quaternion
  4932. * @param right defines second quaternion
  4933. * @param amount defines the gradient to use
  4934. * @returns the new interpolated quaternion
  4935. */
  4936. Quaternion.Slerp = function (left, right, amount) {
  4937. var result = Quaternion.Identity();
  4938. Quaternion.SlerpToRef(left, right, amount, result);
  4939. return result;
  4940. };
  4941. /**
  4942. * Interpolates between two quaternions and stores it into a target quaternion
  4943. * @param left defines first quaternion
  4944. * @param right defines second quaternion
  4945. * @param amount defines the gradient to use
  4946. * @param result defines the target quaternion
  4947. */
  4948. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4949. var num2;
  4950. var num3;
  4951. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4952. var flag = false;
  4953. if (num4 < 0) {
  4954. flag = true;
  4955. num4 = -num4;
  4956. }
  4957. if (num4 > 0.999999) {
  4958. num3 = 1 - amount;
  4959. num2 = flag ? -amount : amount;
  4960. }
  4961. else {
  4962. var num5 = Math.acos(num4);
  4963. var num6 = (1.0 / Math.sin(num5));
  4964. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4965. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4966. }
  4967. result.x = (num3 * left.x) + (num2 * right.x);
  4968. result.y = (num3 * left.y) + (num2 * right.y);
  4969. result.z = (num3 * left.z) + (num2 * right.z);
  4970. result.w = (num3 * left.w) + (num2 * right.w);
  4971. };
  4972. /**
  4973. * Interpolate between two quaternions using Hermite interpolation
  4974. * @param value1 defines first quaternion
  4975. * @param tangent1 defines the incoming tangent
  4976. * @param value2 defines second quaternion
  4977. * @param tangent2 defines the outgoing tangent
  4978. * @param amount defines the target quaternion
  4979. * @returns the new interpolated quaternion
  4980. */
  4981. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4982. var squared = amount * amount;
  4983. var cubed = amount * squared;
  4984. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4985. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4986. var part3 = (cubed - (2.0 * squared)) + amount;
  4987. var part4 = cubed - squared;
  4988. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4989. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4990. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4991. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4992. return new Quaternion(x, y, z, w);
  4993. };
  4994. return Quaternion;
  4995. }());
  4996. BABYLON.Quaternion = Quaternion;
  4997. /**
  4998. * Class used to store matrix data (4x4)
  4999. */
  5000. var Matrix = /** @class */ (function () {
  5001. /**
  5002. * Creates an empty matrix (filled with zeros)
  5003. */
  5004. function Matrix() {
  5005. this._isIdentity = false;
  5006. this._isIdentityDirty = true;
  5007. /**
  5008. * Gets or sets the internal data of the matrix
  5009. */
  5010. this.m = new Float32Array(16);
  5011. this._markAsUpdated();
  5012. }
  5013. /** @hidden */
  5014. Matrix.prototype._markAsUpdated = function () {
  5015. this.updateFlag = Matrix._updateFlagSeed++;
  5016. this._isIdentityDirty = true;
  5017. };
  5018. // Properties
  5019. /**
  5020. * Check if the current matrix is indentity
  5021. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5022. * @returns true is the matrix is the identity matrix
  5023. */
  5024. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5025. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5026. if (this._isIdentityDirty) {
  5027. this._isIdentityDirty = false;
  5028. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5029. this._isIdentity = false;
  5030. }
  5031. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5032. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5033. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5034. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5035. this._isIdentity = false;
  5036. }
  5037. else {
  5038. this._isIdentity = true;
  5039. }
  5040. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5041. this._isIdentity = false;
  5042. }
  5043. }
  5044. return this._isIdentity;
  5045. };
  5046. /**
  5047. * Gets the determinant of the matrix
  5048. * @returns the matrix determinant
  5049. */
  5050. Matrix.prototype.determinant = function () {
  5051. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5052. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5053. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5054. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5055. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5056. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5057. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5058. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5059. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5060. };
  5061. // Methods
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array
  5065. */
  5066. Matrix.prototype.toArray = function () {
  5067. return this.m;
  5068. };
  5069. /**
  5070. * Returns the matrix as a Float32Array
  5071. * @returns the matrix underlying array.
  5072. */
  5073. Matrix.prototype.asArray = function () {
  5074. return this.toArray();
  5075. };
  5076. /**
  5077. * Inverts the current matrix in place
  5078. * @returns the current inverted matrix
  5079. */
  5080. Matrix.prototype.invert = function () {
  5081. this.invertToRef(this);
  5082. return this;
  5083. };
  5084. /**
  5085. * Sets all the matrix elements to zero
  5086. * @returns the current matrix
  5087. */
  5088. Matrix.prototype.reset = function () {
  5089. for (var index = 0; index < 16; index++) {
  5090. this.m[index] = 0.0;
  5091. }
  5092. this._markAsUpdated();
  5093. return this;
  5094. };
  5095. /**
  5096. * Adds the current matrix with a second one
  5097. * @param other defines the matrix to add
  5098. * @returns a new matrix as the addition of the current matrix and the given one
  5099. */
  5100. Matrix.prototype.add = function (other) {
  5101. var result = new Matrix();
  5102. this.addToRef(other, result);
  5103. return result;
  5104. };
  5105. /**
  5106. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5107. * @param other defines the matrix to add
  5108. * @param result defines the target matrix
  5109. * @returns the current matrix
  5110. */
  5111. Matrix.prototype.addToRef = function (other, result) {
  5112. for (var index = 0; index < 16; index++) {
  5113. result.m[index] = this.m[index] + other.m[index];
  5114. }
  5115. result._markAsUpdated();
  5116. return this;
  5117. };
  5118. /**
  5119. * Adds in place the given matrix to the current matrix
  5120. * @param other defines the second operand
  5121. * @returns the current updated matrix
  5122. */
  5123. Matrix.prototype.addToSelf = function (other) {
  5124. for (var index = 0; index < 16; index++) {
  5125. this.m[index] += other.m[index];
  5126. }
  5127. this._markAsUpdated();
  5128. return this;
  5129. };
  5130. /**
  5131. * Sets the given matrix to the current inverted Matrix
  5132. * @param other defines the target matrix
  5133. * @returns the unmodified current matrix
  5134. */
  5135. Matrix.prototype.invertToRef = function (other) {
  5136. var l1 = this.m[0];
  5137. var l2 = this.m[1];
  5138. var l3 = this.m[2];
  5139. var l4 = this.m[3];
  5140. var l5 = this.m[4];
  5141. var l6 = this.m[5];
  5142. var l7 = this.m[6];
  5143. var l8 = this.m[7];
  5144. var l9 = this.m[8];
  5145. var l10 = this.m[9];
  5146. var l11 = this.m[10];
  5147. var l12 = this.m[11];
  5148. var l13 = this.m[12];
  5149. var l14 = this.m[13];
  5150. var l15 = this.m[14];
  5151. var l16 = this.m[15];
  5152. var l17 = (l11 * l16) - (l12 * l15);
  5153. var l18 = (l10 * l16) - (l12 * l14);
  5154. var l19 = (l10 * l15) - (l11 * l14);
  5155. var l20 = (l9 * l16) - (l12 * l13);
  5156. var l21 = (l9 * l15) - (l11 * l13);
  5157. var l22 = (l9 * l14) - (l10 * l13);
  5158. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5159. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5160. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5161. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5162. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5163. var l28 = (l7 * l16) - (l8 * l15);
  5164. var l29 = (l6 * l16) - (l8 * l14);
  5165. var l30 = (l6 * l15) - (l7 * l14);
  5166. var l31 = (l5 * l16) - (l8 * l13);
  5167. var l32 = (l5 * l15) - (l7 * l13);
  5168. var l33 = (l5 * l14) - (l6 * l13);
  5169. var l34 = (l7 * l12) - (l8 * l11);
  5170. var l35 = (l6 * l12) - (l8 * l10);
  5171. var l36 = (l6 * l11) - (l7 * l10);
  5172. var l37 = (l5 * l12) - (l8 * l9);
  5173. var l38 = (l5 * l11) - (l7 * l9);
  5174. var l39 = (l5 * l10) - (l6 * l9);
  5175. other.m[0] = l23 * l27;
  5176. other.m[4] = l24 * l27;
  5177. other.m[8] = l25 * l27;
  5178. other.m[12] = l26 * l27;
  5179. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5180. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5181. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5182. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5183. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5184. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5185. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5186. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5187. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5188. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5189. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5190. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5191. other._markAsUpdated();
  5192. return this;
  5193. };
  5194. /**
  5195. * Inserts the translation vector (using 3 floats) in the current matrix
  5196. * @param x defines the 1st component of the translation
  5197. * @param y defines the 2nd component of the translation
  5198. * @param z defines the 3rd component of the translation
  5199. * @returns the current updated matrix
  5200. */
  5201. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5202. this.m[12] = x;
  5203. this.m[13] = y;
  5204. this.m[14] = z;
  5205. this._markAsUpdated();
  5206. return this;
  5207. };
  5208. /**
  5209. * Inserts the translation vector in the current matrix
  5210. * @param vector3 defines the translation to insert
  5211. * @returns the current updated matrix
  5212. */
  5213. Matrix.prototype.setTranslation = function (vector3) {
  5214. this.m[12] = vector3.x;
  5215. this.m[13] = vector3.y;
  5216. this.m[14] = vector3.z;
  5217. this._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Gets the translation value of the current matrix
  5222. * @returns a new Vector3 as the extracted translation from the matrix
  5223. */
  5224. Matrix.prototype.getTranslation = function () {
  5225. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5226. };
  5227. /**
  5228. * Fill a Vector3 with the extracted translation from the matrix
  5229. * @param result defines the Vector3 where to store the translation
  5230. * @returns the current matrix
  5231. */
  5232. Matrix.prototype.getTranslationToRef = function (result) {
  5233. result.x = this.m[12];
  5234. result.y = this.m[13];
  5235. result.z = this.m[14];
  5236. return this;
  5237. };
  5238. /**
  5239. * Remove rotation and scaling part from the matrix
  5240. * @returns the updated matrix
  5241. */
  5242. Matrix.prototype.removeRotationAndScaling = function () {
  5243. this.setRowFromFloats(0, 1, 0, 0, 0);
  5244. this.setRowFromFloats(1, 0, 1, 0, 0);
  5245. this.setRowFromFloats(2, 0, 0, 1, 0);
  5246. return this;
  5247. };
  5248. /**
  5249. * Multiply two matrices
  5250. * @param other defines the second operand
  5251. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5252. */
  5253. Matrix.prototype.multiply = function (other) {
  5254. var result = new Matrix();
  5255. this.multiplyToRef(other, result);
  5256. return result;
  5257. };
  5258. /**
  5259. * Copy the current matrix from the given one
  5260. * @param other defines the source matrix
  5261. * @returns the current updated matrix
  5262. */
  5263. Matrix.prototype.copyFrom = function (other) {
  5264. for (var index = 0; index < 16; index++) {
  5265. this.m[index] = other.m[index];
  5266. }
  5267. this._markAsUpdated();
  5268. return this;
  5269. };
  5270. /**
  5271. * Populates the given array from the starting index with the current matrix values
  5272. * @param array defines the target array
  5273. * @param offset defines the offset in the target array where to start storing values
  5274. * @returns the current matrix
  5275. */
  5276. Matrix.prototype.copyToArray = function (array, offset) {
  5277. if (offset === void 0) { offset = 0; }
  5278. for (var index = 0; index < 16; index++) {
  5279. array[offset + index] = this.m[index];
  5280. }
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the matrix where to store the multiplication
  5287. * @returns the current matrix
  5288. */
  5289. Matrix.prototype.multiplyToRef = function (other, result) {
  5290. this.multiplyToArray(other, result.m, 0);
  5291. result._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5296. * @param other defines the second operand
  5297. * @param result defines the array where to store the multiplication
  5298. * @param offset defines the offset in the target array where to start storing values
  5299. * @returns the current matrix
  5300. */
  5301. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5302. var tm0 = this.m[0];
  5303. var tm1 = this.m[1];
  5304. var tm2 = this.m[2];
  5305. var tm3 = this.m[3];
  5306. var tm4 = this.m[4];
  5307. var tm5 = this.m[5];
  5308. var tm6 = this.m[6];
  5309. var tm7 = this.m[7];
  5310. var tm8 = this.m[8];
  5311. var tm9 = this.m[9];
  5312. var tm10 = this.m[10];
  5313. var tm11 = this.m[11];
  5314. var tm12 = this.m[12];
  5315. var tm13 = this.m[13];
  5316. var tm14 = this.m[14];
  5317. var tm15 = this.m[15];
  5318. var om0 = other.m[0];
  5319. var om1 = other.m[1];
  5320. var om2 = other.m[2];
  5321. var om3 = other.m[3];
  5322. var om4 = other.m[4];
  5323. var om5 = other.m[5];
  5324. var om6 = other.m[6];
  5325. var om7 = other.m[7];
  5326. var om8 = other.m[8];
  5327. var om9 = other.m[9];
  5328. var om10 = other.m[10];
  5329. var om11 = other.m[11];
  5330. var om12 = other.m[12];
  5331. var om13 = other.m[13];
  5332. var om14 = other.m[14];
  5333. var om15 = other.m[15];
  5334. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5335. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5336. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5337. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5338. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5339. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5340. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5341. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5342. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5343. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5344. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5345. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5346. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5347. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5348. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5349. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5350. return this;
  5351. };
  5352. /**
  5353. * Check equality between this matrix and a second one
  5354. * @param value defines the second matrix to compare
  5355. * @returns true is the current matrix and the given one values are strictly equal
  5356. */
  5357. Matrix.prototype.equals = function (value) {
  5358. return value &&
  5359. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5360. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5361. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5362. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5363. };
  5364. /**
  5365. * Clone the current matrix
  5366. * @returns a new matrix from the current matrix
  5367. */
  5368. Matrix.prototype.clone = function () {
  5369. 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]);
  5370. };
  5371. /**
  5372. * Returns the name of the current matrix class
  5373. * @returns the string "Matrix"
  5374. */
  5375. Matrix.prototype.getClassName = function () {
  5376. return "Matrix";
  5377. };
  5378. /**
  5379. * Gets the hash code of the current matrix
  5380. * @returns the hash code
  5381. */
  5382. Matrix.prototype.getHashCode = function () {
  5383. var hash = this.m[0] || 0;
  5384. for (var i = 1; i < 16; i++) {
  5385. hash = (hash * 397) ^ (this.m[i] || 0);
  5386. }
  5387. return hash;
  5388. };
  5389. /**
  5390. * Decomposes the current Matrix into a translation, rotation and scaling components
  5391. * @param scale defines the scale vector3 given as a reference to update
  5392. * @param rotation defines the rotation quaternion given as a reference to update
  5393. * @param translation defines the translation vector3 given as a reference to update
  5394. * @returns true if operation was successful
  5395. */
  5396. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5397. if (translation) {
  5398. translation.x = this.m[12];
  5399. translation.y = this.m[13];
  5400. translation.z = this.m[14];
  5401. }
  5402. scale = scale || MathTmp.Vector3[0];
  5403. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5404. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5405. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5406. if (this.determinant() <= 0) {
  5407. scale.y *= -1;
  5408. }
  5409. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5410. if (rotation) {
  5411. rotation.x = 0;
  5412. rotation.y = 0;
  5413. rotation.z = 0;
  5414. rotation.w = 1;
  5415. }
  5416. return false;
  5417. }
  5418. if (rotation) {
  5419. 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]);
  5420. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5421. }
  5422. return true;
  5423. };
  5424. /**
  5425. * Gets specific row of the matrix
  5426. * @param index defines the number of the row to get
  5427. * @returns the index-th row of the current matrix as a new Vector4
  5428. */
  5429. Matrix.prototype.getRow = function (index) {
  5430. if (index < 0 || index > 3) {
  5431. return null;
  5432. }
  5433. var i = index * 4;
  5434. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5435. };
  5436. /**
  5437. * Sets the index-th row of the current matrix to the vector4 values
  5438. * @param index defines the number of the row to set
  5439. * @param row defines the target vector4
  5440. * @returns the updated current matrix
  5441. */
  5442. Matrix.prototype.setRow = function (index, row) {
  5443. if (index < 0 || index > 3) {
  5444. return this;
  5445. }
  5446. var i = index * 4;
  5447. this.m[i + 0] = row.x;
  5448. this.m[i + 1] = row.y;
  5449. this.m[i + 2] = row.z;
  5450. this.m[i + 3] = row.w;
  5451. this._markAsUpdated();
  5452. return this;
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix
  5456. * @returns the new transposed matrix
  5457. */
  5458. Matrix.prototype.transpose = function () {
  5459. return Matrix.Transpose(this);
  5460. };
  5461. /**
  5462. * Compute the transpose of the matrix and store it in a given matrix
  5463. * @param result defines the target matrix
  5464. * @returns the current matrix
  5465. */
  5466. Matrix.prototype.transposeToRef = function (result) {
  5467. Matrix.TransposeToRef(this, result);
  5468. return this;
  5469. };
  5470. /**
  5471. * Sets the index-th row of the current matrix with the given 4 x float values
  5472. * @param index defines the row index
  5473. * @param x defines the x component to set
  5474. * @param y defines the y component to set
  5475. * @param z defines the z component to set
  5476. * @param w defines the w component to set
  5477. * @returns the updated current matrix
  5478. */
  5479. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5480. if (index < 0 || index > 3) {
  5481. return this;
  5482. }
  5483. var i = index * 4;
  5484. this.m[i + 0] = x;
  5485. this.m[i + 1] = y;
  5486. this.m[i + 2] = z;
  5487. this.m[i + 3] = w;
  5488. this._markAsUpdated();
  5489. return this;
  5490. };
  5491. /**
  5492. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5493. * @param scale defines the scale factor
  5494. * @returns a new matrix
  5495. */
  5496. Matrix.prototype.scale = function (scale) {
  5497. var result = new Matrix();
  5498. this.scaleToRef(scale, result);
  5499. return result;
  5500. };
  5501. /**
  5502. * Scale the current matrix values by a factor to a given result matrix
  5503. * @param scale defines the scale factor
  5504. * @param result defines the matrix to store the result
  5505. * @returns the current matrix
  5506. */
  5507. Matrix.prototype.scaleToRef = function (scale, result) {
  5508. for (var index = 0; index < 16; index++) {
  5509. result.m[index] = this.m[index] * scale;
  5510. }
  5511. result._markAsUpdated();
  5512. return this;
  5513. };
  5514. /**
  5515. * Scale the current matrix values by a factor and add the result to a given matrix
  5516. * @param scale defines the scale factor
  5517. * @param result defines the Matrix to store the result
  5518. * @returns the current matrix
  5519. */
  5520. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5521. for (var index = 0; index < 16; index++) {
  5522. result.m[index] += this.m[index] * scale;
  5523. }
  5524. result._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5529. * @param ref matrix to store the result
  5530. */
  5531. Matrix.prototype.toNormalMatrix = function (ref) {
  5532. this.invertToRef(ref);
  5533. ref.transpose();
  5534. var m = ref.m;
  5535. 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);
  5536. };
  5537. /**
  5538. * Gets only rotation part of the current matrix
  5539. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5540. */
  5541. Matrix.prototype.getRotationMatrix = function () {
  5542. var result = Matrix.Identity();
  5543. this.getRotationMatrixToRef(result);
  5544. return result;
  5545. };
  5546. /**
  5547. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5548. * @param result defines the target matrix to store data to
  5549. * @returns the current matrix
  5550. */
  5551. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5552. var m = this.m;
  5553. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5554. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5555. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5556. if (this.determinant() <= 0) {
  5557. sy *= -1;
  5558. }
  5559. if (sx === 0 || sy === 0 || sz === 0) {
  5560. Matrix.IdentityToRef(result);
  5561. }
  5562. else {
  5563. 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);
  5564. }
  5565. return this;
  5566. };
  5567. // Statics
  5568. /**
  5569. * Creates a matrix from an array
  5570. * @param array defines the source array
  5571. * @param offset defines an offset in the source array
  5572. * @returns a new Matrix set from the starting index of the given array
  5573. */
  5574. Matrix.FromArray = function (array, offset) {
  5575. var result = new Matrix();
  5576. if (!offset) {
  5577. offset = 0;
  5578. }
  5579. Matrix.FromArrayToRef(array, offset, result);
  5580. return result;
  5581. };
  5582. /**
  5583. * Copy the content of an array into a given matrix
  5584. * @param array defines the source array
  5585. * @param offset defines an offset in the source array
  5586. * @param result defines the target matrix
  5587. */
  5588. Matrix.FromArrayToRef = function (array, offset, result) {
  5589. for (var index = 0; index < 16; index++) {
  5590. result.m[index] = array[index + offset];
  5591. }
  5592. result._markAsUpdated();
  5593. };
  5594. /**
  5595. * Stores an array into a matrix after having multiplied each component by a given factor
  5596. * @param array defines the source array
  5597. * @param offset defines the offset in the source array
  5598. * @param scale defines the scaling factor
  5599. * @param result defines the target matrix
  5600. */
  5601. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = array[index + offset] * scale;
  5604. }
  5605. result._markAsUpdated();
  5606. };
  5607. /**
  5608. * Stores a list of values (16) inside a given matrix
  5609. * @param initialM11 defines 1st value of 1st row
  5610. * @param initialM12 defines 2nd value of 1st row
  5611. * @param initialM13 defines 3rd value of 1st row
  5612. * @param initialM14 defines 4th value of 1st row
  5613. * @param initialM21 defines 1st value of 2nd row
  5614. * @param initialM22 defines 2nd value of 2nd row
  5615. * @param initialM23 defines 3rd value of 2nd row
  5616. * @param initialM24 defines 4th value of 2nd row
  5617. * @param initialM31 defines 1st value of 3rd row
  5618. * @param initialM32 defines 2nd value of 3rd row
  5619. * @param initialM33 defines 3rd value of 3rd row
  5620. * @param initialM34 defines 4th value of 3rd row
  5621. * @param initialM41 defines 1st value of 4th row
  5622. * @param initialM42 defines 2nd value of 4th row
  5623. * @param initialM43 defines 3rd value of 4th row
  5624. * @param initialM44 defines 4th value of 4th row
  5625. * @param result defines the target matrix
  5626. */
  5627. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5628. result.m[0] = initialM11;
  5629. result.m[1] = initialM12;
  5630. result.m[2] = initialM13;
  5631. result.m[3] = initialM14;
  5632. result.m[4] = initialM21;
  5633. result.m[5] = initialM22;
  5634. result.m[6] = initialM23;
  5635. result.m[7] = initialM24;
  5636. result.m[8] = initialM31;
  5637. result.m[9] = initialM32;
  5638. result.m[10] = initialM33;
  5639. result.m[11] = initialM34;
  5640. result.m[12] = initialM41;
  5641. result.m[13] = initialM42;
  5642. result.m[14] = initialM43;
  5643. result.m[15] = initialM44;
  5644. result._markAsUpdated();
  5645. };
  5646. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5647. /**
  5648. * Gets an identity matrix that must not be updated
  5649. */
  5650. get: function () {
  5651. return Matrix._identityReadOnly;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. /**
  5657. * Creates new matrix from a list of values (16)
  5658. * @param initialM11 defines 1st value of 1st row
  5659. * @param initialM12 defines 2nd value of 1st row
  5660. * @param initialM13 defines 3rd value of 1st row
  5661. * @param initialM14 defines 4th value of 1st row
  5662. * @param initialM21 defines 1st value of 2nd row
  5663. * @param initialM22 defines 2nd value of 2nd row
  5664. * @param initialM23 defines 3rd value of 2nd row
  5665. * @param initialM24 defines 4th value of 2nd row
  5666. * @param initialM31 defines 1st value of 3rd row
  5667. * @param initialM32 defines 2nd value of 3rd row
  5668. * @param initialM33 defines 3rd value of 3rd row
  5669. * @param initialM34 defines 4th value of 3rd row
  5670. * @param initialM41 defines 1st value of 4th row
  5671. * @param initialM42 defines 2nd value of 4th row
  5672. * @param initialM43 defines 3rd value of 4th row
  5673. * @param initialM44 defines 4th value of 4th row
  5674. * @returns the new matrix
  5675. */
  5676. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5677. var result = new Matrix();
  5678. result.m[0] = initialM11;
  5679. result.m[1] = initialM12;
  5680. result.m[2] = initialM13;
  5681. result.m[3] = initialM14;
  5682. result.m[4] = initialM21;
  5683. result.m[5] = initialM22;
  5684. result.m[6] = initialM23;
  5685. result.m[7] = initialM24;
  5686. result.m[8] = initialM31;
  5687. result.m[9] = initialM32;
  5688. result.m[10] = initialM33;
  5689. result.m[11] = initialM34;
  5690. result.m[12] = initialM41;
  5691. result.m[13] = initialM42;
  5692. result.m[14] = initialM43;
  5693. result.m[15] = initialM44;
  5694. return result;
  5695. };
  5696. /**
  5697. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5698. * @param scale defines the scale vector3
  5699. * @param rotation defines the rotation quaternion
  5700. * @param translation defines the translation vector3
  5701. * @returns a new matrix
  5702. */
  5703. Matrix.Compose = function (scale, rotation, translation) {
  5704. var result = Matrix.Identity();
  5705. Matrix.ComposeToRef(scale, rotation, translation, result);
  5706. return result;
  5707. };
  5708. /**
  5709. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5710. * @param scale defines the scale vector3
  5711. * @param rotation defines the rotation quaternion
  5712. * @param translation defines the translation vector3
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5716. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5717. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5718. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5719. result.setTranslation(translation);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix
  5723. * @returns a new identity matrix
  5724. */
  5725. Matrix.Identity = function () {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new identity matrix and stores the result in a given matrix
  5730. * @param result defines the target matrix
  5731. */
  5732. Matrix.IdentityToRef = function (result) {
  5733. 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);
  5734. };
  5735. /**
  5736. * Creates a new zero matrix
  5737. * @returns a new zero matrix
  5738. */
  5739. Matrix.Zero = function () {
  5740. 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);
  5741. };
  5742. /**
  5743. * Creates a new rotation matrix for "angle" radians around the X axis
  5744. * @param angle defines the angle (in radians) to use
  5745. * @return the new matrix
  5746. */
  5747. Matrix.RotationX = function (angle) {
  5748. var result = new Matrix();
  5749. Matrix.RotationXToRef(angle, result);
  5750. return result;
  5751. };
  5752. /**
  5753. * Creates a new matrix as the invert of a given matrix
  5754. * @param source defines the source matrix
  5755. * @returns the new matrix
  5756. */
  5757. Matrix.Invert = function (source) {
  5758. var result = new Matrix();
  5759. source.invertToRef(result);
  5760. return result;
  5761. };
  5762. /**
  5763. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5764. * @param angle defines the angle (in radians) to use
  5765. * @param result defines the target matrix
  5766. */
  5767. Matrix.RotationXToRef = function (angle, result) {
  5768. var s = Math.sin(angle);
  5769. var c = Math.cos(angle);
  5770. result.m[0] = 1.0;
  5771. result.m[15] = 1.0;
  5772. result.m[5] = c;
  5773. result.m[10] = c;
  5774. result.m[9] = -s;
  5775. result.m[6] = s;
  5776. result.m[1] = 0.0;
  5777. result.m[2] = 0.0;
  5778. result.m[3] = 0.0;
  5779. result.m[4] = 0.0;
  5780. result.m[7] = 0.0;
  5781. result.m[8] = 0.0;
  5782. result.m[11] = 0.0;
  5783. result.m[12] = 0.0;
  5784. result.m[13] = 0.0;
  5785. result.m[14] = 0.0;
  5786. result._markAsUpdated();
  5787. };
  5788. /**
  5789. * Creates a new rotation matrix for "angle" radians around the Y axis
  5790. * @param angle defines the angle (in radians) to use
  5791. * @return the new matrix
  5792. */
  5793. Matrix.RotationY = function (angle) {
  5794. var result = new Matrix();
  5795. Matrix.RotationYToRef(angle, result);
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5800. * @param angle defines the angle (in radians) to use
  5801. * @param result defines the target matrix
  5802. */
  5803. Matrix.RotationYToRef = function (angle, result) {
  5804. var s = Math.sin(angle);
  5805. var c = Math.cos(angle);
  5806. result.m[5] = 1.0;
  5807. result.m[15] = 1.0;
  5808. result.m[0] = c;
  5809. result.m[2] = -s;
  5810. result.m[8] = s;
  5811. result.m[10] = c;
  5812. result.m[1] = 0.0;
  5813. result.m[3] = 0.0;
  5814. result.m[4] = 0.0;
  5815. result.m[6] = 0.0;
  5816. result.m[7] = 0.0;
  5817. result.m[9] = 0.0;
  5818. result.m[11] = 0.0;
  5819. result.m[12] = 0.0;
  5820. result.m[13] = 0.0;
  5821. result.m[14] = 0.0;
  5822. result._markAsUpdated();
  5823. };
  5824. /**
  5825. * Creates a new rotation matrix for "angle" radians around the Z axis
  5826. * @param angle defines the angle (in radians) to use
  5827. * @return the new matrix
  5828. */
  5829. Matrix.RotationZ = function (angle) {
  5830. var result = new Matrix();
  5831. Matrix.RotationZToRef(angle, result);
  5832. return result;
  5833. };
  5834. /**
  5835. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5836. * @param angle defines the angle (in radians) to use
  5837. * @param result defines the target matrix
  5838. */
  5839. Matrix.RotationZToRef = function (angle, result) {
  5840. var s = Math.sin(angle);
  5841. var c = Math.cos(angle);
  5842. result.m[10] = 1.0;
  5843. result.m[15] = 1.0;
  5844. result.m[0] = c;
  5845. result.m[1] = s;
  5846. result.m[4] = -s;
  5847. result.m[5] = c;
  5848. result.m[2] = 0.0;
  5849. result.m[3] = 0.0;
  5850. result.m[6] = 0.0;
  5851. result.m[7] = 0.0;
  5852. result.m[8] = 0.0;
  5853. result.m[9] = 0.0;
  5854. result.m[11] = 0.0;
  5855. result.m[12] = 0.0;
  5856. result.m[13] = 0.0;
  5857. result.m[14] = 0.0;
  5858. result._markAsUpdated();
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationAxis = function (axis, angle) {
  5867. var result = Matrix.Zero();
  5868. Matrix.RotationAxisToRef(axis, angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5873. * @param axis defines the axis to use
  5874. * @param angle defines the angle (in radians) to use
  5875. * @param result defines the target matrix
  5876. */
  5877. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5878. var s = Math.sin(-angle);
  5879. var c = Math.cos(-angle);
  5880. var c1 = 1 - c;
  5881. axis.normalize();
  5882. result.m[0] = (axis.x * axis.x) * c1 + c;
  5883. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5884. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5885. result.m[3] = 0.0;
  5886. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5887. result.m[5] = (axis.y * axis.y) * c1 + c;
  5888. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5889. result.m[7] = 0.0;
  5890. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5891. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5892. result.m[10] = (axis.z * axis.z) * c1 + c;
  5893. result.m[11] = 0.0;
  5894. result.m[15] = 1.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a rotation matrix
  5899. * @param yaw defines the yaw angle in radians (Y axis)
  5900. * @param pitch defines the pitch angle in radians (X axis)
  5901. * @param roll defines the roll angle in radians (X axis)
  5902. * @returns the new rotation matrix
  5903. */
  5904. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5905. var result = new Matrix();
  5906. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5907. return result;
  5908. };
  5909. /**
  5910. * Creates a rotation matrix and stores it in a given matrix
  5911. * @param yaw defines the yaw angle in radians (Y axis)
  5912. * @param pitch defines the pitch angle in radians (X axis)
  5913. * @param roll defines the roll angle in radians (X axis)
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5917. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5918. this._tempQuaternion.toRotationMatrix(result);
  5919. };
  5920. /**
  5921. * Creates a scaling matrix
  5922. * @param x defines the scale factor on X axis
  5923. * @param y defines the scale factor on Y axis
  5924. * @param z defines the scale factor on Z axis
  5925. * @returns the new matrix
  5926. */
  5927. Matrix.Scaling = function (x, y, z) {
  5928. var result = Matrix.Zero();
  5929. Matrix.ScalingToRef(x, y, z, result);
  5930. return result;
  5931. };
  5932. /**
  5933. * Creates a scaling matrix and stores it in a given matrix
  5934. * @param x defines the scale factor on X axis
  5935. * @param y defines the scale factor on Y axis
  5936. * @param z defines the scale factor on Z axis
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.ScalingToRef = function (x, y, z, result) {
  5940. result.m[0] = x;
  5941. result.m[1] = 0.0;
  5942. result.m[2] = 0.0;
  5943. result.m[3] = 0.0;
  5944. result.m[4] = 0.0;
  5945. result.m[5] = y;
  5946. result.m[6] = 0.0;
  5947. result.m[7] = 0.0;
  5948. result.m[8] = 0.0;
  5949. result.m[9] = 0.0;
  5950. result.m[10] = z;
  5951. result.m[11] = 0.0;
  5952. result.m[12] = 0.0;
  5953. result.m[13] = 0.0;
  5954. result.m[14] = 0.0;
  5955. result.m[15] = 1.0;
  5956. result._markAsUpdated();
  5957. };
  5958. /**
  5959. * Creates a translation matrix
  5960. * @param x defines the translation on X axis
  5961. * @param y defines the translation on Y axis
  5962. * @param z defines the translationon Z axis
  5963. * @returns the new matrix
  5964. */
  5965. Matrix.Translation = function (x, y, z) {
  5966. var result = Matrix.Identity();
  5967. Matrix.TranslationToRef(x, y, z, result);
  5968. return result;
  5969. };
  5970. /**
  5971. * Creates a translation matrix and stores it in a given matrix
  5972. * @param x defines the translation on X axis
  5973. * @param y defines the translation on Y axis
  5974. * @param z defines the translationon Z axis
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.TranslationToRef = function (x, y, z, result) {
  5978. 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);
  5979. };
  5980. /**
  5981. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5982. * @param startValue defines the start value
  5983. * @param endValue defines the end value
  5984. * @param gradient defines the gradient factor
  5985. * @returns the new matrix
  5986. */
  5987. Matrix.Lerp = function (startValue, endValue, gradient) {
  5988. var result = Matrix.Zero();
  5989. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5990. return result;
  5991. };
  5992. /**
  5993. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5994. * @param startValue defines the start value
  5995. * @param endValue defines the end value
  5996. * @param gradient defines the gradient factor
  5997. * @param result defines the Matrix object where to store data
  5998. */
  5999. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6000. for (var index = 0; index < 16; index++) {
  6001. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6002. }
  6003. result._markAsUpdated();
  6004. };
  6005. /**
  6006. * Builds a new matrix whose values are computed by:
  6007. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6008. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6009. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6010. * @param startValue defines the first matrix
  6011. * @param endValue defines the second matrix
  6012. * @param gradient defines the gradient between the two matrices
  6013. * @returns the new matrix
  6014. */
  6015. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6016. var result = Matrix.Zero();
  6017. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6018. return result;
  6019. };
  6020. /**
  6021. * Update a matrix to values which are computed by:
  6022. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6023. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6024. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6025. * @param startValue defines the first matrix
  6026. * @param endValue defines the second matrix
  6027. * @param gradient defines the gradient between the two matrices
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6031. var startScale = MathTmp.Vector3[0];
  6032. var startRotation = MathTmp.Quaternion[0];
  6033. var startTranslation = MathTmp.Vector3[1];
  6034. startValue.decompose(startScale, startRotation, startTranslation);
  6035. var endScale = MathTmp.Vector3[2];
  6036. var endRotation = MathTmp.Quaternion[1];
  6037. var endTranslation = MathTmp.Vector3[3];
  6038. endValue.decompose(endScale, endRotation, endTranslation);
  6039. var resultScale = MathTmp.Vector3[4];
  6040. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6041. var resultRotation = MathTmp.Quaternion[2];
  6042. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6043. var resultTranslation = MathTmp.Vector3[5];
  6044. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6045. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6046. };
  6047. /**
  6048. * 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"
  6049. * This function works in left handed mode
  6050. * @param eye defines the final position of the entity
  6051. * @param target defines where the entity should look at
  6052. * @param up defines the up vector for the entity
  6053. * @returns the new matrix
  6054. */
  6055. Matrix.LookAtLH = function (eye, target, up) {
  6056. var result = Matrix.Zero();
  6057. Matrix.LookAtLHToRef(eye, target, up, result);
  6058. return result;
  6059. };
  6060. /**
  6061. * 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".
  6062. * This function works in left handed mode
  6063. * @param eye defines the final position of the entity
  6064. * @param target defines where the entity should look at
  6065. * @param up defines the up vector for the entity
  6066. * @param result defines the target matrix
  6067. */
  6068. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6069. // Z axis
  6070. target.subtractToRef(eye, this._zAxis);
  6071. this._zAxis.normalize();
  6072. // X axis
  6073. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6074. if (this._xAxis.lengthSquared() === 0) {
  6075. this._xAxis.x = 1.0;
  6076. }
  6077. else {
  6078. this._xAxis.normalize();
  6079. }
  6080. // Y axis
  6081. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6082. this._yAxis.normalize();
  6083. // Eye angles
  6084. var ex = -Vector3.Dot(this._xAxis, eye);
  6085. var ey = -Vector3.Dot(this._yAxis, eye);
  6086. var ez = -Vector3.Dot(this._zAxis, eye);
  6087. 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);
  6088. };
  6089. /**
  6090. * 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"
  6091. * This function works in right handed mode
  6092. * @param eye defines the final position of the entity
  6093. * @param target defines where the entity should look at
  6094. * @param up defines the up vector for the entity
  6095. * @returns the new matrix
  6096. */
  6097. Matrix.LookAtRH = function (eye, target, up) {
  6098. var result = Matrix.Zero();
  6099. Matrix.LookAtRHToRef(eye, target, up, result);
  6100. return result;
  6101. };
  6102. /**
  6103. * 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".
  6104. * This function works in right handed mode
  6105. * @param eye defines the final position of the entity
  6106. * @param target defines where the entity should look at
  6107. * @param up defines the up vector for the entity
  6108. * @param result defines the target matrix
  6109. */
  6110. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6111. // Z axis
  6112. eye.subtractToRef(target, this._zAxis);
  6113. this._zAxis.normalize();
  6114. // X axis
  6115. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6116. if (this._xAxis.lengthSquared() === 0) {
  6117. this._xAxis.x = 1.0;
  6118. }
  6119. else {
  6120. this._xAxis.normalize();
  6121. }
  6122. // Y axis
  6123. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6124. this._yAxis.normalize();
  6125. // Eye angles
  6126. var ex = -Vector3.Dot(this._xAxis, eye);
  6127. var ey = -Vector3.Dot(this._yAxis, eye);
  6128. var ez = -Vector3.Dot(this._zAxis, eye);
  6129. 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);
  6130. };
  6131. /**
  6132. * Create a left-handed orthographic projection matrix
  6133. * @param width defines the viewport width
  6134. * @param height defines the viewport height
  6135. * @param znear defines the near clip plane
  6136. * @param zfar defines the far clip plane
  6137. * @returns a new matrix as a left-handed orthographic projection matrix
  6138. */
  6139. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6140. var matrix = Matrix.Zero();
  6141. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6142. return matrix;
  6143. };
  6144. /**
  6145. * Store a left-handed orthographic projection to a given matrix
  6146. * @param width defines the viewport width
  6147. * @param height defines the viewport height
  6148. * @param znear defines the near clip plane
  6149. * @param zfar defines the far clip plane
  6150. * @param result defines the target matrix
  6151. */
  6152. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6153. var n = znear;
  6154. var f = zfar;
  6155. var a = 2.0 / width;
  6156. var b = 2.0 / height;
  6157. var c = 2.0 / (f - n);
  6158. var d = -(f + n) / (f - n);
  6159. 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);
  6160. };
  6161. /**
  6162. * Create a left-handed orthographic projection matrix
  6163. * @param left defines the viewport left coordinate
  6164. * @param right defines the viewport right coordinate
  6165. * @param bottom defines the viewport bottom coordinate
  6166. * @param top defines the viewport top coordinate
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Stores a left-handed orthographic projection into a given matrix
  6178. * @param left defines the viewport left coordinate
  6179. * @param right defines the viewport right coordinate
  6180. * @param bottom defines the viewport bottom coordinate
  6181. * @param top defines the viewport top coordinate
  6182. * @param znear defines the near clip plane
  6183. * @param zfar defines the far clip plane
  6184. * @param result defines the target matrix
  6185. */
  6186. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6187. var n = znear;
  6188. var f = zfar;
  6189. var a = 2.0 / (right - left);
  6190. var b = 2.0 / (top - bottom);
  6191. var c = 2.0 / (f - n);
  6192. var d = -(f + n) / (f - n);
  6193. var i0 = (left + right) / (left - right);
  6194. var i1 = (top + bottom) / (bottom - top);
  6195. 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);
  6196. };
  6197. /**
  6198. * Creates a right-handed orthographic projection matrix
  6199. * @param left defines the viewport left coordinate
  6200. * @param right defines the viewport right coordinate
  6201. * @param bottom defines the viewport bottom coordinate
  6202. * @param top defines the viewport top coordinate
  6203. * @param znear defines the near clip plane
  6204. * @param zfar defines the far clip plane
  6205. * @returns a new matrix as a right-handed orthographic projection matrix
  6206. */
  6207. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6208. var matrix = Matrix.Zero();
  6209. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Stores a right-handed orthographic projection into a given matrix
  6214. * @param left defines the viewport left coordinate
  6215. * @param right defines the viewport right coordinate
  6216. * @param bottom defines the viewport bottom coordinate
  6217. * @param top defines the viewport top coordinate
  6218. * @param znear defines the near clip plane
  6219. * @param zfar defines the far clip plane
  6220. * @param result defines the target matrix
  6221. */
  6222. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6223. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6224. result.m[10] *= -1.0;
  6225. };
  6226. /**
  6227. * Creates a left-handed perspective projection matrix
  6228. * @param width defines the viewport width
  6229. * @param height defines the viewport height
  6230. * @param znear defines the near clip plane
  6231. * @param zfar defines the far clip plane
  6232. * @returns a new matrix as a left-handed perspective projection matrix
  6233. */
  6234. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6235. var matrix = Matrix.Zero();
  6236. var n = znear;
  6237. var f = zfar;
  6238. var a = 2.0 * n / width;
  6239. var b = 2.0 * n / height;
  6240. var c = (f + n) / (f - n);
  6241. var d = -2.0 * f * n / (f - n);
  6242. 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);
  6243. return matrix;
  6244. };
  6245. /**
  6246. * Creates a left-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a left-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6269. var n = znear;
  6270. var f = zfar;
  6271. var t = 1.0 / (Math.tan(fov * 0.5));
  6272. var a = isVerticalFovFixed ? (t / aspect) : t;
  6273. var b = isVerticalFovFixed ? t : (t * aspect);
  6274. var c = (f + n) / (f - n);
  6275. var d = -2.0 * f * n / (f - n);
  6276. 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);
  6277. };
  6278. /**
  6279. * Creates a right-handed perspective projection matrix
  6280. * @param fov defines the horizontal field of view
  6281. * @param aspect defines the aspect ratio
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @returns a new matrix as a right-handed perspective projection matrix
  6285. */
  6286. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6287. var matrix = Matrix.Zero();
  6288. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6289. return matrix;
  6290. };
  6291. /**
  6292. * Stores a right-handed perspective projection into a given matrix
  6293. * @param fov defines the horizontal field of view
  6294. * @param aspect defines the aspect ratio
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @param result defines the target matrix
  6298. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6299. */
  6300. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6301. //alternatively this could be expressed as:
  6302. // m = PerspectiveFovLHToRef
  6303. // m[10] *= -1.0;
  6304. // m[11] *= -1.0;
  6305. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6306. var n = znear;
  6307. var f = zfar;
  6308. var t = 1.0 / (Math.tan(fov * 0.5));
  6309. var a = isVerticalFovFixed ? (t / aspect) : t;
  6310. var b = isVerticalFovFixed ? t : (t * aspect);
  6311. var c = -(f + n) / (f - n);
  6312. var d = -2 * f * n / (f - n);
  6313. 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);
  6314. };
  6315. /**
  6316. * Stores a perspective projection for WebVR info a given matrix
  6317. * @param fov defines the field of view
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6322. */
  6323. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6324. if (rightHanded === void 0) { rightHanded = false; }
  6325. var rightHandedFactor = rightHanded ? -1 : 1;
  6326. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6327. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6328. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6329. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6330. var xScale = 2.0 / (leftTan + rightTan);
  6331. var yScale = 2.0 / (upTan + downTan);
  6332. result.m[0] = xScale;
  6333. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6334. result.m[5] = yScale;
  6335. result.m[6] = result.m[7] = 0.0;
  6336. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6337. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6338. result.m[10] = -zfar / (znear - zfar);
  6339. result.m[11] = 1.0 * rightHandedFactor;
  6340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6341. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6342. result._markAsUpdated();
  6343. };
  6344. /**
  6345. * Computes a complete transformation matrix
  6346. * @param viewport defines the viewport to use
  6347. * @param world defines the world matrix
  6348. * @param view defines the view matrix
  6349. * @param projection defines the projection matrix
  6350. * @param zmin defines the near clip plane
  6351. * @param zmax defines the far clip plane
  6352. * @returns the transformation matrix
  6353. */
  6354. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6355. var cw = viewport.width;
  6356. var ch = viewport.height;
  6357. var cx = viewport.x;
  6358. var cy = viewport.y;
  6359. 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);
  6360. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6361. };
  6362. /**
  6363. * Extracts a 2x2 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 4 elements : the 2x2 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix2x2 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1],
  6370. matrix.m[4], matrix.m[5]
  6371. ]);
  6372. };
  6373. /**
  6374. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6375. * @param matrix defines the matrix to use
  6376. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6377. */
  6378. Matrix.GetAsMatrix3x3 = function (matrix) {
  6379. return new Float32Array([
  6380. matrix.m[0], matrix.m[1], matrix.m[2],
  6381. matrix.m[4], matrix.m[5], matrix.m[6],
  6382. matrix.m[8], matrix.m[9], matrix.m[10]
  6383. ]);
  6384. };
  6385. /**
  6386. * Compute the transpose of a given matrix
  6387. * @param matrix defines the matrix to transpose
  6388. * @returns the new matrix
  6389. */
  6390. Matrix.Transpose = function (matrix) {
  6391. var result = new Matrix();
  6392. Matrix.TransposeToRef(matrix, result);
  6393. return result;
  6394. };
  6395. /**
  6396. * Compute the transpose of a matrix and store it in a target matrix
  6397. * @param matrix defines the matrix to transpose
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.TransposeToRef = function (matrix, result) {
  6401. result.m[0] = matrix.m[0];
  6402. result.m[1] = matrix.m[4];
  6403. result.m[2] = matrix.m[8];
  6404. result.m[3] = matrix.m[12];
  6405. result.m[4] = matrix.m[1];
  6406. result.m[5] = matrix.m[5];
  6407. result.m[6] = matrix.m[9];
  6408. result.m[7] = matrix.m[13];
  6409. result.m[8] = matrix.m[2];
  6410. result.m[9] = matrix.m[6];
  6411. result.m[10] = matrix.m[10];
  6412. result.m[11] = matrix.m[14];
  6413. result.m[12] = matrix.m[3];
  6414. result.m[13] = matrix.m[7];
  6415. result.m[14] = matrix.m[11];
  6416. result.m[15] = matrix.m[15];
  6417. };
  6418. /**
  6419. * Computes a reflection matrix from a plane
  6420. * @param plane defines the reflection plane
  6421. * @returns a new matrix
  6422. */
  6423. Matrix.Reflection = function (plane) {
  6424. var matrix = new Matrix();
  6425. Matrix.ReflectionToRef(plane, matrix);
  6426. return matrix;
  6427. };
  6428. /**
  6429. * Computes a reflection matrix from a plane
  6430. * @param plane defines the reflection plane
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.ReflectionToRef = function (plane, result) {
  6434. plane.normalize();
  6435. var x = plane.normal.x;
  6436. var y = plane.normal.y;
  6437. var z = plane.normal.z;
  6438. var temp = -2 * x;
  6439. var temp2 = -2 * y;
  6440. var temp3 = -2 * z;
  6441. result.m[0] = (temp * x) + 1;
  6442. result.m[1] = temp2 * x;
  6443. result.m[2] = temp3 * x;
  6444. result.m[3] = 0.0;
  6445. result.m[4] = temp * y;
  6446. result.m[5] = (temp2 * y) + 1;
  6447. result.m[6] = temp3 * y;
  6448. result.m[7] = 0.0;
  6449. result.m[8] = temp * z;
  6450. result.m[9] = temp2 * z;
  6451. result.m[10] = (temp3 * z) + 1;
  6452. result.m[11] = 0.0;
  6453. result.m[12] = temp * plane.d;
  6454. result.m[13] = temp2 * plane.d;
  6455. result.m[14] = temp3 * plane.d;
  6456. result.m[15] = 1.0;
  6457. result._markAsUpdated();
  6458. };
  6459. /**
  6460. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6461. * @param xaxis defines the value of the 1st axis
  6462. * @param yaxis defines the value of the 2nd axis
  6463. * @param zaxis defines the value of the 3rd axis
  6464. * @param result defines the target matrix
  6465. */
  6466. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6467. result.m[0] = xaxis.x;
  6468. result.m[1] = xaxis.y;
  6469. result.m[2] = xaxis.z;
  6470. result.m[3] = 0.0;
  6471. result.m[4] = yaxis.x;
  6472. result.m[5] = yaxis.y;
  6473. result.m[6] = yaxis.z;
  6474. result.m[7] = 0.0;
  6475. result.m[8] = zaxis.x;
  6476. result.m[9] = zaxis.y;
  6477. result.m[10] = zaxis.z;
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. /**
  6486. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6487. * @param quat defines the quaternion to use
  6488. * @param result defines the target matrix
  6489. */
  6490. Matrix.FromQuaternionToRef = function (quat, result) {
  6491. var xx = quat.x * quat.x;
  6492. var yy = quat.y * quat.y;
  6493. var zz = quat.z * quat.z;
  6494. var xy = quat.x * quat.y;
  6495. var zw = quat.z * quat.w;
  6496. var zx = quat.z * quat.x;
  6497. var yw = quat.y * quat.w;
  6498. var yz = quat.y * quat.z;
  6499. var xw = quat.x * quat.w;
  6500. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6501. result.m[1] = 2.0 * (xy + zw);
  6502. result.m[2] = 2.0 * (zx - yw);
  6503. result.m[3] = 0.0;
  6504. result.m[4] = 2.0 * (xy - zw);
  6505. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6506. result.m[6] = 2.0 * (yz + xw);
  6507. result.m[7] = 0.0;
  6508. result.m[8] = 2.0 * (zx + yw);
  6509. result.m[9] = 2.0 * (yz - xw);
  6510. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6511. result.m[11] = 0.0;
  6512. result.m[12] = 0.0;
  6513. result.m[13] = 0.0;
  6514. result.m[14] = 0.0;
  6515. result.m[15] = 1.0;
  6516. result._markAsUpdated();
  6517. };
  6518. Matrix._tempQuaternion = new Quaternion();
  6519. Matrix._xAxis = Vector3.Zero();
  6520. Matrix._yAxis = Vector3.Zero();
  6521. Matrix._zAxis = Vector3.Zero();
  6522. Matrix._updateFlagSeed = 0;
  6523. Matrix._identityReadOnly = Matrix.Identity();
  6524. return Matrix;
  6525. }());
  6526. BABYLON.Matrix = Matrix;
  6527. var Plane = /** @class */ (function () {
  6528. /**
  6529. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6530. */
  6531. function Plane(a, b, c, d) {
  6532. this.normal = new Vector3(a, b, c);
  6533. this.d = d;
  6534. }
  6535. /**
  6536. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6537. */
  6538. Plane.prototype.asArray = function () {
  6539. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6540. };
  6541. // Methods
  6542. /**
  6543. * Returns a new plane copied from the current Plane.
  6544. */
  6545. Plane.prototype.clone = function () {
  6546. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6547. };
  6548. /**
  6549. * Returns the string "Plane".
  6550. */
  6551. Plane.prototype.getClassName = function () {
  6552. return "Plane";
  6553. };
  6554. /**
  6555. * Returns the Plane hash code.
  6556. */
  6557. Plane.prototype.getHashCode = function () {
  6558. var hash = this.normal.getHashCode();
  6559. hash = (hash * 397) ^ (this.d || 0);
  6560. return hash;
  6561. };
  6562. /**
  6563. * Normalize the current Plane in place.
  6564. * Returns the updated Plane.
  6565. */
  6566. Plane.prototype.normalize = function () {
  6567. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6568. var magnitude = 0.0;
  6569. if (norm !== 0) {
  6570. magnitude = 1.0 / norm;
  6571. }
  6572. this.normal.x *= magnitude;
  6573. this.normal.y *= magnitude;
  6574. this.normal.z *= magnitude;
  6575. this.d *= magnitude;
  6576. return this;
  6577. };
  6578. /**
  6579. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6580. */
  6581. Plane.prototype.transform = function (transformation) {
  6582. var transposedMatrix = Matrix.Transpose(transformation);
  6583. var x = this.normal.x;
  6584. var y = this.normal.y;
  6585. var z = this.normal.z;
  6586. var d = this.d;
  6587. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6588. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6589. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6590. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6591. return new Plane(normalX, normalY, normalZ, finalD);
  6592. };
  6593. /**
  6594. * Returns the dot product (float) of the point coordinates and the plane normal.
  6595. */
  6596. Plane.prototype.dotCoordinate = function (point) {
  6597. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6598. };
  6599. /**
  6600. * Updates the current Plane from the plane defined by the three given points.
  6601. * Returns the updated Plane.
  6602. */
  6603. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6604. var x1 = point2.x - point1.x;
  6605. var y1 = point2.y - point1.y;
  6606. var z1 = point2.z - point1.z;
  6607. var x2 = point3.x - point1.x;
  6608. var y2 = point3.y - point1.y;
  6609. var z2 = point3.z - point1.z;
  6610. var yz = (y1 * z2) - (z1 * y2);
  6611. var xz = (z1 * x2) - (x1 * z2);
  6612. var xy = (x1 * y2) - (y1 * x2);
  6613. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6614. var invPyth;
  6615. if (pyth !== 0) {
  6616. invPyth = 1.0 / pyth;
  6617. }
  6618. else {
  6619. invPyth = 0.0;
  6620. }
  6621. this.normal.x = yz * invPyth;
  6622. this.normal.y = xz * invPyth;
  6623. this.normal.z = xy * invPyth;
  6624. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6625. return this;
  6626. };
  6627. /**
  6628. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6629. */
  6630. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6631. var dot = Vector3.Dot(this.normal, direction);
  6632. return (dot <= epsilon);
  6633. };
  6634. /**
  6635. * Returns the signed distance (float) from the given point to the Plane.
  6636. */
  6637. Plane.prototype.signedDistanceTo = function (point) {
  6638. return Vector3.Dot(point, this.normal) + this.d;
  6639. };
  6640. // Statics
  6641. /**
  6642. * Returns a new Plane from the given array.
  6643. */
  6644. Plane.FromArray = function (array) {
  6645. return new Plane(array[0], array[1], array[2], array[3]);
  6646. };
  6647. /**
  6648. * Returns a new Plane defined by the three given points.
  6649. */
  6650. Plane.FromPoints = function (point1, point2, point3) {
  6651. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6652. result.copyFromPoints(point1, point2, point3);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns a new Plane the normal vector to this plane at the given origin point.
  6657. * Note : the vector "normal" is updated because normalized.
  6658. */
  6659. Plane.FromPositionAndNormal = function (origin, normal) {
  6660. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6661. normal.normalize();
  6662. result.normal = normal;
  6663. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return result;
  6665. };
  6666. /**
  6667. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6668. */
  6669. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6670. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6671. return Vector3.Dot(point, normal) + d;
  6672. };
  6673. return Plane;
  6674. }());
  6675. BABYLON.Plane = Plane;
  6676. var Viewport = /** @class */ (function () {
  6677. /**
  6678. * Creates a Viewport object located at (x, y) and sized (width, height).
  6679. */
  6680. function Viewport(x, y, width, height) {
  6681. this.x = x;
  6682. this.y = y;
  6683. this.width = width;
  6684. this.height = height;
  6685. }
  6686. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6687. if (renderWidthOrEngine.getRenderWidth) {
  6688. var engine = renderWidthOrEngine;
  6689. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6690. }
  6691. var renderWidth = renderWidthOrEngine;
  6692. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6693. };
  6694. /**
  6695. * Returns a new Viewport copied from the current one.
  6696. */
  6697. Viewport.prototype.clone = function () {
  6698. return new Viewport(this.x, this.y, this.width, this.height);
  6699. };
  6700. return Viewport;
  6701. }());
  6702. BABYLON.Viewport = Viewport;
  6703. var Frustum = /** @class */ (function () {
  6704. function Frustum() {
  6705. }
  6706. /**
  6707. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6708. */
  6709. Frustum.GetPlanes = function (transform) {
  6710. var frustumPlanes = [];
  6711. for (var index = 0; index < 6; index++) {
  6712. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6713. }
  6714. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6715. return frustumPlanes;
  6716. };
  6717. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6719. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6720. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6721. frustumPlane.d = transform.m[15] + transform.m[14];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6726. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6727. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6728. frustumPlane.d = transform.m[15] - transform.m[14];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6732. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6733. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6734. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6735. frustumPlane.d = transform.m[15] + transform.m[12];
  6736. frustumPlane.normalize();
  6737. };
  6738. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6742. frustumPlane.d = transform.m[15] - transform.m[12];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6746. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6747. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6748. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6749. frustumPlane.d = transform.m[15] - transform.m[13];
  6750. frustumPlane.normalize();
  6751. };
  6752. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6753. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6754. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6755. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6756. frustumPlane.d = transform.m[15] + transform.m[13];
  6757. frustumPlane.normalize();
  6758. };
  6759. /**
  6760. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6761. */
  6762. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6763. // Near
  6764. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6765. // Far
  6766. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6767. // Left
  6768. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6769. // Right
  6770. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6771. // Top
  6772. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6773. // Bottom
  6774. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6775. };
  6776. return Frustum;
  6777. }());
  6778. BABYLON.Frustum = Frustum;
  6779. /** Defines supported spaces */
  6780. var Space;
  6781. (function (Space) {
  6782. /** Local (object) space */
  6783. Space[Space["LOCAL"] = 0] = "LOCAL";
  6784. /** World space */
  6785. Space[Space["WORLD"] = 1] = "WORLD";
  6786. /** Bone space */
  6787. Space[Space["BONE"] = 2] = "BONE";
  6788. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6789. /** Defines the 3 main axes */
  6790. var Axis = /** @class */ (function () {
  6791. function Axis() {
  6792. }
  6793. /** X axis */
  6794. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6795. /** Y axis */
  6796. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6797. /** Z axis */
  6798. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6799. return Axis;
  6800. }());
  6801. BABYLON.Axis = Axis;
  6802. ;
  6803. var BezierCurve = /** @class */ (function () {
  6804. function BezierCurve() {
  6805. }
  6806. /**
  6807. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6808. */
  6809. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6810. // Extract X (which is equal to time here)
  6811. var f0 = 1 - 3 * x2 + 3 * x1;
  6812. var f1 = 3 * x2 - 6 * x1;
  6813. var f2 = 3 * x1;
  6814. var refinedT = t;
  6815. for (var i = 0; i < 5; i++) {
  6816. var refinedT2 = refinedT * refinedT;
  6817. var refinedT3 = refinedT2 * refinedT;
  6818. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6819. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6820. refinedT -= (x - t) * slope;
  6821. refinedT = Math.min(1, Math.max(0, refinedT));
  6822. }
  6823. // Resolve cubic bezier for the given x
  6824. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6825. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6826. Math.pow(refinedT, 3);
  6827. };
  6828. return BezierCurve;
  6829. }());
  6830. BABYLON.BezierCurve = BezierCurve;
  6831. /**
  6832. * Defines potential orientation for back face culling
  6833. */
  6834. var Orientation;
  6835. (function (Orientation) {
  6836. /**
  6837. * Clockwise
  6838. */
  6839. Orientation[Orientation["CW"] = 0] = "CW";
  6840. /** Counter clockwise */
  6841. Orientation[Orientation["CCW"] = 1] = "CCW";
  6842. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6843. /**
  6844. * Defines angle representation
  6845. */
  6846. var Angle = /** @class */ (function () {
  6847. /**
  6848. * Creates an Angle object of "radians" radians (float).
  6849. */
  6850. function Angle(radians) {
  6851. this._radians = radians;
  6852. if (this._radians < 0.0)
  6853. this._radians += (2.0 * Math.PI);
  6854. }
  6855. /**
  6856. * Get value in degrees
  6857. * @returns the Angle value in degrees (float)
  6858. */
  6859. Angle.prototype.degrees = function () {
  6860. return this._radians * 180.0 / Math.PI;
  6861. };
  6862. /**
  6863. * Get value in radians
  6864. * @returns the Angle value in radians (float)
  6865. */
  6866. Angle.prototype.radians = function () {
  6867. return this._radians;
  6868. };
  6869. /**
  6870. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6871. * @param a defines first vector
  6872. * @param b defines second vector
  6873. * @returns a new Angle
  6874. */
  6875. Angle.BetweenTwoPoints = function (a, b) {
  6876. var delta = b.subtract(a);
  6877. var theta = Math.atan2(delta.y, delta.x);
  6878. return new Angle(theta);
  6879. };
  6880. /**
  6881. * Gets a new Angle object from the given float in radians
  6882. * @param radians defines the angle value in radians
  6883. * @returns a new Angle
  6884. */
  6885. Angle.FromRadians = function (radians) {
  6886. return new Angle(radians);
  6887. };
  6888. /**
  6889. * Gets a new Angle object from the given float in degrees
  6890. * @param degrees defines the angle value in degrees
  6891. * @returns a new Angle
  6892. */
  6893. Angle.FromDegrees = function (degrees) {
  6894. return new Angle(degrees * Math.PI / 180.0);
  6895. };
  6896. return Angle;
  6897. }());
  6898. BABYLON.Angle = Angle;
  6899. var Arc2 = /** @class */ (function () {
  6900. /**
  6901. * Creates an Arc object from the three given points : start, middle and end.
  6902. */
  6903. function Arc2(startPoint, midPoint, endPoint) {
  6904. this.startPoint = startPoint;
  6905. this.midPoint = midPoint;
  6906. this.endPoint = endPoint;
  6907. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6908. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6909. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6910. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6911. 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);
  6912. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6913. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6914. var a1 = this.startAngle.degrees();
  6915. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6916. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6917. // angles correction
  6918. if (a2 - a1 > +180.0)
  6919. a2 -= 360.0;
  6920. if (a2 - a1 < -180.0)
  6921. a2 += 360.0;
  6922. if (a3 - a2 > +180.0)
  6923. a3 -= 360.0;
  6924. if (a3 - a2 < -180.0)
  6925. a3 += 360.0;
  6926. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6927. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6928. }
  6929. return Arc2;
  6930. }());
  6931. BABYLON.Arc2 = Arc2;
  6932. var Path2 = /** @class */ (function () {
  6933. /**
  6934. * Creates a Path2 object from the starting 2D coordinates x and y.
  6935. */
  6936. function Path2(x, y) {
  6937. this._points = new Array();
  6938. this._length = 0.0;
  6939. this.closed = false;
  6940. this._points.push(new Vector2(x, y));
  6941. }
  6942. /**
  6943. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6944. * Returns the updated Path2.
  6945. */
  6946. Path2.prototype.addLineTo = function (x, y) {
  6947. if (this.closed) {
  6948. return this;
  6949. }
  6950. var newPoint = new Vector2(x, y);
  6951. var previousPoint = this._points[this._points.length - 1];
  6952. this._points.push(newPoint);
  6953. this._length += newPoint.subtract(previousPoint).length();
  6954. return this;
  6955. };
  6956. /**
  6957. * 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.
  6958. * Returns the updated Path2.
  6959. */
  6960. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6961. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6962. if (this.closed) {
  6963. return this;
  6964. }
  6965. var startPoint = this._points[this._points.length - 1];
  6966. var midPoint = new Vector2(midX, midY);
  6967. var endPoint = new Vector2(endX, endY);
  6968. var arc = new Arc2(startPoint, midPoint, endPoint);
  6969. var increment = arc.angle.radians() / numberOfSegments;
  6970. if (arc.orientation === Orientation.CW)
  6971. increment *= -1;
  6972. var currentAngle = arc.startAngle.radians() + increment;
  6973. for (var i = 0; i < numberOfSegments; i++) {
  6974. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6975. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6976. this.addLineTo(x, y);
  6977. currentAngle += increment;
  6978. }
  6979. return this;
  6980. };
  6981. /**
  6982. * Closes the Path2.
  6983. * Returns the Path2.
  6984. */
  6985. Path2.prototype.close = function () {
  6986. this.closed = true;
  6987. return this;
  6988. };
  6989. /**
  6990. * Returns the Path2 total length (float).
  6991. */
  6992. Path2.prototype.length = function () {
  6993. var result = this._length;
  6994. if (!this.closed) {
  6995. var lastPoint = this._points[this._points.length - 1];
  6996. var firstPoint = this._points[0];
  6997. result += (firstPoint.subtract(lastPoint).length());
  6998. }
  6999. return result;
  7000. };
  7001. /**
  7002. * Returns the Path2 internal array of points.
  7003. */
  7004. Path2.prototype.getPoints = function () {
  7005. return this._points;
  7006. };
  7007. /**
  7008. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7009. */
  7010. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7011. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7012. return Vector2.Zero();
  7013. }
  7014. var lengthPosition = normalizedLengthPosition * this.length();
  7015. var previousOffset = 0;
  7016. for (var i = 0; i < this._points.length; i++) {
  7017. var j = (i + 1) % this._points.length;
  7018. var a = this._points[i];
  7019. var b = this._points[j];
  7020. var bToA = b.subtract(a);
  7021. var nextOffset = (bToA.length() + previousOffset);
  7022. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7023. var dir = bToA.normalize();
  7024. var localOffset = lengthPosition - previousOffset;
  7025. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7026. }
  7027. previousOffset = nextOffset;
  7028. }
  7029. return Vector2.Zero();
  7030. };
  7031. /**
  7032. * Returns a new Path2 starting at the coordinates (x, y).
  7033. */
  7034. Path2.StartingAt = function (x, y) {
  7035. return new Path2(x, y);
  7036. };
  7037. return Path2;
  7038. }());
  7039. BABYLON.Path2 = Path2;
  7040. var Path3D = /** @class */ (function () {
  7041. /**
  7042. * new Path3D(path, normal, raw)
  7043. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7044. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7045. * path : an array of Vector3, the curve axis of the Path3D
  7046. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7047. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7048. */
  7049. function Path3D(path, firstNormal, raw) {
  7050. if (firstNormal === void 0) { firstNormal = null; }
  7051. this.path = path;
  7052. this._curve = new Array();
  7053. this._distances = new Array();
  7054. this._tangents = new Array();
  7055. this._normals = new Array();
  7056. this._binormals = new Array();
  7057. for (var p = 0; p < path.length; p++) {
  7058. this._curve[p] = path[p].clone(); // hard copy
  7059. }
  7060. this._raw = raw || false;
  7061. this._compute(firstNormal);
  7062. }
  7063. /**
  7064. * Returns the Path3D array of successive Vector3 designing its curve.
  7065. */
  7066. Path3D.prototype.getCurve = function () {
  7067. return this._curve;
  7068. };
  7069. /**
  7070. * Returns an array populated with tangent vectors on each Path3D curve point.
  7071. */
  7072. Path3D.prototype.getTangents = function () {
  7073. return this._tangents;
  7074. };
  7075. /**
  7076. * Returns an array populated with normal vectors on each Path3D curve point.
  7077. */
  7078. Path3D.prototype.getNormals = function () {
  7079. return this._normals;
  7080. };
  7081. /**
  7082. * Returns an array populated with binormal vectors on each Path3D curve point.
  7083. */
  7084. Path3D.prototype.getBinormals = function () {
  7085. return this._binormals;
  7086. };
  7087. /**
  7088. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7089. */
  7090. Path3D.prototype.getDistances = function () {
  7091. return this._distances;
  7092. };
  7093. /**
  7094. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7095. * Returns the same object updated.
  7096. */
  7097. Path3D.prototype.update = function (path, firstNormal) {
  7098. if (firstNormal === void 0) { firstNormal = null; }
  7099. for (var p = 0; p < path.length; p++) {
  7100. this._curve[p].x = path[p].x;
  7101. this._curve[p].y = path[p].y;
  7102. this._curve[p].z = path[p].z;
  7103. }
  7104. this._compute(firstNormal);
  7105. return this;
  7106. };
  7107. // private function compute() : computes tangents, normals and binormals
  7108. Path3D.prototype._compute = function (firstNormal) {
  7109. var l = this._curve.length;
  7110. // first and last tangents
  7111. this._tangents[0] = this._getFirstNonNullVector(0);
  7112. if (!this._raw) {
  7113. this._tangents[0].normalize();
  7114. }
  7115. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7116. if (!this._raw) {
  7117. this._tangents[l - 1].normalize();
  7118. }
  7119. // normals and binormals at first point : arbitrary vector with _normalVector()
  7120. var tg0 = this._tangents[0];
  7121. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7122. this._normals[0] = pp0;
  7123. if (!this._raw) {
  7124. this._normals[0].normalize();
  7125. }
  7126. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7127. if (!this._raw) {
  7128. this._binormals[0].normalize();
  7129. }
  7130. this._distances[0] = 0.0;
  7131. // normals and binormals : next points
  7132. var prev; // previous vector (segment)
  7133. var cur; // current vector (segment)
  7134. var curTang; // current tangent
  7135. // previous normal
  7136. var prevBinor; // previous binormal
  7137. for (var i = 1; i < l; i++) {
  7138. // tangents
  7139. prev = this._getLastNonNullVector(i);
  7140. if (i < l - 1) {
  7141. cur = this._getFirstNonNullVector(i);
  7142. this._tangents[i] = prev.add(cur);
  7143. this._tangents[i].normalize();
  7144. }
  7145. this._distances[i] = this._distances[i - 1] + prev.length();
  7146. // normals and binormals
  7147. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7148. curTang = this._tangents[i];
  7149. prevBinor = this._binormals[i - 1];
  7150. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7151. if (!this._raw) {
  7152. this._normals[i].normalize();
  7153. }
  7154. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7155. if (!this._raw) {
  7156. this._binormals[i].normalize();
  7157. }
  7158. }
  7159. };
  7160. // private function getFirstNonNullVector(index)
  7161. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7162. Path3D.prototype._getFirstNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7165. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7166. i++;
  7167. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7168. }
  7169. return nNVector;
  7170. };
  7171. // private function getLastNonNullVector(index)
  7172. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7173. Path3D.prototype._getLastNonNullVector = function (index) {
  7174. var i = 1;
  7175. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7176. while (nLVector.length() === 0 && index > i + 1) {
  7177. i++;
  7178. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7179. }
  7180. return nLVector;
  7181. };
  7182. // private function normalVector(v0, vt, va) :
  7183. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7184. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7185. Path3D.prototype._normalVector = function (v0, vt, va) {
  7186. var normal0;
  7187. var tgl = vt.length();
  7188. if (tgl === 0.0) {
  7189. tgl = 1.0;
  7190. }
  7191. if (va === undefined || va === null) {
  7192. var point;
  7193. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7194. point = new Vector3(0.0, -1.0, 0.0);
  7195. }
  7196. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7197. point = new Vector3(1.0, 0.0, 0.0);
  7198. }
  7199. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7200. point = new Vector3(0.0, 0.0, 1.0);
  7201. }
  7202. else {
  7203. point = Vector3.Zero();
  7204. }
  7205. normal0 = Vector3.Cross(vt, point);
  7206. }
  7207. else {
  7208. normal0 = Vector3.Cross(vt, va);
  7209. Vector3.CrossToRef(normal0, vt, normal0);
  7210. }
  7211. normal0.normalize();
  7212. return normal0;
  7213. };
  7214. return Path3D;
  7215. }());
  7216. BABYLON.Path3D = Path3D;
  7217. var Curve3 = /** @class */ (function () {
  7218. /**
  7219. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7220. * A Curve3 is designed from a series of successive Vector3.
  7221. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7222. */
  7223. function Curve3(points) {
  7224. this._length = 0.0;
  7225. this._points = points;
  7226. this._length = this._computeLength(points);
  7227. }
  7228. /**
  7229. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7230. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7231. * @param v1 (Vector3) the control point
  7232. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7233. * @param nbPoints (integer) the wanted number of points in the curve
  7234. */
  7235. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7236. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7237. var bez = new Array();
  7238. var equation = function (t, val0, val1, val2) {
  7239. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7240. return res;
  7241. };
  7242. for (var i = 0; i <= nbPoints; i++) {
  7243. 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)));
  7244. }
  7245. return new Curve3(bez);
  7246. };
  7247. /**
  7248. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7249. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7250. * @param v1 (Vector3) the first control point
  7251. * @param v2 (Vector3) the second control point
  7252. * @param v3 (Vector3) the end point of the Cubic Bezier
  7253. * @param nbPoints (integer) the wanted number of points in the curve
  7254. */
  7255. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7256. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7257. var bez = new Array();
  7258. var equation = function (t, val0, val1, val2, val3) {
  7259. 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;
  7260. return res;
  7261. };
  7262. for (var i = 0; i <= nbPoints; i++) {
  7263. 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)));
  7264. }
  7265. return new Curve3(bez);
  7266. };
  7267. /**
  7268. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7269. * @param p1 (Vector3) the origin point of the Hermite Spline
  7270. * @param t1 (Vector3) the tangent vector at the origin point
  7271. * @param p2 (Vector3) the end point of the Hermite Spline
  7272. * @param t2 (Vector3) the tangent vector at the end point
  7273. * @param nbPoints (integer) the wanted number of points in the curve
  7274. */
  7275. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7276. var hermite = new Array();
  7277. var step = 1.0 / nbPoints;
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7280. }
  7281. return new Curve3(hermite);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a CatmullRom Spline curve :
  7285. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7286. * @param nbPoints (integer) the wanted number of points between each curve control points
  7287. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7288. */
  7289. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7290. var catmullRom = new Array();
  7291. var step = 1.0 / nbPoints;
  7292. var amount = 0.0;
  7293. if (closed) {
  7294. var pointsCount = points.length;
  7295. for (var i = 0; i < pointsCount; i++) {
  7296. amount = 0;
  7297. for (var c = 0; c < nbPoints; c++) {
  7298. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7299. amount += step;
  7300. }
  7301. }
  7302. catmullRom.push(catmullRom[0]);
  7303. }
  7304. else {
  7305. var totalPoints = new Array();
  7306. totalPoints.push(points[0].clone());
  7307. Array.prototype.push.apply(totalPoints, points);
  7308. totalPoints.push(points[points.length - 1].clone());
  7309. for (var i = 0; i < totalPoints.length - 3; i++) {
  7310. amount = 0;
  7311. for (var c = 0; c < nbPoints; c++) {
  7312. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7313. amount += step;
  7314. }
  7315. }
  7316. i--;
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. }
  7319. return new Curve3(catmullRom);
  7320. };
  7321. /**
  7322. * Returns the Curve3 stored array of successive Vector3
  7323. */
  7324. Curve3.prototype.getPoints = function () {
  7325. return this._points;
  7326. };
  7327. /**
  7328. * Returns the computed length (float) of the curve.
  7329. */
  7330. Curve3.prototype.length = function () {
  7331. return this._length;
  7332. };
  7333. /**
  7334. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7335. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7336. * curveA and curveB keep unchanged.
  7337. */
  7338. Curve3.prototype.continue = function (curve) {
  7339. var lastPoint = this._points[this._points.length - 1];
  7340. var continuedPoints = this._points.slice();
  7341. var curvePoints = curve.getPoints();
  7342. for (var i = 1; i < curvePoints.length; i++) {
  7343. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7344. }
  7345. var continuedCurve = new Curve3(continuedPoints);
  7346. return continuedCurve;
  7347. };
  7348. Curve3.prototype._computeLength = function (path) {
  7349. var l = 0;
  7350. for (var i = 1; i < path.length; i++) {
  7351. l += (path[i].subtract(path[i - 1])).length();
  7352. }
  7353. return l;
  7354. };
  7355. return Curve3;
  7356. }());
  7357. BABYLON.Curve3 = Curve3;
  7358. // Vertex formats
  7359. var PositionNormalVertex = /** @class */ (function () {
  7360. function PositionNormalVertex(position, normal) {
  7361. if (position === void 0) { position = Vector3.Zero(); }
  7362. if (normal === void 0) { normal = Vector3.Up(); }
  7363. this.position = position;
  7364. this.normal = normal;
  7365. }
  7366. PositionNormalVertex.prototype.clone = function () {
  7367. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7368. };
  7369. return PositionNormalVertex;
  7370. }());
  7371. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7372. var PositionNormalTextureVertex = /** @class */ (function () {
  7373. function PositionNormalTextureVertex(position, normal, uv) {
  7374. if (position === void 0) { position = Vector3.Zero(); }
  7375. if (normal === void 0) { normal = Vector3.Up(); }
  7376. if (uv === void 0) { uv = Vector2.Zero(); }
  7377. this.position = position;
  7378. this.normal = normal;
  7379. this.uv = uv;
  7380. }
  7381. PositionNormalTextureVertex.prototype.clone = function () {
  7382. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7383. };
  7384. return PositionNormalTextureVertex;
  7385. }());
  7386. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7387. // Temporary pre-allocated objects for engine internal use
  7388. // usage in any internal function :
  7389. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7390. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7391. var Tmp = /** @class */ (function () {
  7392. function Tmp() {
  7393. }
  7394. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7395. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7396. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7397. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7398. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7399. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7400. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7401. Matrix.Zero(), Matrix.Zero(),
  7402. Matrix.Zero(), Matrix.Zero(),
  7403. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7404. return Tmp;
  7405. }());
  7406. BABYLON.Tmp = Tmp;
  7407. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7408. var MathTmp = /** @class */ (function () {
  7409. function MathTmp() {
  7410. }
  7411. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7412. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7413. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7414. return MathTmp;
  7415. }());
  7416. })(BABYLON || (BABYLON = {}));
  7417. //# sourceMappingURL=babylon.math.js.map
  7418. var BABYLON;
  7419. (function (BABYLON) {
  7420. var Scalar = /** @class */ (function () {
  7421. function Scalar() {
  7422. }
  7423. /**
  7424. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7425. */
  7426. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7427. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7428. var num = a - b;
  7429. return -epsilon <= num && num <= epsilon;
  7430. };
  7431. /**
  7432. * Returns a string : the upper case translation of the number i to hexadecimal.
  7433. */
  7434. Scalar.ToHex = function (i) {
  7435. var str = i.toString(16);
  7436. if (i <= 15) {
  7437. return ("0" + str).toUpperCase();
  7438. }
  7439. return str.toUpperCase();
  7440. };
  7441. /**
  7442. * Returns -1 if value is negative and +1 is value is positive.
  7443. * Returns the value itself if it's equal to zero.
  7444. */
  7445. Scalar.Sign = function (value) {
  7446. value = +value; // convert to a number
  7447. if (value === 0 || isNaN(value))
  7448. return value;
  7449. return value > 0 ? 1 : -1;
  7450. };
  7451. /**
  7452. * Returns the value itself if it's between min and max.
  7453. * Returns min if the value is lower than min.
  7454. * Returns max if the value is greater than max.
  7455. */
  7456. Scalar.Clamp = function (value, min, max) {
  7457. if (min === void 0) { min = 0; }
  7458. if (max === void 0) { max = 1; }
  7459. return Math.min(max, Math.max(min, value));
  7460. };
  7461. /**
  7462. * Returns the log2 of value.
  7463. */
  7464. Scalar.Log2 = function (value) {
  7465. return Math.log(value) * Math.LOG2E;
  7466. };
  7467. /**
  7468. * Loops the value, so that it is never larger than length and never smaller than 0.
  7469. *
  7470. * This is similar to the modulo operator but it works with floating point numbers.
  7471. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7472. * With t = 5 and length = 2.5, the result would be 0.0.
  7473. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7474. */
  7475. Scalar.Repeat = function (value, length) {
  7476. return value - Math.floor(value / length) * length;
  7477. };
  7478. /**
  7479. * Normalize the value between 0.0 and 1.0 using min and max values
  7480. */
  7481. Scalar.Normalize = function (value, min, max) {
  7482. return (value - min) / (max - min);
  7483. };
  7484. /**
  7485. * Denormalize the value from 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Denormalize = function (normalized, min, max) {
  7488. return (normalized * (max - min) + min);
  7489. };
  7490. /**
  7491. * Calculates the shortest difference between two given angles given in degrees.
  7492. */
  7493. Scalar.DeltaAngle = function (current, target) {
  7494. var num = Scalar.Repeat(target - current, 360.0);
  7495. if (num > 180.0) {
  7496. num -= 360.0;
  7497. }
  7498. return num;
  7499. };
  7500. /**
  7501. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * The returned value will move back and forth between 0 and length
  7504. */
  7505. Scalar.PingPong = function (tx, length) {
  7506. var t = Scalar.Repeat(tx, length * 2.0);
  7507. return length - Math.abs(t - length);
  7508. };
  7509. /**
  7510. * Interpolates between min and max with smoothing at the limits.
  7511. *
  7512. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7513. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7514. */
  7515. Scalar.SmoothStep = function (from, to, tx) {
  7516. var t = Scalar.Clamp(tx);
  7517. t = -2.0 * t * t * t + 3.0 * t * t;
  7518. return to * t + from * (1.0 - t);
  7519. };
  7520. /**
  7521. * Moves a value current towards target.
  7522. *
  7523. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7524. * Negative values of maxDelta pushes the value away from target.
  7525. */
  7526. Scalar.MoveTowards = function (current, target, maxDelta) {
  7527. var result = 0;
  7528. if (Math.abs(target - current) <= maxDelta) {
  7529. result = target;
  7530. }
  7531. else {
  7532. result = current + Scalar.Sign(target - current) * maxDelta;
  7533. }
  7534. return result;
  7535. };
  7536. /**
  7537. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7538. *
  7539. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7540. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7541. */
  7542. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7543. var num = Scalar.DeltaAngle(current, target);
  7544. var result = 0;
  7545. if (-maxDelta < num && num < maxDelta) {
  7546. result = target;
  7547. }
  7548. else {
  7549. target = current + num;
  7550. result = Scalar.MoveTowards(current, target, maxDelta);
  7551. }
  7552. return result;
  7553. };
  7554. /**
  7555. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7556. */
  7557. Scalar.Lerp = function (start, end, amount) {
  7558. return start + ((end - start) * amount);
  7559. };
  7560. /**
  7561. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7562. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7563. */
  7564. Scalar.LerpAngle = function (start, end, amount) {
  7565. var num = Scalar.Repeat(end - start, 360.0);
  7566. if (num > 180.0) {
  7567. num -= 360.0;
  7568. }
  7569. return start + num * Scalar.Clamp(amount);
  7570. };
  7571. /**
  7572. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7573. */
  7574. Scalar.InverseLerp = function (a, b, value) {
  7575. var result = 0;
  7576. if (a != b) {
  7577. result = Scalar.Clamp((value - a) / (b - a));
  7578. }
  7579. else {
  7580. result = 0.0;
  7581. }
  7582. return result;
  7583. };
  7584. /**
  7585. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7586. */
  7587. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7588. var squared = amount * amount;
  7589. var cubed = amount * squared;
  7590. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7591. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7592. var part3 = (cubed - (2.0 * squared)) + amount;
  7593. var part4 = cubed - squared;
  7594. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7595. };
  7596. /**
  7597. * Returns a random float number between and min and max values
  7598. */
  7599. Scalar.RandomRange = function (min, max) {
  7600. if (min === max)
  7601. return min;
  7602. return ((Math.random() * (max - min)) + min);
  7603. };
  7604. /**
  7605. * This function returns percentage of a number in a given range.
  7606. *
  7607. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7608. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7609. */
  7610. Scalar.RangeToPercent = function (number, min, max) {
  7611. return ((number - min) / (max - min));
  7612. };
  7613. /**
  7614. * This function returns number that corresponds to the percentage in a given range.
  7615. *
  7616. * PercentToRange(0.34,0,100) will return 34.
  7617. */
  7618. Scalar.PercentToRange = function (percent, min, max) {
  7619. return ((max - min) * percent + min);
  7620. };
  7621. /**
  7622. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7623. * @param angle The angle to normalize in radian.
  7624. * @return The converted angle.
  7625. */
  7626. Scalar.NormalizeRadians = function (angle) {
  7627. // More precise but slower version kept for reference.
  7628. // angle = angle % Tools.TwoPi;
  7629. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7630. //if (angle > Math.PI) {
  7631. // angle -= Tools.TwoPi;
  7632. //}
  7633. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7634. return angle;
  7635. };
  7636. /**
  7637. * Two pi constants convenient for computation.
  7638. */
  7639. Scalar.TwoPi = Math.PI * 2;
  7640. return Scalar;
  7641. }());
  7642. BABYLON.Scalar = Scalar;
  7643. })(BABYLON || (BABYLON = {}));
  7644. //# sourceMappingURL=babylon.math.scalar.js.map
  7645. //# sourceMappingURL=babylon.mixins.js.map
  7646. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7647. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7648. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7649. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7650. //# sourceMappingURL=babylon.webgl2.js.map
  7651. var BABYLON;
  7652. (function (BABYLON) {
  7653. var __decoratorInitialStore = {};
  7654. var __mergedStore = {};
  7655. var _copySource = function (creationFunction, source, instanciate) {
  7656. var destination = creationFunction();
  7657. // Tags
  7658. if (BABYLON.Tags) {
  7659. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7660. }
  7661. var classStore = getMergedStore(destination);
  7662. // Properties
  7663. for (var property in classStore) {
  7664. var propertyDescriptor = classStore[property];
  7665. var sourceProperty = source[property];
  7666. var propertyType = propertyDescriptor.type;
  7667. if (sourceProperty !== undefined && sourceProperty !== null) {
  7668. switch (propertyType) {
  7669. case 0: // Value
  7670. case 6: // Mesh reference
  7671. case 11: // Camera reference
  7672. destination[property] = sourceProperty;
  7673. break;
  7674. case 1: // Texture
  7675. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7676. break;
  7677. case 2: // Color3
  7678. case 3: // FresnelParameters
  7679. case 4: // Vector2
  7680. case 5: // Vector3
  7681. case 7: // Color Curves
  7682. case 10: // Quaternion
  7683. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7684. break;
  7685. }
  7686. }
  7687. }
  7688. return destination;
  7689. };
  7690. function getDirectStore(target) {
  7691. var classKey = target.getClassName();
  7692. if (!__decoratorInitialStore[classKey]) {
  7693. __decoratorInitialStore[classKey] = {};
  7694. }
  7695. return __decoratorInitialStore[classKey];
  7696. }
  7697. /**
  7698. * Return the list of properties flagged as serializable
  7699. * @param target: host object
  7700. */
  7701. function getMergedStore(target) {
  7702. var classKey = target.getClassName();
  7703. if (__mergedStore[classKey]) {
  7704. return __mergedStore[classKey];
  7705. }
  7706. __mergedStore[classKey] = {};
  7707. var store = __mergedStore[classKey];
  7708. var currentTarget = target;
  7709. var currentKey = classKey;
  7710. while (currentKey) {
  7711. var initialStore = __decoratorInitialStore[currentKey];
  7712. for (var property in initialStore) {
  7713. store[property] = initialStore[property];
  7714. }
  7715. var parent_1 = void 0;
  7716. var done = false;
  7717. do {
  7718. parent_1 = Object.getPrototypeOf(currentTarget);
  7719. if (!parent_1.getClassName) {
  7720. done = true;
  7721. break;
  7722. }
  7723. if (parent_1.getClassName() !== currentKey) {
  7724. break;
  7725. }
  7726. currentTarget = parent_1;
  7727. } while (parent_1);
  7728. if (done) {
  7729. break;
  7730. }
  7731. currentKey = parent_1.getClassName();
  7732. currentTarget = parent_1;
  7733. }
  7734. return store;
  7735. }
  7736. function generateSerializableMember(type, sourceName) {
  7737. return function (target, propertyKey) {
  7738. var classStore = getDirectStore(target);
  7739. if (!classStore[propertyKey]) {
  7740. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7741. }
  7742. };
  7743. }
  7744. function generateExpandMember(setCallback, targetKey) {
  7745. if (targetKey === void 0) { targetKey = null; }
  7746. return function (target, propertyKey) {
  7747. var key = targetKey || ("_" + propertyKey);
  7748. Object.defineProperty(target, propertyKey, {
  7749. get: function () {
  7750. return this[key];
  7751. },
  7752. set: function (value) {
  7753. if (this[key] === value) {
  7754. return;
  7755. }
  7756. this[key] = value;
  7757. target[setCallback].apply(this);
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. };
  7763. }
  7764. function expandToProperty(callback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return generateExpandMember(callback, targetKey);
  7767. }
  7768. BABYLON.expandToProperty = expandToProperty;
  7769. function serialize(sourceName) {
  7770. return generateSerializableMember(0, sourceName); // value member
  7771. }
  7772. BABYLON.serialize = serialize;
  7773. function serializeAsTexture(sourceName) {
  7774. return generateSerializableMember(1, sourceName); // texture member
  7775. }
  7776. BABYLON.serializeAsTexture = serializeAsTexture;
  7777. function serializeAsColor3(sourceName) {
  7778. return generateSerializableMember(2, sourceName); // color3 member
  7779. }
  7780. BABYLON.serializeAsColor3 = serializeAsColor3;
  7781. function serializeAsFresnelParameters(sourceName) {
  7782. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7783. }
  7784. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7785. function serializeAsVector2(sourceName) {
  7786. return generateSerializableMember(4, sourceName); // vector2 member
  7787. }
  7788. BABYLON.serializeAsVector2 = serializeAsVector2;
  7789. function serializeAsVector3(sourceName) {
  7790. return generateSerializableMember(5, sourceName); // vector3 member
  7791. }
  7792. BABYLON.serializeAsVector3 = serializeAsVector3;
  7793. function serializeAsMeshReference(sourceName) {
  7794. return generateSerializableMember(6, sourceName); // mesh reference member
  7795. }
  7796. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7797. function serializeAsColorCurves(sourceName) {
  7798. return generateSerializableMember(7, sourceName); // color curves
  7799. }
  7800. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7801. function serializeAsColor4(sourceName) {
  7802. return generateSerializableMember(8, sourceName); // color 4
  7803. }
  7804. BABYLON.serializeAsColor4 = serializeAsColor4;
  7805. function serializeAsImageProcessingConfiguration(sourceName) {
  7806. return generateSerializableMember(9, sourceName); // image processing
  7807. }
  7808. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7809. function serializeAsQuaternion(sourceName) {
  7810. return generateSerializableMember(10, sourceName); // quaternion member
  7811. }
  7812. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7813. /**
  7814. * Decorator used to define property that can be serialized as reference to a camera
  7815. * @param sourceName defines the name of the property to decorate
  7816. */
  7817. function serializeAsCameraReference(sourceName) {
  7818. return generateSerializableMember(11, sourceName); // camera reference member
  7819. }
  7820. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7821. var SerializationHelper = /** @class */ (function () {
  7822. function SerializationHelper() {
  7823. }
  7824. SerializationHelper.Serialize = function (entity, serializationObject) {
  7825. if (!serializationObject) {
  7826. serializationObject = {};
  7827. }
  7828. // Tags
  7829. if (BABYLON.Tags) {
  7830. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7831. }
  7832. var serializedProperties = getMergedStore(entity);
  7833. // Properties
  7834. for (var property in serializedProperties) {
  7835. var propertyDescriptor = serializedProperties[property];
  7836. var targetPropertyName = propertyDescriptor.sourceName || property;
  7837. var propertyType = propertyDescriptor.type;
  7838. var sourceProperty = entity[property];
  7839. if (sourceProperty !== undefined && sourceProperty !== null) {
  7840. switch (propertyType) {
  7841. case 0: // Value
  7842. serializationObject[targetPropertyName] = sourceProperty;
  7843. break;
  7844. case 1: // Texture
  7845. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7846. break;
  7847. case 2: // Color3
  7848. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7849. break;
  7850. case 3: // FresnelParameters
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 4: // Vector2
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 5: // Vector3
  7857. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7858. break;
  7859. case 6: // Mesh reference
  7860. serializationObject[targetPropertyName] = sourceProperty.id;
  7861. break;
  7862. case 7: // Color Curves
  7863. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7864. break;
  7865. case 8: // Color 4
  7866. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7867. break;
  7868. case 9: // Image Processing
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 10: // Quaternion
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 11: // Camera reference
  7875. serializationObject[targetPropertyName] = sourceProperty.id;
  7876. break;
  7877. }
  7878. }
  7879. }
  7880. return serializationObject;
  7881. };
  7882. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7883. if (rootUrl === void 0) { rootUrl = null; }
  7884. var destination = creationFunction();
  7885. if (!rootUrl) {
  7886. rootUrl = "";
  7887. }
  7888. // Tags
  7889. if (BABYLON.Tags) {
  7890. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7891. }
  7892. var classStore = getMergedStore(destination);
  7893. // Properties
  7894. for (var property in classStore) {
  7895. var propertyDescriptor = classStore[property];
  7896. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7897. var propertyType = propertyDescriptor.type;
  7898. if (sourceProperty !== undefined && sourceProperty !== null) {
  7899. var dest = destination;
  7900. switch (propertyType) {
  7901. case 0: // Value
  7902. dest[property] = sourceProperty;
  7903. break;
  7904. case 1: // Texture
  7905. if (scene) {
  7906. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7907. }
  7908. break;
  7909. case 2: // Color3
  7910. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7911. break;
  7912. case 3: // FresnelParameters
  7913. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7914. break;
  7915. case 4: // Vector2
  7916. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7917. break;
  7918. case 5: // Vector3
  7919. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7920. break;
  7921. case 6: // Mesh reference
  7922. if (scene) {
  7923. dest[property] = scene.getLastMeshByID(sourceProperty);
  7924. }
  7925. break;
  7926. case 7: // Color Curves
  7927. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7928. break;
  7929. case 8: // Color 4
  7930. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7931. break;
  7932. case 9: // Image Processing
  7933. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7934. break;
  7935. case 10: // Quaternion
  7936. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7937. break;
  7938. case 11: // Camera reference
  7939. if (scene) {
  7940. dest[property] = scene.getCameraByID(sourceProperty);
  7941. }
  7942. break;
  7943. }
  7944. }
  7945. }
  7946. return destination;
  7947. };
  7948. SerializationHelper.Clone = function (creationFunction, source) {
  7949. return _copySource(creationFunction, source, false);
  7950. };
  7951. SerializationHelper.Instanciate = function (creationFunction, source) {
  7952. return _copySource(creationFunction, source, true);
  7953. };
  7954. return SerializationHelper;
  7955. }());
  7956. BABYLON.SerializationHelper = SerializationHelper;
  7957. })(BABYLON || (BABYLON = {}));
  7958. //# sourceMappingURL=babylon.decorators.js.map
  7959. var BABYLON;
  7960. (function (BABYLON) {
  7961. /**
  7962. * Wrapper class for promise with external resolve and reject.
  7963. */
  7964. var Deferred = /** @class */ (function () {
  7965. /**
  7966. * Constructor for this deferred object.
  7967. */
  7968. function Deferred() {
  7969. var _this = this;
  7970. this.promise = new Promise(function (resolve, reject) {
  7971. _this._resolve = resolve;
  7972. _this._reject = reject;
  7973. });
  7974. }
  7975. Object.defineProperty(Deferred.prototype, "resolve", {
  7976. /**
  7977. * The resolve method of the promise associated with this deferred object.
  7978. */
  7979. get: function () {
  7980. return this._resolve;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Deferred.prototype, "reject", {
  7986. /**
  7987. * The reject method of the promise associated with this deferred object.
  7988. */
  7989. get: function () {
  7990. return this._reject;
  7991. },
  7992. enumerable: true,
  7993. configurable: true
  7994. });
  7995. return Deferred;
  7996. }());
  7997. BABYLON.Deferred = Deferred;
  7998. })(BABYLON || (BABYLON = {}));
  7999. //# sourceMappingURL=babylon.deferred.js.map
  8000. var BABYLON;
  8001. (function (BABYLON) {
  8002. /**
  8003. * A class serves as a medium between the observable and its observers
  8004. */
  8005. var EventState = /** @class */ (function () {
  8006. /**
  8007. * Create a new EventState
  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. */
  8013. function EventState(mask, skipNextObservers, target, currentTarget) {
  8014. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8015. this.initalize(mask, skipNextObservers, target, currentTarget);
  8016. }
  8017. /**
  8018. * Initialize the current event state
  8019. * @param mask defines the mask associated with this state
  8020. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8021. * @param target defines the original target of the state
  8022. * @param currentTarget defines the current target of the state
  8023. * @returns the current event state
  8024. */
  8025. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8026. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8027. this.mask = mask;
  8028. this.skipNextObservers = skipNextObservers;
  8029. this.target = target;
  8030. this.currentTarget = currentTarget;
  8031. return this;
  8032. };
  8033. return EventState;
  8034. }());
  8035. BABYLON.EventState = EventState;
  8036. /**
  8037. * Represent an Observer registered to a given Observable object.
  8038. */
  8039. var Observer = /** @class */ (function () {
  8040. /**
  8041. * Creates a new observer
  8042. * @param callback defines the callback to call when the observer is notified
  8043. * @param mask defines the mask of the observer (used to filter notifications)
  8044. * @param scope defines the current scope used to restore the JS context
  8045. */
  8046. function Observer(
  8047. /**
  8048. * Defines the callback to call when the observer is notified
  8049. */
  8050. callback,
  8051. /**
  8052. * Defines the mask of the observer (used to filter notifications)
  8053. */
  8054. mask,
  8055. /**
  8056. * Defines the current scope used to restore the JS context
  8057. */
  8058. scope) {
  8059. if (scope === void 0) { scope = null; }
  8060. this.callback = callback;
  8061. this.mask = mask;
  8062. this.scope = scope;
  8063. /** @hidden */
  8064. this._willBeUnregistered = false;
  8065. /**
  8066. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8067. */
  8068. this.unregisterOnNextCall = false;
  8069. }
  8070. return Observer;
  8071. }());
  8072. BABYLON.Observer = Observer;
  8073. /**
  8074. * Represent a list of observers registered to multiple Observables object.
  8075. */
  8076. var MultiObserver = /** @class */ (function () {
  8077. function MultiObserver() {
  8078. }
  8079. /**
  8080. * Release associated resources
  8081. */
  8082. MultiObserver.prototype.dispose = function () {
  8083. if (this._observers && this._observables) {
  8084. for (var index = 0; index < this._observers.length; index++) {
  8085. this._observables[index].remove(this._observers[index]);
  8086. }
  8087. }
  8088. this._observers = null;
  8089. this._observables = null;
  8090. };
  8091. /**
  8092. * Raise a callback when one of the observable will notify
  8093. * @param observables defines a list of observables to watch
  8094. * @param callback defines the callback to call on notification
  8095. * @param mask defines the mask used to filter notifications
  8096. * @param scope defines the current scope used to restore the JS context
  8097. * @returns the new MultiObserver
  8098. */
  8099. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8100. if (mask === void 0) { mask = -1; }
  8101. if (scope === void 0) { scope = null; }
  8102. var result = new MultiObserver();
  8103. result._observers = new Array();
  8104. result._observables = observables;
  8105. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8106. var observable = observables_1[_i];
  8107. var observer = observable.add(callback, mask, false, scope);
  8108. if (observer) {
  8109. result._observers.push(observer);
  8110. }
  8111. }
  8112. return result;
  8113. };
  8114. return MultiObserver;
  8115. }());
  8116. BABYLON.MultiObserver = MultiObserver;
  8117. /**
  8118. * The Observable class is a simple implementation of the Observable pattern.
  8119. *
  8120. * 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.
  8121. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8122. * 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).
  8123. * 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.
  8124. */
  8125. var Observable = /** @class */ (function () {
  8126. /**
  8127. * Creates a new observable
  8128. * @param onObserverAdded defines a callback to call when a new observer is added
  8129. */
  8130. function Observable(onObserverAdded) {
  8131. this._observers = new Array();
  8132. this._eventState = new EventState(0);
  8133. if (onObserverAdded) {
  8134. this._onObserverAdded = onObserverAdded;
  8135. }
  8136. }
  8137. /**
  8138. * Create a new Observer with the specified callback
  8139. * @param callback the callback that will be executed for that Observer
  8140. * @param mask the mask used to filter observers
  8141. * @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.
  8142. * @param scope optional scope for the callback to be called from
  8143. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8144. * @returns the new observer created for the callback
  8145. */
  8146. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8147. if (mask === void 0) { mask = -1; }
  8148. if (insertFirst === void 0) { insertFirst = false; }
  8149. if (scope === void 0) { scope = null; }
  8150. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8151. if (!callback) {
  8152. return null;
  8153. }
  8154. var observer = new Observer(callback, mask, scope);
  8155. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8156. if (insertFirst) {
  8157. this._observers.unshift(observer);
  8158. }
  8159. else {
  8160. this._observers.push(observer);
  8161. }
  8162. if (this._onObserverAdded) {
  8163. this._onObserverAdded(observer);
  8164. }
  8165. return observer;
  8166. };
  8167. /**
  8168. * Create a new Observer with the specified callback and unregisters after the next notification
  8169. * @param callback the callback that will be executed for that Observer
  8170. * @returns the new observer created for the callback
  8171. */
  8172. Observable.prototype.addOnce = function (callback) {
  8173. return this.add(callback, undefined, undefined, undefined, true);
  8174. };
  8175. /**
  8176. * Remove an Observer from the Observable object
  8177. * @param observer the instance of the Observer to remove
  8178. * @returns false if it doesn't belong to this Observable
  8179. */
  8180. Observable.prototype.remove = function (observer) {
  8181. if (!observer) {
  8182. return false;
  8183. }
  8184. var index = this._observers.indexOf(observer);
  8185. if (index !== -1) {
  8186. this._observers.splice(index, 1);
  8187. return true;
  8188. }
  8189. return false;
  8190. };
  8191. /**
  8192. * Remove a callback from the Observable object
  8193. * @param callback the callback to remove
  8194. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8195. * @returns false if it doesn't belong to this Observable
  8196. */
  8197. Observable.prototype.removeCallback = function (callback, scope) {
  8198. for (var index = 0; index < this._observers.length; index++) {
  8199. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8200. this._observers.splice(index, 1);
  8201. return true;
  8202. }
  8203. }
  8204. return false;
  8205. };
  8206. Observable.prototype._deferUnregister = function (observer) {
  8207. var _this = this;
  8208. observer.unregisterOnNextCall = false;
  8209. observer._willBeUnregistered = true;
  8210. BABYLON.Tools.SetImmediate(function () {
  8211. _this.remove(observer);
  8212. });
  8213. };
  8214. /**
  8215. * Notify all Observers by calling their respective callback with the given data
  8216. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8217. * @param eventData defines the data to send to all observers
  8218. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8219. * @param target defines the original target of the state
  8220. * @param currentTarget defines the current target of the state
  8221. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8222. */
  8223. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8224. if (mask === void 0) { mask = -1; }
  8225. if (!this._observers.length) {
  8226. return true;
  8227. }
  8228. var state = this._eventState;
  8229. state.mask = mask;
  8230. state.target = target;
  8231. state.currentTarget = currentTarget;
  8232. state.skipNextObservers = false;
  8233. state.lastReturnValue = eventData;
  8234. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8235. var obs = _a[_i];
  8236. if (obs._willBeUnregistered) {
  8237. continue;
  8238. }
  8239. if (obs.mask & mask) {
  8240. if (obs.scope) {
  8241. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8242. }
  8243. else {
  8244. state.lastReturnValue = obs.callback(eventData, state);
  8245. }
  8246. if (obs.unregisterOnNextCall) {
  8247. this._deferUnregister(obs);
  8248. }
  8249. }
  8250. if (state.skipNextObservers) {
  8251. return false;
  8252. }
  8253. }
  8254. return true;
  8255. };
  8256. /**
  8257. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8258. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8259. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8260. * and it is crucial that all callbacks will be executed.
  8261. * The order of the callbacks is kept, callbacks are not executed parallel.
  8262. *
  8263. * @param eventData The data to be sent to each callback
  8264. * @param mask is used to filter observers defaults to -1
  8265. * @param target defines the callback target (see EventState)
  8266. * @param currentTarget defines he current object in the bubbling phase
  8267. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8268. */
  8269. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8270. var _this = this;
  8271. if (mask === void 0) { mask = -1; }
  8272. // create an empty promise
  8273. var p = Promise.resolve(eventData);
  8274. // no observers? return this promise.
  8275. if (!this._observers.length) {
  8276. return p;
  8277. }
  8278. var state = this._eventState;
  8279. state.mask = mask;
  8280. state.target = target;
  8281. state.currentTarget = currentTarget;
  8282. state.skipNextObservers = false;
  8283. // execute one callback after another (not using Promise.all, the order is important)
  8284. this._observers.forEach(function (obs) {
  8285. if (state.skipNextObservers) {
  8286. return;
  8287. }
  8288. if (obs._willBeUnregistered) {
  8289. return;
  8290. }
  8291. if (obs.mask & mask) {
  8292. if (obs.scope) {
  8293. p = p.then(function (lastReturnedValue) {
  8294. state.lastReturnValue = lastReturnedValue;
  8295. return obs.callback.apply(obs.scope, [eventData, state]);
  8296. });
  8297. }
  8298. else {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback(eventData, state);
  8302. });
  8303. }
  8304. if (obs.unregisterOnNextCall) {
  8305. _this._deferUnregister(obs);
  8306. }
  8307. }
  8308. });
  8309. // return the eventData
  8310. return p.then(function () { return eventData; });
  8311. };
  8312. /**
  8313. * Notify a specific observer
  8314. * @param observer defines the observer to notify
  8315. * @param eventData defines the data to be sent to each callback
  8316. * @param mask is used to filter observers defaults to -1
  8317. */
  8318. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8319. if (mask === void 0) { mask = -1; }
  8320. var state = this._eventState;
  8321. state.mask = mask;
  8322. state.skipNextObservers = false;
  8323. observer.callback(eventData, state);
  8324. };
  8325. /**
  8326. * Gets a boolean indicating if the observable has at least one observer
  8327. * @returns true is the Observable has at least one Observer registered
  8328. */
  8329. Observable.prototype.hasObservers = function () {
  8330. return this._observers.length > 0;
  8331. };
  8332. /**
  8333. * Clear the list of observers
  8334. */
  8335. Observable.prototype.clear = function () {
  8336. this._observers = new Array();
  8337. this._onObserverAdded = null;
  8338. };
  8339. /**
  8340. * Clone the current observable
  8341. * @returns a new observable
  8342. */
  8343. Observable.prototype.clone = function () {
  8344. var result = new Observable();
  8345. result._observers = this._observers.slice(0);
  8346. return result;
  8347. };
  8348. /**
  8349. * Does this observable handles observer registered with a given mask
  8350. * @param mask defines the mask to be tested
  8351. * @return whether or not one observer registered with the given mask is handeled
  8352. **/
  8353. Observable.prototype.hasSpecificMask = function (mask) {
  8354. if (mask === void 0) { mask = -1; }
  8355. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8356. var obs = _a[_i];
  8357. if (obs.mask & mask || obs.mask === mask) {
  8358. return true;
  8359. }
  8360. }
  8361. return false;
  8362. };
  8363. return Observable;
  8364. }());
  8365. BABYLON.Observable = Observable;
  8366. })(BABYLON || (BABYLON = {}));
  8367. //# sourceMappingURL=babylon.observable.js.map
  8368. var BABYLON;
  8369. (function (BABYLON) {
  8370. var SmartArray = /** @class */ (function () {
  8371. function SmartArray(capacity) {
  8372. this.length = 0;
  8373. this.data = new Array(capacity);
  8374. this._id = SmartArray._GlobalId++;
  8375. }
  8376. SmartArray.prototype.push = function (value) {
  8377. this.data[this.length++] = value;
  8378. if (this.length > this.data.length) {
  8379. this.data.length *= 2;
  8380. }
  8381. };
  8382. SmartArray.prototype.forEach = function (func) {
  8383. for (var index = 0; index < this.length; index++) {
  8384. func(this.data[index]);
  8385. }
  8386. };
  8387. SmartArray.prototype.sort = function (compareFn) {
  8388. this.data.sort(compareFn);
  8389. };
  8390. SmartArray.prototype.reset = function () {
  8391. this.length = 0;
  8392. };
  8393. SmartArray.prototype.dispose = function () {
  8394. this.reset();
  8395. if (this.data) {
  8396. this.data.length = 0;
  8397. this.data = [];
  8398. }
  8399. };
  8400. SmartArray.prototype.concat = function (array) {
  8401. if (array.length === 0) {
  8402. return;
  8403. }
  8404. if (this.length + array.length > this.data.length) {
  8405. this.data.length = (this.length + array.length) * 2;
  8406. }
  8407. for (var index = 0; index < array.length; index++) {
  8408. this.data[this.length++] = (array.data || array)[index];
  8409. }
  8410. };
  8411. SmartArray.prototype.indexOf = function (value) {
  8412. var position = this.data.indexOf(value);
  8413. if (position >= this.length) {
  8414. return -1;
  8415. }
  8416. return position;
  8417. };
  8418. SmartArray.prototype.contains = function (value) {
  8419. return this.data.indexOf(value) !== -1;
  8420. };
  8421. // Statics
  8422. SmartArray._GlobalId = 0;
  8423. return SmartArray;
  8424. }());
  8425. BABYLON.SmartArray = SmartArray;
  8426. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8427. __extends(SmartArrayNoDuplicate, _super);
  8428. function SmartArrayNoDuplicate() {
  8429. var _this = _super !== null && _super.apply(this, arguments) || this;
  8430. _this._duplicateId = 0;
  8431. return _this;
  8432. }
  8433. SmartArrayNoDuplicate.prototype.push = function (value) {
  8434. _super.prototype.push.call(this, value);
  8435. if (!value.__smartArrayFlags) {
  8436. value.__smartArrayFlags = {};
  8437. }
  8438. value.__smartArrayFlags[this._id] = this._duplicateId;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8441. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8442. return false;
  8443. }
  8444. this.push(value);
  8445. return true;
  8446. };
  8447. SmartArrayNoDuplicate.prototype.reset = function () {
  8448. _super.prototype.reset.call(this);
  8449. this._duplicateId++;
  8450. };
  8451. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8452. if (array.length === 0) {
  8453. return;
  8454. }
  8455. if (this.length + array.length > this.data.length) {
  8456. this.data.length = (this.length + array.length) * 2;
  8457. }
  8458. for (var index = 0; index < array.length; index++) {
  8459. var item = (array.data || array)[index];
  8460. this.pushNoDuplicate(item);
  8461. }
  8462. };
  8463. return SmartArrayNoDuplicate;
  8464. }(SmartArray));
  8465. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8466. })(BABYLON || (BABYLON = {}));
  8467. //# sourceMappingURL=babylon.smartArray.js.map
  8468. var BABYLON;
  8469. (function (BABYLON) {
  8470. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8471. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8472. var LoadFileError = /** @class */ (function (_super) {
  8473. __extends(LoadFileError, _super);
  8474. function LoadFileError(message, request) {
  8475. var _this = _super.call(this, message) || this;
  8476. _this.request = request;
  8477. _this.name = "LoadFileError";
  8478. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8479. return _this;
  8480. }
  8481. // Polyfill for Object.setPrototypeOf if necessary.
  8482. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8483. return LoadFileError;
  8484. }(Error));
  8485. BABYLON.LoadFileError = LoadFileError;
  8486. var RetryStrategy = /** @class */ (function () {
  8487. function RetryStrategy() {
  8488. }
  8489. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8490. if (maxRetries === void 0) { maxRetries = 3; }
  8491. if (baseInterval === void 0) { baseInterval = 500; }
  8492. return function (url, request, retryIndex) {
  8493. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8494. return -1;
  8495. }
  8496. return Math.pow(2, retryIndex) * baseInterval;
  8497. };
  8498. };
  8499. return RetryStrategy;
  8500. }());
  8501. BABYLON.RetryStrategy = RetryStrategy;
  8502. // Screenshots
  8503. var screenshotCanvas;
  8504. var cloneValue = function (source, destinationObject) {
  8505. if (!source)
  8506. return null;
  8507. if (source instanceof BABYLON.Mesh) {
  8508. return null;
  8509. }
  8510. if (source instanceof BABYLON.SubMesh) {
  8511. return source.clone(destinationObject);
  8512. }
  8513. else if (source.clone) {
  8514. return source.clone();
  8515. }
  8516. return null;
  8517. };
  8518. var Tools = /** @class */ (function () {
  8519. function Tools() {
  8520. }
  8521. /**
  8522. * Interpolates between a and b via alpha
  8523. * @param a The lower value (returned when alpha = 0)
  8524. * @param b The upper value (returned when alpha = 1)
  8525. * @param alpha The interpolation-factor
  8526. * @return The mixed value
  8527. */
  8528. Tools.Mix = function (a, b, alpha) {
  8529. return a * (1 - alpha) + b * alpha;
  8530. };
  8531. Tools.Instantiate = function (className) {
  8532. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8533. return Tools.RegisteredExternalClasses[className];
  8534. }
  8535. var arr = className.split(".");
  8536. var fn = (window || this);
  8537. for (var i = 0, len = arr.length; i < len; i++) {
  8538. fn = fn[arr[i]];
  8539. }
  8540. if (typeof fn !== "function") {
  8541. return null;
  8542. }
  8543. return fn;
  8544. };
  8545. /**
  8546. * Provides a slice function that will work even on IE
  8547. * @param data defines the array to slice
  8548. * @param start defines the start of the data (optional)
  8549. * @param end defines the end of the data (optional)
  8550. * @returns the new sliced array
  8551. */
  8552. Tools.Slice = function (data, start, end) {
  8553. if (data.slice) {
  8554. return data.slice(start, end);
  8555. }
  8556. return Array.prototype.slice.call(data, start, end);
  8557. };
  8558. Tools.SetImmediate = function (action) {
  8559. if (window.setImmediate) {
  8560. window.setImmediate(action);
  8561. }
  8562. else {
  8563. setTimeout(action, 1);
  8564. }
  8565. };
  8566. Tools.IsExponentOfTwo = function (value) {
  8567. var count = 1;
  8568. do {
  8569. count *= 2;
  8570. } while (count < value);
  8571. return count === value;
  8572. };
  8573. /**
  8574. * Returns the nearest 32-bit single precision float representation of a Number
  8575. * @param value A Number. If the parameter is of a different type, it will get converted
  8576. * to a number or to NaN if it cannot be converted
  8577. * @returns number
  8578. */
  8579. Tools.FloatRound = function (value) {
  8580. if (Math.fround) {
  8581. return Math.fround(value);
  8582. }
  8583. return (Tools._tmpFloatArray[0] = value);
  8584. };
  8585. /**
  8586. * Find the next highest power of two.
  8587. * @param x Number to start search from.
  8588. * @return Next highest power of two.
  8589. */
  8590. Tools.CeilingPOT = function (x) {
  8591. x--;
  8592. x |= x >> 1;
  8593. x |= x >> 2;
  8594. x |= x >> 4;
  8595. x |= x >> 8;
  8596. x |= x >> 16;
  8597. x++;
  8598. return x;
  8599. };
  8600. /**
  8601. * Find the next lowest power of two.
  8602. * @param x Number to start search from.
  8603. * @return Next lowest power of two.
  8604. */
  8605. Tools.FloorPOT = function (x) {
  8606. x = x | (x >> 1);
  8607. x = x | (x >> 2);
  8608. x = x | (x >> 4);
  8609. x = x | (x >> 8);
  8610. x = x | (x >> 16);
  8611. return x - (x >> 1);
  8612. };
  8613. /**
  8614. * Find the nearest power of two.
  8615. * @param x Number to start search from.
  8616. * @return Next nearest power of two.
  8617. */
  8618. Tools.NearestPOT = function (x) {
  8619. var c = Tools.CeilingPOT(x);
  8620. var f = Tools.FloorPOT(x);
  8621. return (c - x) > (x - f) ? f : c;
  8622. };
  8623. Tools.GetExponentOfTwo = function (value, max, mode) {
  8624. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8625. var pot;
  8626. switch (mode) {
  8627. case BABYLON.Engine.SCALEMODE_FLOOR:
  8628. pot = Tools.FloorPOT(value);
  8629. break;
  8630. case BABYLON.Engine.SCALEMODE_NEAREST:
  8631. pot = Tools.NearestPOT(value);
  8632. break;
  8633. case BABYLON.Engine.SCALEMODE_CEILING:
  8634. default:
  8635. pot = Tools.CeilingPOT(value);
  8636. break;
  8637. }
  8638. return Math.min(pot, max);
  8639. };
  8640. Tools.GetFilename = function (path) {
  8641. var index = path.lastIndexOf("/");
  8642. if (index < 0)
  8643. return path;
  8644. return path.substring(index + 1);
  8645. };
  8646. /**
  8647. * Extracts the "folder" part of a path (everything before the filename).
  8648. * @param uri The URI to extract the info from
  8649. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8650. * @returns The "folder" part of the path
  8651. */
  8652. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8653. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8654. var index = uri.lastIndexOf("/");
  8655. if (index < 0) {
  8656. if (returnUnchangedIfNoSlash) {
  8657. return uri;
  8658. }
  8659. return "";
  8660. }
  8661. return uri.substring(0, index + 1);
  8662. };
  8663. Tools.GetDOMTextContent = function (element) {
  8664. var result = "";
  8665. var child = element.firstChild;
  8666. while (child) {
  8667. if (child.nodeType === 3) {
  8668. result += child.textContent;
  8669. }
  8670. child = child.nextSibling;
  8671. }
  8672. return result;
  8673. };
  8674. Tools.ToDegrees = function (angle) {
  8675. return angle * 180 / Math.PI;
  8676. };
  8677. Tools.ToRadians = function (angle) {
  8678. return angle * Math.PI / 180;
  8679. };
  8680. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8681. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8682. var output = "";
  8683. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8684. var i = 0;
  8685. var bytes = new Uint8Array(buffer);
  8686. while (i < bytes.length) {
  8687. chr1 = bytes[i++];
  8688. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8689. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8690. enc1 = chr1 >> 2;
  8691. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8692. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8693. enc4 = chr3 & 63;
  8694. if (isNaN(chr2)) {
  8695. enc3 = enc4 = 64;
  8696. }
  8697. else if (isNaN(chr3)) {
  8698. enc4 = 64;
  8699. }
  8700. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8701. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8702. }
  8703. return "data:image/png;base64," + output;
  8704. };
  8705. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8706. if (bias === void 0) { bias = null; }
  8707. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8708. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8709. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8710. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8711. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8712. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8713. }
  8714. if (bias) {
  8715. minimum.x -= minimum.x * bias.x + bias.y;
  8716. minimum.y -= minimum.y * bias.x + bias.y;
  8717. minimum.z -= minimum.z * bias.x + bias.y;
  8718. maximum.x += maximum.x * bias.x + bias.y;
  8719. maximum.y += maximum.y * bias.x + bias.y;
  8720. maximum.z += maximum.z * bias.x + bias.y;
  8721. }
  8722. return {
  8723. minimum: minimum,
  8724. maximum: maximum
  8725. };
  8726. };
  8727. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8728. if (bias === void 0) { bias = null; }
  8729. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8730. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8731. if (!stride) {
  8732. stride = 3;
  8733. }
  8734. for (var index = start; index < start + count; index++) {
  8735. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8736. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8737. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8738. }
  8739. if (bias) {
  8740. minimum.x -= minimum.x * bias.x + bias.y;
  8741. minimum.y -= minimum.y * bias.x + bias.y;
  8742. minimum.z -= minimum.z * bias.x + bias.y;
  8743. maximum.x += maximum.x * bias.x + bias.y;
  8744. maximum.y += maximum.y * bias.x + bias.y;
  8745. maximum.z += maximum.z * bias.x + bias.y;
  8746. }
  8747. return {
  8748. minimum: minimum,
  8749. maximum: maximum
  8750. };
  8751. };
  8752. Tools.Vector2ArrayFeeder = function (array) {
  8753. return function (index) {
  8754. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8755. var length = isFloatArray ? array.length / 2 : array.length;
  8756. if (index >= length) {
  8757. return null;
  8758. }
  8759. if (isFloatArray) {
  8760. var fa = array;
  8761. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8762. }
  8763. var a = array;
  8764. return a[index];
  8765. };
  8766. };
  8767. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8768. if (bias === void 0) { bias = null; }
  8769. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8770. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8771. var i = 0;
  8772. var cur = feeder(i++);
  8773. while (cur) {
  8774. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8775. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8776. cur = feeder(i++);
  8777. }
  8778. if (bias) {
  8779. minimum.x -= minimum.x * bias.x + bias.y;
  8780. minimum.y -= minimum.y * bias.x + bias.y;
  8781. maximum.x += maximum.x * bias.x + bias.y;
  8782. maximum.y += maximum.y * bias.x + bias.y;
  8783. }
  8784. return {
  8785. minimum: minimum,
  8786. maximum: maximum
  8787. };
  8788. };
  8789. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8790. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8791. return null;
  8792. return Array.isArray(obj) ? obj : [obj];
  8793. };
  8794. // Misc.
  8795. Tools.GetPointerPrefix = function () {
  8796. var eventPrefix = "pointer";
  8797. // Check if pointer events are supported
  8798. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8799. eventPrefix = "mouse";
  8800. }
  8801. return eventPrefix;
  8802. };
  8803. /**
  8804. * @param func - the function to be called
  8805. * @param requester - the object that will request the next frame. Falls back to window.
  8806. */
  8807. Tools.QueueNewFrame = function (func, requester) {
  8808. if (!Tools.IsWindowObjectExist()) {
  8809. return setTimeout(func, 16);
  8810. }
  8811. if (!requester) {
  8812. requester = window;
  8813. }
  8814. if (requester.requestAnimationFrame) {
  8815. return requester.requestAnimationFrame(func);
  8816. }
  8817. else if (requester.msRequestAnimationFrame) {
  8818. return requester.msRequestAnimationFrame(func);
  8819. }
  8820. else if (requester.webkitRequestAnimationFrame) {
  8821. return requester.webkitRequestAnimationFrame(func);
  8822. }
  8823. else if (requester.mozRequestAnimationFrame) {
  8824. return requester.mozRequestAnimationFrame(func);
  8825. }
  8826. else if (requester.oRequestAnimationFrame) {
  8827. return requester.oRequestAnimationFrame(func);
  8828. }
  8829. else {
  8830. return window.setTimeout(func, 16);
  8831. }
  8832. };
  8833. Tools.RequestFullscreen = function (element) {
  8834. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8835. if (!requestFunction)
  8836. return;
  8837. requestFunction.call(element);
  8838. };
  8839. Tools.ExitFullscreen = function () {
  8840. if (document.exitFullscreen) {
  8841. document.exitFullscreen();
  8842. }
  8843. else if (document.mozCancelFullScreen) {
  8844. document.mozCancelFullScreen();
  8845. }
  8846. else if (document.webkitCancelFullScreen) {
  8847. document.webkitCancelFullScreen();
  8848. }
  8849. else if (document.msCancelFullScreen) {
  8850. document.msCancelFullScreen();
  8851. }
  8852. };
  8853. Tools.SetCorsBehavior = function (url, element) {
  8854. if (url && url.indexOf("data:") === 0) {
  8855. return;
  8856. }
  8857. if (Tools.CorsBehavior) {
  8858. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8859. element.crossOrigin = Tools.CorsBehavior;
  8860. }
  8861. else {
  8862. var result = Tools.CorsBehavior(url);
  8863. if (result) {
  8864. element.crossOrigin = result;
  8865. }
  8866. }
  8867. }
  8868. };
  8869. // External files
  8870. Tools.CleanUrl = function (url) {
  8871. url = url.replace(/#/mg, "%23");
  8872. return url;
  8873. };
  8874. /**
  8875. * Loads an image as an HTMLImageElement.
  8876. * @param input url string, ArrayBuffer, or Blob to load
  8877. * @param onLoad callback called when the image successfully loads
  8878. * @param onError callback called when the image fails to load
  8879. * @param database database for caching
  8880. * @returns the HTMLImageElement of the loaded image
  8881. */
  8882. Tools.LoadImage = function (input, onLoad, onError, database) {
  8883. var url;
  8884. var usingObjectURL = false;
  8885. if (input instanceof ArrayBuffer) {
  8886. url = URL.createObjectURL(new Blob([input]));
  8887. usingObjectURL = true;
  8888. }
  8889. else if (input instanceof Blob) {
  8890. url = URL.createObjectURL(input);
  8891. usingObjectURL = true;
  8892. }
  8893. else {
  8894. url = Tools.CleanUrl(input);
  8895. url = Tools.PreprocessUrl(input);
  8896. }
  8897. var img = new Image();
  8898. Tools.SetCorsBehavior(url, img);
  8899. var loadHandler = function () {
  8900. if (usingObjectURL && img.src) {
  8901. URL.revokeObjectURL(img.src);
  8902. }
  8903. img.removeEventListener("load", loadHandler);
  8904. img.removeEventListener("error", errorHandler);
  8905. onLoad(img);
  8906. };
  8907. var errorHandler = function (err) {
  8908. if (usingObjectURL && img.src) {
  8909. URL.revokeObjectURL(img.src);
  8910. }
  8911. img.removeEventListener("load", loadHandler);
  8912. img.removeEventListener("error", errorHandler);
  8913. Tools.Error("Error while trying to load image: " + input);
  8914. if (onError) {
  8915. onError("Error while trying to load image: " + input, err);
  8916. }
  8917. };
  8918. img.addEventListener("load", loadHandler);
  8919. img.addEventListener("error", errorHandler);
  8920. var noIndexedDB = function () {
  8921. img.src = url;
  8922. };
  8923. var loadFromIndexedDB = function () {
  8924. if (database) {
  8925. database.loadImageFromDB(url, img);
  8926. }
  8927. };
  8928. //ANY database to do!
  8929. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8930. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8931. }
  8932. else {
  8933. if (url.indexOf("file:") !== -1) {
  8934. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8935. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8936. try {
  8937. var blobURL;
  8938. try {
  8939. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8940. }
  8941. catch (ex) {
  8942. // Chrome doesn't support oneTimeOnly parameter
  8943. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8944. }
  8945. img.src = blobURL;
  8946. usingObjectURL = true;
  8947. }
  8948. catch (e) {
  8949. img.src = "";
  8950. }
  8951. return img;
  8952. }
  8953. }
  8954. noIndexedDB();
  8955. }
  8956. return img;
  8957. };
  8958. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8959. url = Tools.CleanUrl(url);
  8960. url = Tools.PreprocessUrl(url);
  8961. // If file and file input are set
  8962. if (url.indexOf("file:") !== -1) {
  8963. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8964. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8965. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8966. }
  8967. }
  8968. var loadUrl = Tools.BaseUrl + url;
  8969. var aborted = false;
  8970. var fileRequest = {
  8971. onCompleteObservable: new BABYLON.Observable(),
  8972. abort: function () { return aborted = true; },
  8973. };
  8974. var requestFile = function () {
  8975. var request = new XMLHttpRequest();
  8976. var retryHandle = null;
  8977. fileRequest.abort = function () {
  8978. aborted = true;
  8979. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8980. request.abort();
  8981. }
  8982. if (retryHandle !== null) {
  8983. clearTimeout(retryHandle);
  8984. retryHandle = null;
  8985. }
  8986. };
  8987. var retryLoop = function (retryIndex) {
  8988. request.open('GET', loadUrl, true);
  8989. if (useArrayBuffer) {
  8990. request.responseType = "arraybuffer";
  8991. }
  8992. if (onProgress) {
  8993. request.addEventListener("progress", onProgress);
  8994. }
  8995. var onLoadEnd = function () {
  8996. request.removeEventListener("loadend", onLoadEnd);
  8997. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8998. fileRequest.onCompleteObservable.clear();
  8999. };
  9000. request.addEventListener("loadend", onLoadEnd);
  9001. var onReadyStateChange = function () {
  9002. if (aborted) {
  9003. return;
  9004. }
  9005. // In case of undefined state in some browsers.
  9006. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9007. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9008. request.removeEventListener("readystatechange", onReadyStateChange);
  9009. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9010. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9011. return;
  9012. }
  9013. var retryStrategy = Tools.DefaultRetryStrategy;
  9014. if (retryStrategy) {
  9015. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9016. if (waitTime !== -1) {
  9017. // Prevent the request from completing for retry.
  9018. request.removeEventListener("loadend", onLoadEnd);
  9019. request = new XMLHttpRequest();
  9020. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9021. return;
  9022. }
  9023. }
  9024. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9025. if (onError) {
  9026. onError(request, e);
  9027. }
  9028. else {
  9029. throw e;
  9030. }
  9031. }
  9032. };
  9033. request.addEventListener("readystatechange", onReadyStateChange);
  9034. request.send();
  9035. };
  9036. retryLoop(0);
  9037. };
  9038. // Caching all files
  9039. if (database && database.enableSceneOffline) {
  9040. var noIndexedDB_1 = function () {
  9041. if (!aborted) {
  9042. requestFile();
  9043. }
  9044. };
  9045. var loadFromIndexedDB = function () {
  9046. // TODO: database needs to support aborting and should return a IFileRequest
  9047. if (aborted) {
  9048. return;
  9049. }
  9050. if (database) {
  9051. database.loadFileFromDB(url, function (data) {
  9052. if (!aborted) {
  9053. onSuccess(data);
  9054. }
  9055. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9056. }, onProgress ? function (event) {
  9057. if (!aborted) {
  9058. onProgress(event);
  9059. }
  9060. } : undefined, noIndexedDB_1, useArrayBuffer);
  9061. }
  9062. };
  9063. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9064. }
  9065. else {
  9066. requestFile();
  9067. }
  9068. return fileRequest;
  9069. };
  9070. /**
  9071. * Load a script (identified by an url). When the url returns, the
  9072. * content of this file is added into a new script element, attached to the DOM (body element)
  9073. */
  9074. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9075. var head = document.getElementsByTagName('head')[0];
  9076. var script = document.createElement('script');
  9077. script.type = 'text/javascript';
  9078. script.src = scriptUrl;
  9079. script.onload = function () {
  9080. if (onSuccess) {
  9081. onSuccess();
  9082. }
  9083. };
  9084. script.onerror = function (e) {
  9085. if (onError) {
  9086. onError("Unable to load script '" + scriptUrl + "'", e);
  9087. }
  9088. };
  9089. head.appendChild(script);
  9090. };
  9091. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9092. var reader = new FileReader();
  9093. var request = {
  9094. onCompleteObservable: new BABYLON.Observable(),
  9095. abort: function () { return reader.abort(); },
  9096. };
  9097. reader.onloadend = function (e) {
  9098. request.onCompleteObservable.notifyObservers(request);
  9099. };
  9100. reader.onload = function (e) {
  9101. //target doesn't have result from ts 1.3
  9102. callback(e.target['result']);
  9103. };
  9104. reader.onprogress = progressCallback;
  9105. reader.readAsDataURL(fileToLoad);
  9106. return request;
  9107. };
  9108. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9109. var reader = new FileReader();
  9110. var request = {
  9111. onCompleteObservable: new BABYLON.Observable(),
  9112. abort: function () { return reader.abort(); },
  9113. };
  9114. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9115. reader.onerror = function (e) {
  9116. Tools.Log("Error while reading file: " + fileToLoad.name);
  9117. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9118. };
  9119. reader.onload = function (e) {
  9120. //target doesn't have result from ts 1.3
  9121. callback(e.target['result']);
  9122. };
  9123. if (progressCallBack) {
  9124. reader.onprogress = progressCallBack;
  9125. }
  9126. if (!useArrayBuffer) {
  9127. // Asynchronous read
  9128. reader.readAsText(fileToLoad);
  9129. }
  9130. else {
  9131. reader.readAsArrayBuffer(fileToLoad);
  9132. }
  9133. return request;
  9134. };
  9135. //returns a downloadable url to a file content.
  9136. Tools.FileAsURL = function (content) {
  9137. var fileBlob = new Blob([content]);
  9138. var url = window.URL || window.webkitURL;
  9139. var link = url.createObjectURL(fileBlob);
  9140. return link;
  9141. };
  9142. // Misc.
  9143. Tools.Format = function (value, decimals) {
  9144. if (decimals === void 0) { decimals = 2; }
  9145. return value.toFixed(decimals);
  9146. };
  9147. Tools.CheckExtends = function (v, min, max) {
  9148. if (v.x < min.x)
  9149. min.x = v.x;
  9150. if (v.y < min.y)
  9151. min.y = v.y;
  9152. if (v.z < min.z)
  9153. min.z = v.z;
  9154. if (v.x > max.x)
  9155. max.x = v.x;
  9156. if (v.y > max.y)
  9157. max.y = v.y;
  9158. if (v.z > max.z)
  9159. max.z = v.z;
  9160. };
  9161. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9162. for (var prop in source) {
  9163. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9164. continue;
  9165. }
  9166. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9167. continue;
  9168. }
  9169. var sourceValue = source[prop];
  9170. var typeOfSourceValue = typeof sourceValue;
  9171. if (typeOfSourceValue === "function") {
  9172. continue;
  9173. }
  9174. try {
  9175. if (typeOfSourceValue === "object") {
  9176. if (sourceValue instanceof Array) {
  9177. destination[prop] = [];
  9178. if (sourceValue.length > 0) {
  9179. if (typeof sourceValue[0] == "object") {
  9180. for (var index = 0; index < sourceValue.length; index++) {
  9181. var clonedValue = cloneValue(sourceValue[index], destination);
  9182. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9183. destination[prop].push(clonedValue);
  9184. }
  9185. }
  9186. }
  9187. else {
  9188. destination[prop] = sourceValue.slice(0);
  9189. }
  9190. }
  9191. }
  9192. else {
  9193. destination[prop] = cloneValue(sourceValue, destination);
  9194. }
  9195. }
  9196. else {
  9197. destination[prop] = sourceValue;
  9198. }
  9199. }
  9200. catch (e) {
  9201. // Just ignore error (it could be because of a read-only property)
  9202. }
  9203. }
  9204. };
  9205. Tools.IsEmpty = function (obj) {
  9206. for (var i in obj) {
  9207. if (obj.hasOwnProperty(i)) {
  9208. return false;
  9209. }
  9210. }
  9211. return true;
  9212. };
  9213. Tools.RegisterTopRootEvents = function (events) {
  9214. for (var index = 0; index < events.length; index++) {
  9215. var event = events[index];
  9216. window.addEventListener(event.name, event.handler, false);
  9217. try {
  9218. if (window.parent) {
  9219. window.parent.addEventListener(event.name, event.handler, false);
  9220. }
  9221. }
  9222. catch (e) {
  9223. // Silently fails...
  9224. }
  9225. }
  9226. };
  9227. Tools.UnregisterTopRootEvents = function (events) {
  9228. for (var index = 0; index < events.length; index++) {
  9229. var event = events[index];
  9230. window.removeEventListener(event.name, event.handler);
  9231. try {
  9232. if (window.parent) {
  9233. window.parent.removeEventListener(event.name, event.handler);
  9234. }
  9235. }
  9236. catch (e) {
  9237. // Silently fails...
  9238. }
  9239. }
  9240. };
  9241. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9242. if (mimeType === void 0) { mimeType = "image/png"; }
  9243. // Read the contents of the framebuffer
  9244. var numberOfChannelsByLine = width * 4;
  9245. var halfHeight = height / 2;
  9246. //Reading datas from WebGL
  9247. var data = engine.readPixels(0, 0, width, height);
  9248. //To flip image on Y axis.
  9249. for (var i = 0; i < halfHeight; i++) {
  9250. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9251. var currentCell = j + i * numberOfChannelsByLine;
  9252. var targetLine = height - i - 1;
  9253. var targetCell = j + targetLine * numberOfChannelsByLine;
  9254. var temp = data[currentCell];
  9255. data[currentCell] = data[targetCell];
  9256. data[targetCell] = temp;
  9257. }
  9258. }
  9259. // Create a 2D canvas to store the result
  9260. if (!screenshotCanvas) {
  9261. screenshotCanvas = document.createElement('canvas');
  9262. }
  9263. screenshotCanvas.width = width;
  9264. screenshotCanvas.height = height;
  9265. var context = screenshotCanvas.getContext('2d');
  9266. if (context) {
  9267. // Copy the pixels to a 2D canvas
  9268. var imageData = context.createImageData(width, height);
  9269. var castData = (imageData.data);
  9270. castData.set(data);
  9271. context.putImageData(imageData, 0, 0);
  9272. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9273. }
  9274. };
  9275. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9276. if (mimeType === void 0) { mimeType = "image/png"; }
  9277. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9278. if (successCallback) {
  9279. successCallback(base64Image);
  9280. }
  9281. else {
  9282. // We need HTMLCanvasElement.toBlob for HD screenshots
  9283. if (!screenshotCanvas.toBlob) {
  9284. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9285. screenshotCanvas.toBlob = function (callback, type, quality) {
  9286. var _this = this;
  9287. setTimeout(function () {
  9288. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9289. for (var i = 0; i < len; i++) {
  9290. arr[i] = binStr.charCodeAt(i);
  9291. }
  9292. callback(new Blob([arr], { type: type || 'image/png' }));
  9293. });
  9294. };
  9295. }
  9296. screenshotCanvas.toBlob(function (blob) {
  9297. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9298. if (("download" in document.createElement("a"))) {
  9299. if (!fileName) {
  9300. var date = new Date();
  9301. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9302. fileName = "screenshot_" + stringDate + ".png";
  9303. }
  9304. Tools.Download(blob, fileName);
  9305. }
  9306. else {
  9307. var url = URL.createObjectURL(blob);
  9308. var newWindow = window.open("");
  9309. if (!newWindow)
  9310. return;
  9311. var img = newWindow.document.createElement("img");
  9312. img.onload = function () {
  9313. // no longer need to read the blob so it's revoked
  9314. URL.revokeObjectURL(url);
  9315. };
  9316. img.src = url;
  9317. newWindow.document.body.appendChild(img);
  9318. }
  9319. });
  9320. }
  9321. };
  9322. /**
  9323. * Downloads a blob in the browser
  9324. * @param blob defines the blob to download
  9325. * @param fileName defines the name of the downloaded file
  9326. */
  9327. Tools.Download = function (blob, fileName) {
  9328. var url = window.URL.createObjectURL(blob);
  9329. var a = document.createElement("a");
  9330. document.body.appendChild(a);
  9331. a.style.display = "none";
  9332. a.href = url;
  9333. a.download = fileName;
  9334. a.addEventListener("click", function () {
  9335. if (a.parentElement) {
  9336. a.parentElement.removeChild(a);
  9337. }
  9338. });
  9339. a.click();
  9340. window.URL.revokeObjectURL(url);
  9341. };
  9342. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9343. if (mimeType === void 0) { mimeType = "image/png"; }
  9344. var width;
  9345. var height;
  9346. // If a precision value is specified
  9347. if (size.precision) {
  9348. width = Math.round(engine.getRenderWidth() * size.precision);
  9349. height = Math.round(width / engine.getAspectRatio(camera));
  9350. }
  9351. else if (size.width && size.height) {
  9352. width = size.width;
  9353. height = size.height;
  9354. }
  9355. //If passing only width, computing height to keep display canvas ratio.
  9356. else if (size.width && !size.height) {
  9357. width = size.width;
  9358. height = Math.round(width / engine.getAspectRatio(camera));
  9359. }
  9360. //If passing only height, computing width to keep display canvas ratio.
  9361. else if (size.height && !size.width) {
  9362. height = size.height;
  9363. width = Math.round(height * engine.getAspectRatio(camera));
  9364. }
  9365. //Assuming here that "size" parameter is a number
  9366. else if (!isNaN(size)) {
  9367. height = size;
  9368. width = size;
  9369. }
  9370. else {
  9371. Tools.Error("Invalid 'size' parameter !");
  9372. return;
  9373. }
  9374. if (!screenshotCanvas) {
  9375. screenshotCanvas = document.createElement('canvas');
  9376. }
  9377. screenshotCanvas.width = width;
  9378. screenshotCanvas.height = height;
  9379. var renderContext = screenshotCanvas.getContext("2d");
  9380. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9381. var newWidth = width;
  9382. var newHeight = newWidth / ratio;
  9383. if (newHeight > height) {
  9384. newHeight = height;
  9385. newWidth = newHeight * ratio;
  9386. }
  9387. var offsetX = Math.max(0, width - newWidth) / 2;
  9388. var offsetY = Math.max(0, height - newHeight) / 2;
  9389. var renderingCanvas = engine.getRenderingCanvas();
  9390. if (renderContext && renderingCanvas) {
  9391. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9392. }
  9393. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9394. };
  9395. /**
  9396. * Generates an image screenshot from the specified camera.
  9397. *
  9398. * @param engine The engine to use for rendering
  9399. * @param camera The camera to use for rendering
  9400. * @param size This parameter can be set to a single number or to an object with the
  9401. * following (optional) properties: precision, width, height. If a single number is passed,
  9402. * it will be used for both width and height. If an object is passed, the screenshot size
  9403. * will be derived from the parameters. The precision property is a multiplier allowing
  9404. * rendering at a higher or lower resolution.
  9405. * @param successCallback The callback receives a single parameter which contains the
  9406. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9407. * src parameter of an <img> to display it.
  9408. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9409. * Check your browser for supported MIME types.
  9410. * @param samples Texture samples (default: 1)
  9411. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9412. * @param fileName A name for for the downloaded file.
  9413. * @constructor
  9414. */
  9415. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9416. if (mimeType === void 0) { mimeType = "image/png"; }
  9417. if (samples === void 0) { samples = 1; }
  9418. if (antialiasing === void 0) { antialiasing = false; }
  9419. var width;
  9420. var height;
  9421. //If a precision value is specified
  9422. if (size.precision) {
  9423. width = Math.round(engine.getRenderWidth() * size.precision);
  9424. height = Math.round(width / engine.getAspectRatio(camera));
  9425. size = { width: width, height: height };
  9426. }
  9427. else if (size.width && size.height) {
  9428. width = size.width;
  9429. height = size.height;
  9430. }
  9431. //If passing only width, computing height to keep display canvas ratio.
  9432. else if (size.width && !size.height) {
  9433. width = size.width;
  9434. height = Math.round(width / engine.getAspectRatio(camera));
  9435. size = { width: width, height: height };
  9436. }
  9437. //If passing only height, computing width to keep display canvas ratio.
  9438. else if (size.height && !size.width) {
  9439. height = size.height;
  9440. width = Math.round(height * engine.getAspectRatio(camera));
  9441. size = { width: width, height: height };
  9442. }
  9443. //Assuming here that "size" parameter is a number
  9444. else if (!isNaN(size)) {
  9445. height = size;
  9446. width = size;
  9447. }
  9448. else {
  9449. Tools.Error("Invalid 'size' parameter !");
  9450. return;
  9451. }
  9452. var scene = camera.getScene();
  9453. var previousCamera = null;
  9454. if (scene.activeCamera !== camera) {
  9455. previousCamera = scene.activeCamera;
  9456. scene.activeCamera = camera;
  9457. }
  9458. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9459. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9460. texture.renderList = null;
  9461. texture.samples = samples;
  9462. if (antialiasing) {
  9463. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9464. }
  9465. texture.onAfterRenderObservable.add(function () {
  9466. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9467. });
  9468. scene.incrementRenderId();
  9469. scene.resetCachedMaterial();
  9470. texture.render(true);
  9471. texture.dispose();
  9472. if (previousCamera) {
  9473. scene.activeCamera = previousCamera;
  9474. }
  9475. camera.getProjectionMatrix(true); // Force cache refresh;
  9476. };
  9477. // XHR response validator for local file scenario
  9478. Tools.ValidateXHRData = function (xhr, dataType) {
  9479. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9480. if (dataType === void 0) { dataType = 7; }
  9481. try {
  9482. if (dataType & 1) {
  9483. if (xhr.responseText && xhr.responseText.length > 0) {
  9484. return true;
  9485. }
  9486. else if (dataType === 1) {
  9487. return false;
  9488. }
  9489. }
  9490. if (dataType & 2) {
  9491. // Check header width and height since there is no "TGA" magic number
  9492. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9493. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9494. return true;
  9495. }
  9496. else if (dataType === 2) {
  9497. return false;
  9498. }
  9499. }
  9500. if (dataType & 4) {
  9501. // Check for the "DDS" magic number
  9502. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9503. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9504. return true;
  9505. }
  9506. else {
  9507. return false;
  9508. }
  9509. }
  9510. }
  9511. catch (e) {
  9512. // Global protection
  9513. }
  9514. return false;
  9515. };
  9516. /**
  9517. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9518. * Be aware Math.random() could cause collisions, but:
  9519. * "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"
  9520. */
  9521. Tools.RandomId = function () {
  9522. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9523. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9524. return v.toString(16);
  9525. });
  9526. };
  9527. /**
  9528. * Test if the given uri is a base64 string.
  9529. * @param uri The uri to test
  9530. * @return True if the uri is a base64 string or false otherwise.
  9531. */
  9532. Tools.IsBase64 = function (uri) {
  9533. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9534. };
  9535. /**
  9536. * Decode the given base64 uri.
  9537. * @param uri The uri to decode
  9538. * @return The decoded base64 data.
  9539. */
  9540. Tools.DecodeBase64 = function (uri) {
  9541. var decodedString = atob(uri.split(",")[1]);
  9542. var bufferLength = decodedString.length;
  9543. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9544. for (var i = 0; i < bufferLength; i++) {
  9545. bufferView[i] = decodedString.charCodeAt(i);
  9546. }
  9547. return bufferView.buffer;
  9548. };
  9549. Object.defineProperty(Tools, "NoneLogLevel", {
  9550. get: function () {
  9551. return Tools._NoneLogLevel;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(Tools, "MessageLogLevel", {
  9557. get: function () {
  9558. return Tools._MessageLogLevel;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Tools, "WarningLogLevel", {
  9564. get: function () {
  9565. return Tools._WarningLogLevel;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Tools, "ErrorLogLevel", {
  9571. get: function () {
  9572. return Tools._ErrorLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Tools, "AllLogLevel", {
  9578. get: function () {
  9579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Tools._AddLogEntry = function (entry) {
  9585. Tools._LogCache = entry + Tools._LogCache;
  9586. if (Tools.OnNewCacheEntry) {
  9587. Tools.OnNewCacheEntry(entry);
  9588. }
  9589. };
  9590. Tools._FormatMessage = function (message) {
  9591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9592. var date = new Date();
  9593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9594. };
  9595. Tools._LogDisabled = function (message) {
  9596. // nothing to do
  9597. };
  9598. Tools._LogEnabled = function (message) {
  9599. var formattedMessage = Tools._FormatMessage(message);
  9600. console.log("BJS - " + formattedMessage);
  9601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9602. Tools._AddLogEntry(entry);
  9603. };
  9604. Tools._WarnDisabled = function (message) {
  9605. // nothing to do
  9606. };
  9607. Tools._WarnEnabled = function (message) {
  9608. var formattedMessage = Tools._FormatMessage(message);
  9609. console.warn("BJS - " + formattedMessage);
  9610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9611. Tools._AddLogEntry(entry);
  9612. };
  9613. Tools._ErrorDisabled = function (message) {
  9614. // nothing to do
  9615. };
  9616. Tools._ErrorEnabled = function (message) {
  9617. Tools.errorsCount++;
  9618. var formattedMessage = Tools._FormatMessage(message);
  9619. console.error("BJS - " + formattedMessage);
  9620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9621. Tools._AddLogEntry(entry);
  9622. };
  9623. Object.defineProperty(Tools, "LogCache", {
  9624. get: function () {
  9625. return Tools._LogCache;
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Tools.ClearLogCache = function () {
  9631. Tools._LogCache = "";
  9632. Tools.errorsCount = 0;
  9633. };
  9634. Object.defineProperty(Tools, "LogLevels", {
  9635. set: function (level) {
  9636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9637. Tools.Log = Tools._LogEnabled;
  9638. }
  9639. else {
  9640. Tools.Log = Tools._LogDisabled;
  9641. }
  9642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9643. Tools.Warn = Tools._WarnEnabled;
  9644. }
  9645. else {
  9646. Tools.Warn = Tools._WarnDisabled;
  9647. }
  9648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9649. Tools.Error = Tools._ErrorEnabled;
  9650. }
  9651. else {
  9652. Tools.Error = Tools._ErrorDisabled;
  9653. }
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Tools.IsWindowObjectExist = function () {
  9659. return (typeof window) !== "undefined";
  9660. };
  9661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9662. get: function () {
  9663. return Tools._PerformanceNoneLogLevel;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9669. get: function () {
  9670. return Tools._PerformanceUserMarkLogLevel;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9676. get: function () {
  9677. return Tools._PerformanceConsoleLogLevel;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9683. set: function (level) {
  9684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9687. return;
  9688. }
  9689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9692. return;
  9693. }
  9694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9701. };
  9702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9703. };
  9704. Tools._StartUserMark = function (counterName, condition) {
  9705. if (condition === void 0) { condition = true; }
  9706. if (!Tools._performance) {
  9707. if (!Tools.IsWindowObjectExist()) {
  9708. return;
  9709. }
  9710. Tools._performance = window.performance;
  9711. }
  9712. if (!condition || !Tools._performance.mark) {
  9713. return;
  9714. }
  9715. Tools._performance.mark(counterName + "-Begin");
  9716. };
  9717. Tools._EndUserMark = function (counterName, condition) {
  9718. if (condition === void 0) { condition = true; }
  9719. if (!condition || !Tools._performance.mark) {
  9720. return;
  9721. }
  9722. Tools._performance.mark(counterName + "-End");
  9723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9724. };
  9725. Tools._StartPerformanceConsole = function (counterName, condition) {
  9726. if (condition === void 0) { condition = true; }
  9727. if (!condition) {
  9728. return;
  9729. }
  9730. Tools._StartUserMark(counterName, condition);
  9731. if (console.time) {
  9732. console.time(counterName);
  9733. }
  9734. };
  9735. Tools._EndPerformanceConsole = function (counterName, condition) {
  9736. if (condition === void 0) { condition = true; }
  9737. if (!condition) {
  9738. return;
  9739. }
  9740. Tools._EndUserMark(counterName, condition);
  9741. if (console.time) {
  9742. console.timeEnd(counterName);
  9743. }
  9744. };
  9745. Object.defineProperty(Tools, "Now", {
  9746. get: function () {
  9747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9748. return window.performance.now();
  9749. }
  9750. return Date.now();
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. /**
  9756. * This method will return the name of the class used to create the instance of the given object.
  9757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9758. * @param object the object to get the class name from
  9759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9760. */
  9761. Tools.GetClassName = function (object, isType) {
  9762. if (isType === void 0) { isType = false; }
  9763. var name = null;
  9764. if (!isType && object.getClassName) {
  9765. name = object.getClassName();
  9766. }
  9767. else {
  9768. if (object instanceof Object) {
  9769. var classObj = isType ? object : Object.getPrototypeOf(object);
  9770. name = classObj.constructor["__bjsclassName__"];
  9771. }
  9772. if (!name) {
  9773. name = typeof object;
  9774. }
  9775. }
  9776. return name;
  9777. };
  9778. Tools.First = function (array, predicate) {
  9779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9780. var el = array_1[_i];
  9781. if (predicate(el)) {
  9782. return el;
  9783. }
  9784. }
  9785. return null;
  9786. };
  9787. /**
  9788. * This method will return the name of the full name of the class, including its owning module (if any).
  9789. * 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).
  9790. * @param object the object to get the class name from
  9791. * @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.
  9792. */
  9793. Tools.getFullClassName = function (object, isType) {
  9794. if (isType === void 0) { isType = false; }
  9795. var className = null;
  9796. var moduleName = null;
  9797. if (!isType && object.getClassName) {
  9798. className = object.getClassName();
  9799. }
  9800. else {
  9801. if (object instanceof Object) {
  9802. var classObj = isType ? object : Object.getPrototypeOf(object);
  9803. className = classObj.constructor["__bjsclassName__"];
  9804. moduleName = classObj.constructor["__bjsmoduleName__"];
  9805. }
  9806. if (!className) {
  9807. className = typeof object;
  9808. }
  9809. }
  9810. if (!className) {
  9811. return null;
  9812. }
  9813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9814. };
  9815. /**
  9816. * 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.
  9817. * @param array
  9818. */
  9819. Tools.arrayOrStringFeeder = function (array) {
  9820. return function (index) {
  9821. if (index >= array.length) {
  9822. return null;
  9823. }
  9824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9825. if (val && val.getHashCode) {
  9826. val = val.getHashCode();
  9827. }
  9828. if (typeof val === "string") {
  9829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9830. }
  9831. return val;
  9832. };
  9833. };
  9834. /**
  9835. * Compute the hashCode of a stream of number
  9836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9838. * @return the hash code computed
  9839. */
  9840. Tools.hashCodeFromStream = function (feeder) {
  9841. // Based from here: http://stackoverflow.com/a/7616484/802124
  9842. var hash = 0;
  9843. var index = 0;
  9844. var chr = feeder(index++);
  9845. while (chr != null) {
  9846. hash = ((hash << 5) - hash) + chr;
  9847. hash |= 0; // Convert to 32bit integer
  9848. chr = feeder(index++);
  9849. }
  9850. return hash;
  9851. };
  9852. /**
  9853. * Returns a promise that resolves after the given amount of time.
  9854. * @param delay Number of milliseconds to delay
  9855. * @returns Promise that resolves after the given amount of time
  9856. */
  9857. Tools.DelayAsync = function (delay) {
  9858. return new Promise(function (resolve) {
  9859. setTimeout(function () {
  9860. resolve();
  9861. }, delay);
  9862. });
  9863. };
  9864. Tools.BaseUrl = "";
  9865. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9866. /**
  9867. * Default behaviour for cors in the application.
  9868. * It can be a string if the expected behavior is identical in the entire app.
  9869. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9870. */
  9871. Tools.CorsBehavior = "anonymous";
  9872. Tools.UseFallbackTexture = true;
  9873. /**
  9874. * Use this object to register external classes like custom textures or material
  9875. * to allow the laoders to instantiate them
  9876. */
  9877. Tools.RegisteredExternalClasses = {};
  9878. // Used in case of a texture loading problem
  9879. 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";
  9880. Tools._tmpFloatArray = new Float32Array(1);
  9881. Tools.PreprocessUrl = function (url) {
  9882. return url;
  9883. };
  9884. // Logs
  9885. Tools._NoneLogLevel = 0;
  9886. Tools._MessageLogLevel = 1;
  9887. Tools._WarningLogLevel = 2;
  9888. Tools._ErrorLogLevel = 4;
  9889. Tools._LogCache = "";
  9890. Tools.errorsCount = 0;
  9891. Tools.Log = Tools._LogEnabled;
  9892. Tools.Warn = Tools._WarnEnabled;
  9893. Tools.Error = Tools._ErrorEnabled;
  9894. // Performances
  9895. Tools._PerformanceNoneLogLevel = 0;
  9896. Tools._PerformanceUserMarkLogLevel = 1;
  9897. Tools._PerformanceConsoleLogLevel = 2;
  9898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9900. return Tools;
  9901. }());
  9902. BABYLON.Tools = Tools;
  9903. /**
  9904. * This class is used to track a performance counter which is number based.
  9905. * The user has access to many properties which give statistics of different nature
  9906. *
  9907. * The implementer can track two kinds of Performance Counter: time and count
  9908. * 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.
  9909. * 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.
  9910. */
  9911. var PerfCounter = /** @class */ (function () {
  9912. function PerfCounter() {
  9913. this._startMonitoringTime = 0;
  9914. this._min = 0;
  9915. this._max = 0;
  9916. this._average = 0;
  9917. this._lastSecAverage = 0;
  9918. this._current = 0;
  9919. this._totalValueCount = 0;
  9920. this._totalAccumulated = 0;
  9921. this._lastSecAccumulated = 0;
  9922. this._lastSecTime = 0;
  9923. this._lastSecValueCount = 0;
  9924. }
  9925. Object.defineProperty(PerfCounter.prototype, "min", {
  9926. /**
  9927. * Returns the smallest value ever
  9928. */
  9929. get: function () {
  9930. return this._min;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(PerfCounter.prototype, "max", {
  9936. /**
  9937. * Returns the biggest value ever
  9938. */
  9939. get: function () {
  9940. return this._max;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(PerfCounter.prototype, "average", {
  9946. /**
  9947. * Returns the average value since the performance counter is running
  9948. */
  9949. get: function () {
  9950. return this._average;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9956. /**
  9957. * Returns the average value of the last second the counter was monitored
  9958. */
  9959. get: function () {
  9960. return this._lastSecAverage;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(PerfCounter.prototype, "current", {
  9966. /**
  9967. * Returns the current value
  9968. */
  9969. get: function () {
  9970. return this._current;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "total", {
  9976. get: function () {
  9977. return this._totalAccumulated;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(PerfCounter.prototype, "count", {
  9983. get: function () {
  9984. return this._totalValueCount;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. /**
  9990. * Call this method to start monitoring a new frame.
  9991. * 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.
  9992. */
  9993. PerfCounter.prototype.fetchNewFrame = function () {
  9994. this._totalValueCount++;
  9995. this._current = 0;
  9996. this._lastSecValueCount++;
  9997. };
  9998. /**
  9999. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10000. * @param newCount the count value to add to the monitored count
  10001. * @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.
  10002. */
  10003. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10004. if (!PerfCounter.Enabled) {
  10005. return;
  10006. }
  10007. this._current += newCount;
  10008. if (fetchResult) {
  10009. this._fetchResult();
  10010. }
  10011. };
  10012. /**
  10013. * Start monitoring this performance counter
  10014. */
  10015. PerfCounter.prototype.beginMonitoring = function () {
  10016. if (!PerfCounter.Enabled) {
  10017. return;
  10018. }
  10019. this._startMonitoringTime = Tools.Now;
  10020. };
  10021. /**
  10022. * Compute the time lapsed since the previous beginMonitoring() call.
  10023. * @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
  10024. */
  10025. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10026. if (newFrame === void 0) { newFrame = true; }
  10027. if (!PerfCounter.Enabled) {
  10028. return;
  10029. }
  10030. if (newFrame) {
  10031. this.fetchNewFrame();
  10032. }
  10033. var currentTime = Tools.Now;
  10034. this._current = currentTime - this._startMonitoringTime;
  10035. if (newFrame) {
  10036. this._fetchResult();
  10037. }
  10038. };
  10039. PerfCounter.prototype._fetchResult = function () {
  10040. this._totalAccumulated += this._current;
  10041. this._lastSecAccumulated += this._current;
  10042. // Min/Max update
  10043. this._min = Math.min(this._min, this._current);
  10044. this._max = Math.max(this._max, this._current);
  10045. this._average = this._totalAccumulated / this._totalValueCount;
  10046. // Reset last sec?
  10047. var now = Tools.Now;
  10048. if ((now - this._lastSecTime) > 1000) {
  10049. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10050. this._lastSecTime = now;
  10051. this._lastSecAccumulated = 0;
  10052. this._lastSecValueCount = 0;
  10053. }
  10054. };
  10055. PerfCounter.Enabled = true;
  10056. return PerfCounter;
  10057. }());
  10058. BABYLON.PerfCounter = PerfCounter;
  10059. /**
  10060. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10061. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10062. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10063. * @param name The name of the class, case should be preserved
  10064. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10065. */
  10066. function className(name, module) {
  10067. return function (target) {
  10068. target["__bjsclassName__"] = name;
  10069. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10070. };
  10071. }
  10072. BABYLON.className = className;
  10073. /**
  10074. * An implementation of a loop for asynchronous functions.
  10075. */
  10076. var AsyncLoop = /** @class */ (function () {
  10077. /**
  10078. * Constroctor.
  10079. * @param iterations the number of iterations.
  10080. * @param _fn the function to run each iteration
  10081. * @param _successCallback the callback that will be called upon succesful execution
  10082. * @param offset starting offset.
  10083. */
  10084. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10085. if (offset === void 0) { offset = 0; }
  10086. this.iterations = iterations;
  10087. this._fn = _fn;
  10088. this._successCallback = _successCallback;
  10089. this.index = offset - 1;
  10090. this._done = false;
  10091. }
  10092. /**
  10093. * Execute the next iteration. Must be called after the last iteration was finished.
  10094. */
  10095. AsyncLoop.prototype.executeNext = function () {
  10096. if (!this._done) {
  10097. if (this.index + 1 < this.iterations) {
  10098. ++this.index;
  10099. this._fn(this);
  10100. }
  10101. else {
  10102. this.breakLoop();
  10103. }
  10104. }
  10105. };
  10106. /**
  10107. * Break the loop and run the success callback.
  10108. */
  10109. AsyncLoop.prototype.breakLoop = function () {
  10110. this._done = true;
  10111. this._successCallback();
  10112. };
  10113. /**
  10114. * Helper function
  10115. */
  10116. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10117. if (offset === void 0) { offset = 0; }
  10118. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10119. loop.executeNext();
  10120. return loop;
  10121. };
  10122. /**
  10123. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10124. * @param iterations total number of iterations
  10125. * @param syncedIterations number of synchronous iterations in each async iteration.
  10126. * @param fn the function to call each iteration.
  10127. * @param callback a success call back that will be called when iterating stops.
  10128. * @param breakFunction a break condition (optional)
  10129. * @param timeout timeout settings for the setTimeout function. default - 0.
  10130. * @constructor
  10131. */
  10132. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10133. if (timeout === void 0) { timeout = 0; }
  10134. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10135. if (breakFunction && breakFunction())
  10136. loop.breakLoop();
  10137. else {
  10138. setTimeout(function () {
  10139. for (var i = 0; i < syncedIterations; ++i) {
  10140. var iteration = (loop.index * syncedIterations) + i;
  10141. if (iteration >= iterations)
  10142. break;
  10143. fn(iteration);
  10144. if (breakFunction && breakFunction()) {
  10145. loop.breakLoop();
  10146. break;
  10147. }
  10148. }
  10149. loop.executeNext();
  10150. }, timeout);
  10151. }
  10152. }, callback);
  10153. };
  10154. return AsyncLoop;
  10155. }());
  10156. BABYLON.AsyncLoop = AsyncLoop;
  10157. })(BABYLON || (BABYLON = {}));
  10158. //# sourceMappingURL=babylon.tools.js.map
  10159. var BABYLON;
  10160. (function (BABYLON) {
  10161. var PromiseStates;
  10162. (function (PromiseStates) {
  10163. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10164. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10165. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10166. })(PromiseStates || (PromiseStates = {}));
  10167. var FulFillmentAgregator = /** @class */ (function () {
  10168. function FulFillmentAgregator() {
  10169. this.count = 0;
  10170. this.target = 0;
  10171. this.results = [];
  10172. }
  10173. return FulFillmentAgregator;
  10174. }());
  10175. var InternalPromise = /** @class */ (function () {
  10176. function InternalPromise(resolver) {
  10177. var _this = this;
  10178. this._state = PromiseStates.Pending;
  10179. this._children = new Array();
  10180. this._rejectWasConsumed = false;
  10181. if (!resolver) {
  10182. return;
  10183. }
  10184. try {
  10185. resolver(function (value) {
  10186. _this._resolve(value);
  10187. }, function (reason) {
  10188. _this._reject(reason);
  10189. });
  10190. }
  10191. catch (e) {
  10192. this._reject(e);
  10193. }
  10194. }
  10195. Object.defineProperty(InternalPromise.prototype, "_result", {
  10196. get: function () {
  10197. return this._resultValue;
  10198. },
  10199. set: function (value) {
  10200. this._resultValue = value;
  10201. if (this._parent && this._parent._result === undefined) {
  10202. this._parent._result = value;
  10203. }
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. InternalPromise.prototype.catch = function (onRejected) {
  10209. return this.then(undefined, onRejected);
  10210. };
  10211. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10212. var _this = this;
  10213. var newPromise = new InternalPromise();
  10214. newPromise._onFulfilled = onFulfilled;
  10215. newPromise._onRejected = onRejected;
  10216. // Composition
  10217. this._children.push(newPromise);
  10218. newPromise._parent = this;
  10219. if (this._state !== PromiseStates.Pending) {
  10220. BABYLON.Tools.SetImmediate(function () {
  10221. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10222. var returnedValue = newPromise._resolve(_this._result);
  10223. if (returnedValue !== undefined && returnedValue !== null) {
  10224. if (returnedValue._state !== undefined) {
  10225. var returnedPromise = returnedValue;
  10226. newPromise._children.push(returnedPromise);
  10227. returnedPromise._parent = newPromise;
  10228. newPromise = returnedPromise;
  10229. }
  10230. else {
  10231. newPromise._result = returnedValue;
  10232. }
  10233. }
  10234. }
  10235. else {
  10236. newPromise._reject(_this._reason);
  10237. }
  10238. });
  10239. }
  10240. return newPromise;
  10241. };
  10242. InternalPromise.prototype._moveChildren = function (children) {
  10243. var _this = this;
  10244. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10245. this._children.forEach(function (child) {
  10246. child._parent = _this;
  10247. });
  10248. if (this._state === PromiseStates.Fulfilled) {
  10249. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10250. var child = _b[_i];
  10251. child._resolve(this._result);
  10252. }
  10253. }
  10254. else if (this._state === PromiseStates.Rejected) {
  10255. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10256. var child = _d[_c];
  10257. child._reject(this._reason);
  10258. }
  10259. }
  10260. var _a;
  10261. };
  10262. InternalPromise.prototype._resolve = function (value) {
  10263. try {
  10264. this._state = PromiseStates.Fulfilled;
  10265. var returnedValue = null;
  10266. if (this._onFulfilled) {
  10267. returnedValue = this._onFulfilled(value);
  10268. }
  10269. if (returnedValue !== undefined && returnedValue !== null) {
  10270. if (returnedValue._state !== undefined) {
  10271. // Transmit children
  10272. var returnedPromise = returnedValue;
  10273. returnedPromise._parent = this;
  10274. returnedPromise._moveChildren(this._children);
  10275. value = returnedPromise._result;
  10276. }
  10277. else {
  10278. value = returnedValue;
  10279. }
  10280. }
  10281. this._result = value;
  10282. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10283. var child = _a[_i];
  10284. child._resolve(value);
  10285. }
  10286. this._children.length = 0;
  10287. delete this._onFulfilled;
  10288. delete this._onRejected;
  10289. }
  10290. catch (e) {
  10291. this._reject(e, true);
  10292. }
  10293. };
  10294. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10295. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10296. this._state = PromiseStates.Rejected;
  10297. this._reason = reason;
  10298. if (this._onRejected && !onLocalThrow) {
  10299. try {
  10300. this._onRejected(reason);
  10301. this._rejectWasConsumed = true;
  10302. }
  10303. catch (e) {
  10304. reason = e;
  10305. }
  10306. }
  10307. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10308. var child = _a[_i];
  10309. if (this._rejectWasConsumed) {
  10310. child._resolve(null);
  10311. }
  10312. else {
  10313. child._reject(reason);
  10314. }
  10315. }
  10316. this._children.length = 0;
  10317. delete this._onFulfilled;
  10318. delete this._onRejected;
  10319. };
  10320. InternalPromise.resolve = function (value) {
  10321. var newPromise = new InternalPromise();
  10322. newPromise._resolve(value);
  10323. return newPromise;
  10324. };
  10325. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10326. promise.then(function (value) {
  10327. agregator.results[index] = value;
  10328. agregator.count++;
  10329. if (agregator.count === agregator.target) {
  10330. agregator.rootPromise._resolve(agregator.results);
  10331. }
  10332. return null;
  10333. }, function (reason) {
  10334. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10335. agregator.rootPromise._reject(reason);
  10336. }
  10337. });
  10338. };
  10339. InternalPromise.all = function (promises) {
  10340. var newPromise = new InternalPromise();
  10341. var agregator = new FulFillmentAgregator();
  10342. agregator.target = promises.length;
  10343. agregator.rootPromise = newPromise;
  10344. if (promises.length) {
  10345. for (var index = 0; index < promises.length; index++) {
  10346. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10347. }
  10348. }
  10349. else {
  10350. newPromise._resolve([]);
  10351. }
  10352. return newPromise;
  10353. };
  10354. InternalPromise.race = function (promises) {
  10355. var newPromise = new InternalPromise();
  10356. if (promises.length) {
  10357. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10358. var promise = promises_1[_i];
  10359. promise.then(function (value) {
  10360. if (newPromise) {
  10361. newPromise._resolve(value);
  10362. newPromise = null;
  10363. }
  10364. return null;
  10365. }, function (reason) {
  10366. if (newPromise) {
  10367. newPromise._reject(reason);
  10368. newPromise = null;
  10369. }
  10370. });
  10371. }
  10372. }
  10373. return newPromise;
  10374. };
  10375. return InternalPromise;
  10376. }());
  10377. /**
  10378. * Helper class that provides a small promise polyfill
  10379. */
  10380. var PromisePolyfill = /** @class */ (function () {
  10381. function PromisePolyfill() {
  10382. }
  10383. /**
  10384. * Static function used to check if the polyfill is required
  10385. * If this is the case then the function will inject the polyfill to window.Promise
  10386. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10387. */
  10388. PromisePolyfill.Apply = function (force) {
  10389. if (force === void 0) { force = false; }
  10390. if (force || typeof Promise === 'undefined') {
  10391. var root = window;
  10392. root.Promise = InternalPromise;
  10393. }
  10394. };
  10395. return PromisePolyfill;
  10396. }());
  10397. BABYLON.PromisePolyfill = PromisePolyfill;
  10398. })(BABYLON || (BABYLON = {}));
  10399. //# sourceMappingURL=babylon.promise.js.map
  10400. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10401. var BABYLON;
  10402. (function (BABYLON) {
  10403. /**
  10404. * Helper class to push actions to a pool of workers.
  10405. */
  10406. var WorkerPool = /** @class */ (function () {
  10407. /**
  10408. * Constructor
  10409. * @param workers Array of workers to use for actions
  10410. */
  10411. function WorkerPool(workers) {
  10412. this._pendingActions = new Array();
  10413. this._workerInfos = workers.map(function (worker) { return ({
  10414. worker: worker,
  10415. active: false
  10416. }); });
  10417. }
  10418. /**
  10419. * Terminates all workers and clears any pending actions.
  10420. */
  10421. WorkerPool.prototype.dispose = function () {
  10422. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10423. var workerInfo = _a[_i];
  10424. workerInfo.worker.terminate();
  10425. }
  10426. delete this._workerInfos;
  10427. delete this._pendingActions;
  10428. };
  10429. /**
  10430. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10431. * pended until a worker has completed its action.
  10432. * @param action The action to perform. Call onComplete when the action is complete.
  10433. */
  10434. WorkerPool.prototype.push = function (action) {
  10435. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10436. var workerInfo = _a[_i];
  10437. if (!workerInfo.active) {
  10438. this._execute(workerInfo, action);
  10439. return;
  10440. }
  10441. }
  10442. this._pendingActions.push(action);
  10443. };
  10444. WorkerPool.prototype._execute = function (workerInfo, action) {
  10445. var _this = this;
  10446. workerInfo.active = true;
  10447. action(workerInfo.worker, function () {
  10448. workerInfo.active = false;
  10449. var nextAction = _this._pendingActions.shift();
  10450. if (nextAction) {
  10451. _this._execute(workerInfo, nextAction);
  10452. }
  10453. });
  10454. };
  10455. return WorkerPool;
  10456. }());
  10457. BABYLON.WorkerPool = WorkerPool;
  10458. })(BABYLON || (BABYLON = {}));
  10459. //# sourceMappingURL=babylon.workerPool.js.map
  10460. var BABYLON;
  10461. (function (BABYLON) {
  10462. /**
  10463. * @hidden
  10464. **/
  10465. var _AlphaState = /** @class */ (function () {
  10466. /**
  10467. * Initializes the state.
  10468. */
  10469. function _AlphaState() {
  10470. this._isAlphaBlendDirty = false;
  10471. this._isBlendFunctionParametersDirty = false;
  10472. this._isBlendEquationParametersDirty = false;
  10473. this._isBlendConstantsDirty = false;
  10474. this._alphaBlend = false;
  10475. this._blendFunctionParameters = new Array(4);
  10476. this._blendEquationParameters = new Array(2);
  10477. this._blendConstants = new Array(4);
  10478. this.reset();
  10479. }
  10480. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10481. get: function () {
  10482. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10483. },
  10484. enumerable: true,
  10485. configurable: true
  10486. });
  10487. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10488. get: function () {
  10489. return this._alphaBlend;
  10490. },
  10491. set: function (value) {
  10492. if (this._alphaBlend === value) {
  10493. return;
  10494. }
  10495. this._alphaBlend = value;
  10496. this._isAlphaBlendDirty = true;
  10497. },
  10498. enumerable: true,
  10499. configurable: true
  10500. });
  10501. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10502. if (this._blendConstants[0] === r &&
  10503. this._blendConstants[1] === g &&
  10504. this._blendConstants[2] === b &&
  10505. this._blendConstants[3] === a) {
  10506. return;
  10507. }
  10508. this._blendConstants[0] = r;
  10509. this._blendConstants[1] = g;
  10510. this._blendConstants[2] = b;
  10511. this._blendConstants[3] = a;
  10512. this._isBlendConstantsDirty = true;
  10513. };
  10514. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10515. if (this._blendFunctionParameters[0] === value0 &&
  10516. this._blendFunctionParameters[1] === value1 &&
  10517. this._blendFunctionParameters[2] === value2 &&
  10518. this._blendFunctionParameters[3] === value3) {
  10519. return;
  10520. }
  10521. this._blendFunctionParameters[0] = value0;
  10522. this._blendFunctionParameters[1] = value1;
  10523. this._blendFunctionParameters[2] = value2;
  10524. this._blendFunctionParameters[3] = value3;
  10525. this._isBlendFunctionParametersDirty = true;
  10526. };
  10527. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10528. if (this._blendEquationParameters[0] === rgb &&
  10529. this._blendEquationParameters[1] === alpha) {
  10530. return;
  10531. }
  10532. this._blendEquationParameters[0] = rgb;
  10533. this._blendEquationParameters[1] = alpha;
  10534. this._isBlendEquationParametersDirty = true;
  10535. };
  10536. _AlphaState.prototype.reset = function () {
  10537. this._alphaBlend = false;
  10538. this._blendFunctionParameters[0] = null;
  10539. this._blendFunctionParameters[1] = null;
  10540. this._blendFunctionParameters[2] = null;
  10541. this._blendFunctionParameters[3] = null;
  10542. this._blendEquationParameters[0] = null;
  10543. this._blendEquationParameters[1] = null;
  10544. this._blendConstants[0] = null;
  10545. this._blendConstants[1] = null;
  10546. this._blendConstants[2] = null;
  10547. this._blendConstants[3] = null;
  10548. this._isAlphaBlendDirty = true;
  10549. this._isBlendFunctionParametersDirty = false;
  10550. this._isBlendEquationParametersDirty = false;
  10551. this._isBlendConstantsDirty = false;
  10552. };
  10553. _AlphaState.prototype.apply = function (gl) {
  10554. if (!this.isDirty) {
  10555. return;
  10556. }
  10557. // Alpha blend
  10558. if (this._isAlphaBlendDirty) {
  10559. if (this._alphaBlend) {
  10560. gl.enable(gl.BLEND);
  10561. }
  10562. else {
  10563. gl.disable(gl.BLEND);
  10564. }
  10565. this._isAlphaBlendDirty = false;
  10566. }
  10567. // Alpha function
  10568. if (this._isBlendFunctionParametersDirty) {
  10569. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10570. this._isBlendFunctionParametersDirty = false;
  10571. }
  10572. // Alpha equation
  10573. if (this._isBlendEquationParametersDirty) {
  10574. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10575. this._isBlendEquationParametersDirty = false;
  10576. }
  10577. // Constants
  10578. if (this._isBlendConstantsDirty) {
  10579. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10580. this._isBlendConstantsDirty = false;
  10581. }
  10582. };
  10583. return _AlphaState;
  10584. }());
  10585. BABYLON._AlphaState = _AlphaState;
  10586. })(BABYLON || (BABYLON = {}));
  10587. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10588. var BABYLON;
  10589. (function (BABYLON) {
  10590. /**
  10591. * @hidden
  10592. **/
  10593. var _DepthCullingState = /** @class */ (function () {
  10594. /**
  10595. * Initializes the state.
  10596. */
  10597. function _DepthCullingState() {
  10598. this._isDepthTestDirty = false;
  10599. this._isDepthMaskDirty = false;
  10600. this._isDepthFuncDirty = false;
  10601. this._isCullFaceDirty = false;
  10602. this._isCullDirty = false;
  10603. this._isZOffsetDirty = false;
  10604. this._isFrontFaceDirty = false;
  10605. this.reset();
  10606. }
  10607. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10608. get: function () {
  10609. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10615. get: function () {
  10616. return this._zOffset;
  10617. },
  10618. set: function (value) {
  10619. if (this._zOffset === value) {
  10620. return;
  10621. }
  10622. this._zOffset = value;
  10623. this._isZOffsetDirty = true;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10629. get: function () {
  10630. return this._cullFace;
  10631. },
  10632. set: function (value) {
  10633. if (this._cullFace === value) {
  10634. return;
  10635. }
  10636. this._cullFace = value;
  10637. this._isCullFaceDirty = true;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10643. get: function () {
  10644. return this._cull;
  10645. },
  10646. set: function (value) {
  10647. if (this._cull === value) {
  10648. return;
  10649. }
  10650. this._cull = value;
  10651. this._isCullDirty = true;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10657. get: function () {
  10658. return this._depthFunc;
  10659. },
  10660. set: function (value) {
  10661. if (this._depthFunc === value) {
  10662. return;
  10663. }
  10664. this._depthFunc = value;
  10665. this._isDepthFuncDirty = true;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10671. get: function () {
  10672. return this._depthMask;
  10673. },
  10674. set: function (value) {
  10675. if (this._depthMask === value) {
  10676. return;
  10677. }
  10678. this._depthMask = value;
  10679. this._isDepthMaskDirty = true;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10685. get: function () {
  10686. return this._depthTest;
  10687. },
  10688. set: function (value) {
  10689. if (this._depthTest === value) {
  10690. return;
  10691. }
  10692. this._depthTest = value;
  10693. this._isDepthTestDirty = true;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10699. get: function () {
  10700. return this._frontFace;
  10701. },
  10702. set: function (value) {
  10703. if (this._frontFace === value) {
  10704. return;
  10705. }
  10706. this._frontFace = value;
  10707. this._isFrontFaceDirty = true;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. _DepthCullingState.prototype.reset = function () {
  10713. this._depthMask = true;
  10714. this._depthTest = true;
  10715. this._depthFunc = null;
  10716. this._cullFace = null;
  10717. this._cull = null;
  10718. this._zOffset = 0;
  10719. this._frontFace = null;
  10720. this._isDepthTestDirty = true;
  10721. this._isDepthMaskDirty = true;
  10722. this._isDepthFuncDirty = false;
  10723. this._isCullFaceDirty = false;
  10724. this._isCullDirty = false;
  10725. this._isZOffsetDirty = false;
  10726. this._isFrontFaceDirty = false;
  10727. };
  10728. _DepthCullingState.prototype.apply = function (gl) {
  10729. if (!this.isDirty) {
  10730. return;
  10731. }
  10732. // Cull
  10733. if (this._isCullDirty) {
  10734. if (this.cull) {
  10735. gl.enable(gl.CULL_FACE);
  10736. }
  10737. else {
  10738. gl.disable(gl.CULL_FACE);
  10739. }
  10740. this._isCullDirty = false;
  10741. }
  10742. // Cull face
  10743. if (this._isCullFaceDirty) {
  10744. gl.cullFace(this.cullFace);
  10745. this._isCullFaceDirty = false;
  10746. }
  10747. // Depth mask
  10748. if (this._isDepthMaskDirty) {
  10749. gl.depthMask(this.depthMask);
  10750. this._isDepthMaskDirty = false;
  10751. }
  10752. // Depth test
  10753. if (this._isDepthTestDirty) {
  10754. if (this.depthTest) {
  10755. gl.enable(gl.DEPTH_TEST);
  10756. }
  10757. else {
  10758. gl.disable(gl.DEPTH_TEST);
  10759. }
  10760. this._isDepthTestDirty = false;
  10761. }
  10762. // Depth func
  10763. if (this._isDepthFuncDirty) {
  10764. gl.depthFunc(this.depthFunc);
  10765. this._isDepthFuncDirty = false;
  10766. }
  10767. // zOffset
  10768. if (this._isZOffsetDirty) {
  10769. if (this.zOffset) {
  10770. gl.enable(gl.POLYGON_OFFSET_FILL);
  10771. gl.polygonOffset(this.zOffset, 0);
  10772. }
  10773. else {
  10774. gl.disable(gl.POLYGON_OFFSET_FILL);
  10775. }
  10776. this._isZOffsetDirty = false;
  10777. }
  10778. // Front face
  10779. if (this._isFrontFaceDirty) {
  10780. gl.frontFace(this.frontFace);
  10781. this._isFrontFaceDirty = false;
  10782. }
  10783. };
  10784. return _DepthCullingState;
  10785. }());
  10786. BABYLON._DepthCullingState = _DepthCullingState;
  10787. })(BABYLON || (BABYLON = {}));
  10788. //# sourceMappingURL=babylon.depthCullingState.js.map
  10789. var BABYLON;
  10790. (function (BABYLON) {
  10791. /**
  10792. * @hidden
  10793. **/
  10794. var _StencilState = /** @class */ (function () {
  10795. function _StencilState() {
  10796. this._isStencilTestDirty = false;
  10797. this._isStencilMaskDirty = false;
  10798. this._isStencilFuncDirty = false;
  10799. this._isStencilOpDirty = false;
  10800. this.reset();
  10801. }
  10802. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10803. get: function () {
  10804. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10810. get: function () {
  10811. return this._stencilFunc;
  10812. },
  10813. set: function (value) {
  10814. if (this._stencilFunc === value) {
  10815. return;
  10816. }
  10817. this._stencilFunc = value;
  10818. this._isStencilFuncDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10824. get: function () {
  10825. return this._stencilFuncRef;
  10826. },
  10827. set: function (value) {
  10828. if (this._stencilFuncRef === value) {
  10829. return;
  10830. }
  10831. this._stencilFuncRef = value;
  10832. this._isStencilFuncDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10838. get: function () {
  10839. return this._stencilFuncMask;
  10840. },
  10841. set: function (value) {
  10842. if (this._stencilFuncMask === value) {
  10843. return;
  10844. }
  10845. this._stencilFuncMask = value;
  10846. this._isStencilFuncDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10852. get: function () {
  10853. return this._stencilOpStencilFail;
  10854. },
  10855. set: function (value) {
  10856. if (this._stencilOpStencilFail === value) {
  10857. return;
  10858. }
  10859. this._stencilOpStencilFail = value;
  10860. this._isStencilOpDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10866. get: function () {
  10867. return this._stencilOpDepthFail;
  10868. },
  10869. set: function (value) {
  10870. if (this._stencilOpDepthFail === value) {
  10871. return;
  10872. }
  10873. this._stencilOpDepthFail = value;
  10874. this._isStencilOpDirty = true;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10880. get: function () {
  10881. return this._stencilOpStencilDepthPass;
  10882. },
  10883. set: function (value) {
  10884. if (this._stencilOpStencilDepthPass === value) {
  10885. return;
  10886. }
  10887. this._stencilOpStencilDepthPass = value;
  10888. this._isStencilOpDirty = true;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10894. get: function () {
  10895. return this._stencilMask;
  10896. },
  10897. set: function (value) {
  10898. if (this._stencilMask === value) {
  10899. return;
  10900. }
  10901. this._stencilMask = value;
  10902. this._isStencilMaskDirty = true;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10908. get: function () {
  10909. return this._stencilTest;
  10910. },
  10911. set: function (value) {
  10912. if (this._stencilTest === value) {
  10913. return;
  10914. }
  10915. this._stencilTest = value;
  10916. this._isStencilTestDirty = true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. _StencilState.prototype.reset = function () {
  10922. this._stencilTest = false;
  10923. this._stencilMask = 0xFF;
  10924. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10925. this._stencilFuncRef = 1;
  10926. this._stencilFuncMask = 0xFF;
  10927. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10928. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10929. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10930. this._isStencilTestDirty = true;
  10931. this._isStencilMaskDirty = true;
  10932. this._isStencilFuncDirty = true;
  10933. this._isStencilOpDirty = true;
  10934. };
  10935. _StencilState.prototype.apply = function (gl) {
  10936. if (!this.isDirty) {
  10937. return;
  10938. }
  10939. // Stencil test
  10940. if (this._isStencilTestDirty) {
  10941. if (this.stencilTest) {
  10942. gl.enable(gl.STENCIL_TEST);
  10943. }
  10944. else {
  10945. gl.disable(gl.STENCIL_TEST);
  10946. }
  10947. this._isStencilTestDirty = false;
  10948. }
  10949. // Stencil mask
  10950. if (this._isStencilMaskDirty) {
  10951. gl.stencilMask(this.stencilMask);
  10952. this._isStencilMaskDirty = false;
  10953. }
  10954. // Stencil func
  10955. if (this._isStencilFuncDirty) {
  10956. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10957. this._isStencilFuncDirty = false;
  10958. }
  10959. // Stencil op
  10960. if (this._isStencilOpDirty) {
  10961. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10962. this._isStencilOpDirty = false;
  10963. }
  10964. };
  10965. return _StencilState;
  10966. }());
  10967. BABYLON._StencilState = _StencilState;
  10968. })(BABYLON || (BABYLON = {}));
  10969. //# sourceMappingURL=babylon.stencilState.js.map
  10970. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10971. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10972. s = arguments[i];
  10973. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10974. t[p] = s[p];
  10975. }
  10976. return t;
  10977. };
  10978. var BABYLON;
  10979. (function (BABYLON) {
  10980. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10981. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10982. };
  10983. var compileRawShader = function (gl, source, type) {
  10984. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10985. gl.shaderSource(shader, source);
  10986. gl.compileShader(shader);
  10987. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10988. var log = gl.getShaderInfoLog(shader);
  10989. if (log) {
  10990. throw new Error(log);
  10991. }
  10992. }
  10993. if (!shader) {
  10994. throw new Error("Something went wrong while compile the shader.");
  10995. }
  10996. return shader;
  10997. };
  10998. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10999. var magFilter = gl.NEAREST;
  11000. var minFilter = gl.NEAREST;
  11001. switch (samplingMode) {
  11002. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11003. magFilter = gl.LINEAR;
  11004. if (generateMipMaps) {
  11005. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11006. }
  11007. else {
  11008. minFilter = gl.LINEAR;
  11009. }
  11010. break;
  11011. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11012. magFilter = gl.LINEAR;
  11013. if (generateMipMaps) {
  11014. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11015. }
  11016. else {
  11017. minFilter = gl.LINEAR;
  11018. }
  11019. break;
  11020. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11021. magFilter = gl.NEAREST;
  11022. if (generateMipMaps) {
  11023. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11024. }
  11025. else {
  11026. minFilter = gl.NEAREST;
  11027. }
  11028. break;
  11029. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11030. magFilter = gl.NEAREST;
  11031. if (generateMipMaps) {
  11032. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11033. }
  11034. else {
  11035. minFilter = gl.NEAREST;
  11036. }
  11037. break;
  11038. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11039. magFilter = gl.NEAREST;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11042. }
  11043. else {
  11044. minFilter = gl.LINEAR;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11048. magFilter = gl.NEAREST;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.LINEAR;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.NEAREST_LINEAR:
  11057. magFilter = gl.NEAREST;
  11058. minFilter = gl.LINEAR;
  11059. break;
  11060. case BABYLON.Texture.NEAREST_NEAREST:
  11061. magFilter = gl.NEAREST;
  11062. minFilter = gl.NEAREST;
  11063. break;
  11064. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11065. magFilter = gl.LINEAR;
  11066. if (generateMipMaps) {
  11067. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11068. }
  11069. else {
  11070. minFilter = gl.NEAREST;
  11071. }
  11072. break;
  11073. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11074. magFilter = gl.LINEAR;
  11075. if (generateMipMaps) {
  11076. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11077. }
  11078. else {
  11079. minFilter = gl.NEAREST;
  11080. }
  11081. break;
  11082. case BABYLON.Texture.LINEAR_LINEAR:
  11083. magFilter = gl.LINEAR;
  11084. minFilter = gl.LINEAR;
  11085. break;
  11086. case BABYLON.Texture.LINEAR_NEAREST:
  11087. magFilter = gl.LINEAR;
  11088. minFilter = gl.NEAREST;
  11089. break;
  11090. }
  11091. return {
  11092. min: minFilter,
  11093. mag: magFilter
  11094. };
  11095. };
  11096. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11097. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11098. var img;
  11099. var onload = function () {
  11100. loadedImages[index] = img;
  11101. loadedImages._internalCount++;
  11102. if (scene) {
  11103. scene._removePendingData(img);
  11104. }
  11105. if (loadedImages._internalCount === 6) {
  11106. onfinish(loadedImages);
  11107. }
  11108. };
  11109. var onerror = function (message, exception) {
  11110. if (scene) {
  11111. scene._removePendingData(img);
  11112. }
  11113. if (onErrorCallBack) {
  11114. onErrorCallBack(message, exception);
  11115. }
  11116. };
  11117. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11118. if (scene) {
  11119. scene._addPendingData(img);
  11120. }
  11121. };
  11122. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11123. if (onError === void 0) { onError = null; }
  11124. var loadedImages = [];
  11125. loadedImages._internalCount = 0;
  11126. for (var index = 0; index < 6; index++) {
  11127. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11128. }
  11129. };
  11130. var BufferPointer = /** @class */ (function () {
  11131. function BufferPointer() {
  11132. }
  11133. return BufferPointer;
  11134. }());
  11135. /**
  11136. * Interface for attribute information associated with buffer instanciation
  11137. */
  11138. var InstancingAttributeInfo = /** @class */ (function () {
  11139. function InstancingAttributeInfo() {
  11140. }
  11141. return InstancingAttributeInfo;
  11142. }());
  11143. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11144. /**
  11145. * Define options used to create a render target texture
  11146. */
  11147. var RenderTargetCreationOptions = /** @class */ (function () {
  11148. function RenderTargetCreationOptions() {
  11149. }
  11150. return RenderTargetCreationOptions;
  11151. }());
  11152. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11153. /**
  11154. * Define options used to create a depth texture
  11155. */
  11156. var DepthTextureCreationOptions = /** @class */ (function () {
  11157. function DepthTextureCreationOptions() {
  11158. }
  11159. return DepthTextureCreationOptions;
  11160. }());
  11161. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11162. /**
  11163. * Class used to describe the capabilities of the engine relatively to the current browser
  11164. */
  11165. var EngineCapabilities = /** @class */ (function () {
  11166. function EngineCapabilities() {
  11167. }
  11168. return EngineCapabilities;
  11169. }());
  11170. BABYLON.EngineCapabilities = EngineCapabilities;
  11171. /**
  11172. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11173. */
  11174. var Engine = /** @class */ (function () {
  11175. /**
  11176. * Creates a new engine
  11177. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11178. * @param antialias defines enable antialiasing (default: false)
  11179. * @param options defines further options to be sent to the getContext() function
  11180. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11181. */
  11182. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11183. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11184. var _this = this;
  11185. // Public members
  11186. /**
  11187. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11188. */
  11189. this.forcePOTTextures = false;
  11190. /**
  11191. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11192. */
  11193. this.isFullscreen = false;
  11194. /**
  11195. * Gets a boolean indicating if the pointer is currently locked
  11196. */
  11197. this.isPointerLock = false;
  11198. /**
  11199. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11200. */
  11201. this.cullBackFaces = true;
  11202. /**
  11203. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11204. */
  11205. this.renderEvenInBackground = true;
  11206. /**
  11207. * Gets or sets a boolean indicating that cache can be kept between frames
  11208. */
  11209. this.preventCacheWipeBetweenFrames = false;
  11210. /**
  11211. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11212. **/
  11213. this.enableOfflineSupport = false;
  11214. /**
  11215. * 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)
  11216. **/
  11217. this.disableManifestCheck = false;
  11218. /**
  11219. * Gets the list of created scenes
  11220. */
  11221. this.scenes = new Array();
  11222. /**
  11223. * Gets the list of created postprocesses
  11224. */
  11225. this.postProcesses = new Array();
  11226. // Observables
  11227. /**
  11228. * Observable event triggered each time the rendering canvas is resized
  11229. */
  11230. this.onResizeObservable = new BABYLON.Observable();
  11231. /**
  11232. * Observable event triggered each time the canvas loses focus
  11233. */
  11234. this.onCanvasBlurObservable = new BABYLON.Observable();
  11235. /**
  11236. * Observable event triggered each time the canvas gains focus
  11237. */
  11238. this.onCanvasFocusObservable = new BABYLON.Observable();
  11239. /**
  11240. * Observable event triggered each time the canvas receives pointerout event
  11241. */
  11242. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11243. /**
  11244. * Observable event triggered before each texture is initialized
  11245. */
  11246. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11247. //WebVR
  11248. this._vrDisplay = undefined;
  11249. this._vrSupported = false;
  11250. this._vrExclusivePointerMode = false;
  11251. // Uniform buffers list
  11252. /**
  11253. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11254. */
  11255. this.disableUniformBuffers = false;
  11256. /** @hidden */
  11257. this._uniformBuffers = new Array();
  11258. // Observables
  11259. /**
  11260. * Observable raised when the engine begins a new frame
  11261. */
  11262. this.onBeginFrameObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable raised when the engine ends the current frame
  11265. */
  11266. this.onEndFrameObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable raised when the engine is about to compile a shader
  11269. */
  11270. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable raised when the engine has jsut compiled a shader
  11273. */
  11274. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11275. this._windowIsBackground = false;
  11276. this._webGLVersion = 1.0;
  11277. /** @hidden */
  11278. this._badOS = false;
  11279. /** @hidden */
  11280. this._badDesktopOS = false;
  11281. /**
  11282. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11283. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11284. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11285. */
  11286. this.disableTextureBindingOptimization = false;
  11287. /**
  11288. * Observable signaled when VR display mode changes
  11289. */
  11290. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable signaled when VR request present is complete
  11293. */
  11294. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11295. /**
  11296. * Observable signaled when VR request present starts
  11297. */
  11298. this.onVRRequestPresentStart = new BABYLON.Observable();
  11299. this._colorWrite = true;
  11300. /** @hidden */
  11301. this._drawCalls = new BABYLON.PerfCounter();
  11302. /** @hidden */
  11303. this._textureCollisions = new BABYLON.PerfCounter();
  11304. this._renderingQueueLaunched = false;
  11305. this._activeRenderLoops = new Array();
  11306. // Deterministic lockstepMaxSteps
  11307. this._deterministicLockstep = false;
  11308. this._lockstepMaxSteps = 4;
  11309. // Lost context
  11310. /**
  11311. * Observable signaled when a context lost event is raised
  11312. */
  11313. this.onContextLostObservable = new BABYLON.Observable();
  11314. /**
  11315. * Observable signaled when a context restored event is raised
  11316. */
  11317. this.onContextRestoredObservable = new BABYLON.Observable();
  11318. this._contextWasLost = false;
  11319. this._doNotHandleContextLost = false;
  11320. // FPS
  11321. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11322. this._fps = 60;
  11323. this._deltaTime = 0;
  11324. /**
  11325. * Turn this value on if you want to pause FPS computation when in background
  11326. */
  11327. this.disablePerformanceMonitorInBackground = false;
  11328. // States
  11329. /** @hidden */
  11330. this._depthCullingState = new BABYLON._DepthCullingState();
  11331. /** @hidden */
  11332. this._stencilState = new BABYLON._StencilState();
  11333. /** @hidden */
  11334. this._alphaState = new BABYLON._AlphaState();
  11335. /** @hidden */
  11336. this._alphaMode = Engine.ALPHA_DISABLE;
  11337. // Cache
  11338. this._internalTexturesCache = new Array();
  11339. /** @hidden */
  11340. this._activeChannel = 0;
  11341. this._currentTextureChannel = -1;
  11342. /** @hidden */
  11343. this._boundTexturesCache = {};
  11344. this._compiledEffects = {};
  11345. this._vertexAttribArraysEnabled = [];
  11346. this._uintIndicesCurrentlySet = false;
  11347. this._currentBoundBuffer = new Array();
  11348. this._currentBufferPointers = new Array();
  11349. this._currentInstanceLocations = new Array();
  11350. this._currentInstanceBuffers = new Array();
  11351. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11352. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11353. this._vaoRecordInProgress = false;
  11354. this._mustWipeVertexAttributes = false;
  11355. this._nextFreeTextureSlots = new Array();
  11356. this._maxSimultaneousTextures = 0;
  11357. this._activeRequests = new Array();
  11358. // Hardware supported Compressed Textures
  11359. this._texturesSupported = new Array();
  11360. /**
  11361. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11362. */
  11363. this.premultipliedAlpha = true;
  11364. this._onVRFullScreenTriggered = function () {
  11365. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11366. //get the old size before we change
  11367. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11368. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11369. //get the width and height, change the render size
  11370. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11371. _this.setHardwareScalingLevel(1);
  11372. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11373. }
  11374. else {
  11375. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11376. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11377. }
  11378. };
  11379. this._boundUniforms = {};
  11380. // Register promises
  11381. BABYLON.PromisePolyfill.Apply();
  11382. var canvas = null;
  11383. Engine.Instances.push(this);
  11384. if (!canvasOrContext) {
  11385. return;
  11386. }
  11387. options = options || {};
  11388. if (canvasOrContext.getContext) {
  11389. canvas = canvasOrContext;
  11390. this._renderingCanvas = canvas;
  11391. if (antialias != null) {
  11392. options.antialias = antialias;
  11393. }
  11394. if (options.deterministicLockstep === undefined) {
  11395. options.deterministicLockstep = false;
  11396. }
  11397. if (options.lockstepMaxSteps === undefined) {
  11398. options.lockstepMaxSteps = 4;
  11399. }
  11400. if (options.preserveDrawingBuffer === undefined) {
  11401. options.preserveDrawingBuffer = false;
  11402. }
  11403. if (options.audioEngine === undefined) {
  11404. options.audioEngine = true;
  11405. }
  11406. if (options.stencil === undefined) {
  11407. options.stencil = true;
  11408. }
  11409. if (options.premultipliedAlpha === false) {
  11410. this.premultipliedAlpha = false;
  11411. }
  11412. this._deterministicLockstep = options.deterministicLockstep;
  11413. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11414. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11415. // Exceptions
  11416. if (navigator && navigator.userAgent) {
  11417. var ua = navigator.userAgent;
  11418. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11419. var exception = _a[_i];
  11420. var key = exception.key;
  11421. var targets = exception.targets;
  11422. if (ua.indexOf(key) > -1) {
  11423. if (exception.capture && exception.captureConstraint) {
  11424. var capture = exception.capture;
  11425. var constraint = exception.captureConstraint;
  11426. var regex = new RegExp(capture);
  11427. var matches = regex.exec(ua);
  11428. if (matches && matches.length > 0) {
  11429. var capturedValue = parseInt(matches[matches.length - 1]);
  11430. if (capturedValue >= constraint) {
  11431. continue;
  11432. }
  11433. }
  11434. }
  11435. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11436. var target = targets_1[_b];
  11437. switch (target) {
  11438. case "uniformBuffer":
  11439. this.disableUniformBuffers = true;
  11440. break;
  11441. case "textureBindingOptimization":
  11442. this.disableTextureBindingOptimization = true;
  11443. break;
  11444. }
  11445. }
  11446. }
  11447. }
  11448. }
  11449. // GL
  11450. if (!options.disableWebGL2Support) {
  11451. try {
  11452. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11453. if (this._gl) {
  11454. this._webGLVersion = 2.0;
  11455. }
  11456. }
  11457. catch (e) {
  11458. // Do nothing
  11459. }
  11460. }
  11461. if (!this._gl) {
  11462. if (!canvas) {
  11463. throw new Error("The provided canvas is null or undefined.");
  11464. }
  11465. try {
  11466. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11467. }
  11468. catch (e) {
  11469. throw new Error("WebGL not supported");
  11470. }
  11471. }
  11472. if (!this._gl) {
  11473. throw new Error("WebGL not supported");
  11474. }
  11475. this._onCanvasFocus = function () {
  11476. _this.onCanvasFocusObservable.notifyObservers(_this);
  11477. };
  11478. this._onCanvasBlur = function () {
  11479. _this.onCanvasBlurObservable.notifyObservers(_this);
  11480. };
  11481. canvas.addEventListener("focus", this._onCanvasFocus);
  11482. canvas.addEventListener("blur", this._onCanvasBlur);
  11483. this._onBlur = function () {
  11484. if (_this.disablePerformanceMonitorInBackground) {
  11485. _this._performanceMonitor.disable();
  11486. }
  11487. _this._windowIsBackground = true;
  11488. };
  11489. this._onFocus = function () {
  11490. if (_this.disablePerformanceMonitorInBackground) {
  11491. _this._performanceMonitor.enable();
  11492. }
  11493. _this._windowIsBackground = false;
  11494. };
  11495. this._onCanvasPointerOut = function (ev) {
  11496. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11497. };
  11498. window.addEventListener("blur", this._onBlur);
  11499. window.addEventListener("focus", this._onFocus);
  11500. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11501. // Context lost
  11502. if (!this._doNotHandleContextLost) {
  11503. this._onContextLost = function (evt) {
  11504. evt.preventDefault();
  11505. _this._contextWasLost = true;
  11506. BABYLON.Tools.Warn("WebGL context lost.");
  11507. _this.onContextLostObservable.notifyObservers(_this);
  11508. };
  11509. this._onContextRestored = function (evt) {
  11510. // Adding a timeout to avoid race condition at browser level
  11511. setTimeout(function () {
  11512. // Rebuild gl context
  11513. _this._initGLContext();
  11514. // Rebuild effects
  11515. _this._rebuildEffects();
  11516. // Rebuild textures
  11517. _this._rebuildInternalTextures();
  11518. // Rebuild buffers
  11519. _this._rebuildBuffers();
  11520. // Cache
  11521. _this.wipeCaches(true);
  11522. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11523. _this.onContextRestoredObservable.notifyObservers(_this);
  11524. _this._contextWasLost = false;
  11525. }, 0);
  11526. };
  11527. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11528. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11529. }
  11530. }
  11531. else {
  11532. this._gl = canvasOrContext;
  11533. this._renderingCanvas = this._gl.canvas;
  11534. if (this._gl.renderbufferStorageMultisample) {
  11535. this._webGLVersion = 2.0;
  11536. }
  11537. options.stencil = this._gl.getContextAttributes().stencil;
  11538. }
  11539. // Viewport
  11540. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11541. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11542. this.resize();
  11543. this._isStencilEnable = options.stencil ? true : false;
  11544. this._initGLContext();
  11545. if (canvas) {
  11546. // Fullscreen
  11547. this._onFullscreenChange = function () {
  11548. if (document.fullscreen !== undefined) {
  11549. _this.isFullscreen = document.fullscreen;
  11550. }
  11551. else if (document.mozFullScreen !== undefined) {
  11552. _this.isFullscreen = document.mozFullScreen;
  11553. }
  11554. else if (document.webkitIsFullScreen !== undefined) {
  11555. _this.isFullscreen = document.webkitIsFullScreen;
  11556. }
  11557. else if (document.msIsFullScreen !== undefined) {
  11558. _this.isFullscreen = document.msIsFullScreen;
  11559. }
  11560. // Pointer lock
  11561. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11562. canvas.requestPointerLock = canvas.requestPointerLock ||
  11563. canvas.msRequestPointerLock ||
  11564. canvas.mozRequestPointerLock ||
  11565. canvas.webkitRequestPointerLock;
  11566. if (canvas.requestPointerLock) {
  11567. canvas.requestPointerLock();
  11568. }
  11569. }
  11570. };
  11571. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11572. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11573. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11574. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11575. // Pointer lock
  11576. this._onPointerLockChange = function () {
  11577. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11578. document.webkitPointerLockElement === canvas ||
  11579. document.msPointerLockElement === canvas ||
  11580. document.pointerLockElement === canvas);
  11581. };
  11582. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11583. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11584. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11585. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11586. this._onVRDisplayPointerRestricted = function () {
  11587. if (canvas) {
  11588. canvas.requestPointerLock();
  11589. }
  11590. };
  11591. this._onVRDisplayPointerUnrestricted = function () {
  11592. document.exitPointerLock();
  11593. };
  11594. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11595. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11596. }
  11597. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11598. Engine.audioEngine = new BABYLON.AudioEngine();
  11599. }
  11600. // Prepare buffer pointers
  11601. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11602. this._currentBufferPointers[i] = new BufferPointer();
  11603. }
  11604. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11605. // Load WebVR Devices
  11606. if (options.autoEnableWebVR) {
  11607. this.initWebVR();
  11608. }
  11609. // Detect if we are running on a faulty buggy OS.
  11610. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11611. // Detect if we are running on a faulty buggy desktop OS.
  11612. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11613. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11614. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11615. }
  11616. Object.defineProperty(Engine, "LastCreatedEngine", {
  11617. /**
  11618. * Gets the latest created engine
  11619. */
  11620. get: function () {
  11621. if (Engine.Instances.length === 0) {
  11622. return null;
  11623. }
  11624. return Engine.Instances[Engine.Instances.length - 1];
  11625. },
  11626. enumerable: true,
  11627. configurable: true
  11628. });
  11629. Object.defineProperty(Engine, "LastCreatedScene", {
  11630. /**
  11631. * Gets the latest created scene
  11632. */
  11633. get: function () {
  11634. var lastCreatedEngine = Engine.LastCreatedEngine;
  11635. if (!lastCreatedEngine) {
  11636. return null;
  11637. }
  11638. if (lastCreatedEngine.scenes.length === 0) {
  11639. return null;
  11640. }
  11641. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. /**
  11647. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11648. * @param flag defines which part of the materials must be marked as dirty
  11649. * @param predicate defines a predicate used to filter which materials should be affected
  11650. */
  11651. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11652. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11653. var engine = Engine.Instances[engineIndex];
  11654. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11655. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11656. }
  11657. }
  11658. };
  11659. Object.defineProperty(Engine, "NEVER", {
  11660. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11661. get: function () {
  11662. return Engine._NEVER;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "ALWAYS", {
  11668. /** 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 */
  11669. get: function () {
  11670. return Engine._ALWAYS;
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Engine, "LESS", {
  11676. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11677. get: function () {
  11678. return Engine._LESS;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Engine, "EQUAL", {
  11684. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11685. get: function () {
  11686. return Engine._EQUAL;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Engine, "LEQUAL", {
  11692. /** 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 */
  11693. get: function () {
  11694. return Engine._LEQUAL;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "GREATER", {
  11700. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11701. get: function () {
  11702. return Engine._GREATER;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Engine, "GEQUAL", {
  11708. /** 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 */
  11709. get: function () {
  11710. return Engine._GEQUAL;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "NOTEQUAL", {
  11716. /** 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 */
  11717. get: function () {
  11718. return Engine._NOTEQUAL;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "KEEP", {
  11724. /** Passed to stencilOperation to specify that stencil value must be kept */
  11725. get: function () {
  11726. return Engine._KEEP;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "REPLACE", {
  11732. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11733. get: function () {
  11734. return Engine._REPLACE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "INCR", {
  11740. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11741. get: function () {
  11742. return Engine._INCR;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "DECR", {
  11748. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11749. get: function () {
  11750. return Engine._DECR;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "INVERT", {
  11756. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11757. get: function () {
  11758. return Engine._INVERT;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "INCR_WRAP", {
  11764. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11765. get: function () {
  11766. return Engine._INCR_WRAP;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "DECR_WRAP", {
  11772. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11773. get: function () {
  11774. return Engine._DECR_WRAP;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11780. // Alpha
  11781. /** Defines that alpha blending is disabled */
  11782. get: function () {
  11783. return Engine._ALPHA_DISABLE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11789. /** Defines that alpha blending to SRC + DEST */
  11790. get: function () {
  11791. return Engine._ALPHA_ONEONE;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "ALPHA_ADD", {
  11797. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11798. get: function () {
  11799. return Engine._ALPHA_ADD;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11805. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11806. get: function () {
  11807. return Engine._ALPHA_COMBINE;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11813. /** Defines that alpha blending to DEST - SRC * DEST */
  11814. get: function () {
  11815. return Engine._ALPHA_SUBTRACT;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11821. /** Defines that alpha blending to SRC * DEST */
  11822. get: function () {
  11823. return Engine._ALPHA_MULTIPLY;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11829. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11830. get: function () {
  11831. return Engine._ALPHA_MAXIMIZED;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11837. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11838. get: function () {
  11839. return Engine._ALPHA_PREMULTIPLIED;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11845. /**
  11846. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11847. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11848. */
  11849. get: function () {
  11850. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11856. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11857. get: function () {
  11858. return Engine._ALPHA_INTERPOLATE;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11864. /**
  11865. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11866. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11867. */
  11868. get: function () {
  11869. return Engine._ALPHA_SCREENMODE;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11875. // Delays
  11876. /** Defines that the ressource is not delayed*/
  11877. get: function () {
  11878. return Engine._DELAYLOADSTATE_NONE;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11884. /** Defines that the ressource was successfully delay loaded */
  11885. get: function () {
  11886. return Engine._DELAYLOADSTATE_LOADED;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11892. /** Defines that the ressource is currently delay loading */
  11893. get: function () {
  11894. return Engine._DELAYLOADSTATE_LOADING;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11900. /** Defines that the ressource is delayed and has not started loading */
  11901. get: function () {
  11902. return Engine._DELAYLOADSTATE_NOTLOADED;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11908. /** ALPHA */
  11909. get: function () {
  11910. return Engine._TEXTUREFORMAT_ALPHA;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11916. /** LUMINANCE */
  11917. get: function () {
  11918. return Engine._TEXTUREFORMAT_LUMINANCE;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11924. /**
  11925. * R
  11926. */
  11927. get: function () {
  11928. return Engine._TEXTUREFORMAT_R;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11934. /**
  11935. * RG
  11936. */
  11937. get: function () {
  11938. return Engine._TEXTUREFORMAT_RG;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11944. /** LUMINANCE_ALPHA */
  11945. get: function () {
  11946. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11952. /** RGB */
  11953. get: function () {
  11954. return Engine._TEXTUREFORMAT_RGB;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11960. /** RGBA */
  11961. get: function () {
  11962. return Engine._TEXTUREFORMAT_RGBA;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11968. /** UNSIGNED_INT */
  11969. get: function () {
  11970. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11976. /** FLOAT */
  11977. get: function () {
  11978. return Engine._TEXTURETYPE_FLOAT;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11984. /** HALF_FLOAT */
  11985. get: function () {
  11986. return Engine._TEXTURETYPE_HALF_FLOAT;
  11987. },
  11988. enumerable: true,
  11989. configurable: true
  11990. });
  11991. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11992. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11993. get: function () {
  11994. return Engine._SCALEMODE_FLOOR;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12000. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12001. get: function () {
  12002. return Engine._SCALEMODE_NEAREST;
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12008. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12009. get: function () {
  12010. return Engine._SCALEMODE_CEILING;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine, "Version", {
  12016. /**
  12017. * Returns the current version of the framework
  12018. */
  12019. get: function () {
  12020. return "3.3.0-alpha.6";
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12026. /**
  12027. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12028. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12029. */
  12030. get: function () {
  12031. return this._vrExclusivePointerMode;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12037. /**
  12038. * Gets a boolean indicating that the engine supports uniform buffers
  12039. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12040. */
  12041. get: function () {
  12042. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12048. /**
  12049. * Gets a boolean indicating that only power of 2 textures are supported
  12050. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12051. */
  12052. get: function () {
  12053. return this._webGLVersion < 2 || this.forcePOTTextures;
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12059. /**
  12060. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12061. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12062. */
  12063. get: function () {
  12064. return this._doNotHandleContextLost;
  12065. },
  12066. set: function (value) {
  12067. this._doNotHandleContextLost = value;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12073. /**
  12074. * Gets the performance monitor attached to this engine
  12075. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12076. */
  12077. get: function () {
  12078. return this._performanceMonitor;
  12079. },
  12080. enumerable: true,
  12081. configurable: true
  12082. });
  12083. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12084. /**
  12085. * Gets the list of texture formats supported
  12086. */
  12087. get: function () {
  12088. return this._texturesSupported;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12094. /**
  12095. * Gets the list of texture formats in use
  12096. */
  12097. get: function () {
  12098. return this._textureFormatInUse;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "currentViewport", {
  12104. /**
  12105. * Gets the current viewport
  12106. */
  12107. get: function () {
  12108. return this._cachedViewport;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12114. /**
  12115. * Gets the default empty texture
  12116. */
  12117. get: function () {
  12118. if (!this._emptyTexture) {
  12119. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12120. }
  12121. return this._emptyTexture;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12127. /**
  12128. * Gets the default empty 3D texture
  12129. */
  12130. get: function () {
  12131. if (!this._emptyTexture3D) {
  12132. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12133. }
  12134. return this._emptyTexture3D;
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12140. /**
  12141. * Gets the default empty cube texture
  12142. */
  12143. get: function () {
  12144. if (!this._emptyCubeTexture) {
  12145. var faceData = new Uint8Array(4);
  12146. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12147. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12148. }
  12149. return this._emptyCubeTexture;
  12150. },
  12151. enumerable: true,
  12152. configurable: true
  12153. });
  12154. Engine.prototype._rebuildInternalTextures = function () {
  12155. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12156. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12157. var internalTexture = currentState_1[_i];
  12158. internalTexture._rebuild();
  12159. }
  12160. };
  12161. Engine.prototype._rebuildEffects = function () {
  12162. for (var key in this._compiledEffects) {
  12163. var effect = this._compiledEffects[key];
  12164. effect._prepareEffect();
  12165. }
  12166. BABYLON.Effect.ResetCache();
  12167. };
  12168. Engine.prototype._rebuildBuffers = function () {
  12169. // Index / Vertex
  12170. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12171. var scene = _a[_i];
  12172. scene.resetCachedMaterial();
  12173. scene._rebuildGeometries();
  12174. scene._rebuildTextures();
  12175. }
  12176. // Uniforms
  12177. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12178. var uniformBuffer = _c[_b];
  12179. uniformBuffer._rebuild();
  12180. }
  12181. };
  12182. Engine.prototype._initGLContext = function () {
  12183. // Caps
  12184. this._caps = new EngineCapabilities();
  12185. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12186. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12187. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12188. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12189. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12190. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12191. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12192. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12193. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12194. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12195. // Infos
  12196. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12197. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12198. if (rendererInfo != null) {
  12199. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12200. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12201. }
  12202. if (!this._glVendor) {
  12203. this._glVendor = "Unknown vendor";
  12204. }
  12205. if (!this._glRenderer) {
  12206. this._glRenderer = "Unknown renderer";
  12207. }
  12208. // Constants
  12209. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12210. if (this._gl.RGBA16F !== 0x881A) {
  12211. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12212. }
  12213. if (this._gl.RGBA32F !== 0x8814) {
  12214. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12215. }
  12216. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12217. this._gl.DEPTH24_STENCIL8 = 35056;
  12218. }
  12219. // Extensions
  12220. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12221. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12222. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12223. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12224. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12225. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12226. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12227. 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');
  12228. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12229. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12230. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12231. this._caps.highPrecisionShaderSupported = true;
  12232. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12233. if (this._caps.timerQuery) {
  12234. if (this._webGLVersion === 1) {
  12235. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12236. }
  12237. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12238. }
  12239. // Checks if some of the format renders first to allow the use of webgl inspector.
  12240. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12241. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12242. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12243. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12244. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12245. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12246. if (this._webGLVersion > 1) {
  12247. this._gl.HALF_FLOAT_OES = 0x140B;
  12248. }
  12249. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12250. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12251. // Draw buffers
  12252. if (this._webGLVersion > 1) {
  12253. this._caps.drawBuffersExtension = true;
  12254. }
  12255. else {
  12256. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12257. if (drawBuffersExtension !== null) {
  12258. this._caps.drawBuffersExtension = true;
  12259. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12260. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12261. for (var i = 0; i < 16; i++) {
  12262. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12263. }
  12264. }
  12265. else {
  12266. this._caps.drawBuffersExtension = false;
  12267. }
  12268. }
  12269. // Depth Texture
  12270. if (this._webGLVersion > 1) {
  12271. this._caps.depthTextureExtension = true;
  12272. }
  12273. else {
  12274. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12275. if (depthTextureExtension != null) {
  12276. this._caps.depthTextureExtension = true;
  12277. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12278. }
  12279. }
  12280. // Vertex array object
  12281. if (this._webGLVersion > 1) {
  12282. this._caps.vertexArrayObject = true;
  12283. }
  12284. else {
  12285. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12286. if (vertexArrayObjectExtension != null) {
  12287. this._caps.vertexArrayObject = true;
  12288. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12289. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12290. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12291. }
  12292. else {
  12293. this._caps.vertexArrayObject = false;
  12294. }
  12295. }
  12296. // Instances count
  12297. if (this._webGLVersion > 1) {
  12298. this._caps.instancedArrays = true;
  12299. }
  12300. else {
  12301. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12302. if (instanceExtension != null) {
  12303. this._caps.instancedArrays = true;
  12304. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12305. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12306. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12307. }
  12308. else {
  12309. this._caps.instancedArrays = false;
  12310. }
  12311. }
  12312. // Intelligently add supported compressed formats in order to check for.
  12313. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12314. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12315. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12316. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12317. if (this._caps.astc)
  12318. this.texturesSupported.push('-astc.ktx');
  12319. if (this._caps.s3tc)
  12320. this.texturesSupported.push('-dxt.ktx');
  12321. if (this._caps.pvrtc)
  12322. this.texturesSupported.push('-pvrtc.ktx');
  12323. if (this._caps.etc2)
  12324. this.texturesSupported.push('-etc2.ktx');
  12325. if (this._caps.etc1)
  12326. this.texturesSupported.push('-etc1.ktx');
  12327. if (this._gl.getShaderPrecisionFormat) {
  12328. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12329. if (highp) {
  12330. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12331. }
  12332. }
  12333. // Depth buffer
  12334. this.setDepthBuffer(true);
  12335. this.setDepthFunctionToLessOrEqual();
  12336. this.setDepthWrite(true);
  12337. // Texture maps
  12338. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12339. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12340. this._nextFreeTextureSlots.push(slot);
  12341. }
  12342. };
  12343. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12344. /**
  12345. * Gets version of the current webGL context
  12346. */
  12347. get: function () {
  12348. return this._webGLVersion;
  12349. },
  12350. enumerable: true,
  12351. configurable: true
  12352. });
  12353. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12354. /**
  12355. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12356. */
  12357. get: function () {
  12358. return this._isStencilEnable;
  12359. },
  12360. enumerable: true,
  12361. configurable: true
  12362. });
  12363. Engine.prototype._prepareWorkingCanvas = function () {
  12364. if (this._workingCanvas) {
  12365. return;
  12366. }
  12367. this._workingCanvas = document.createElement("canvas");
  12368. var context = this._workingCanvas.getContext("2d");
  12369. if (context) {
  12370. this._workingContext = context;
  12371. }
  12372. };
  12373. /**
  12374. * Reset the texture cache to empty state
  12375. */
  12376. Engine.prototype.resetTextureCache = function () {
  12377. for (var key in this._boundTexturesCache) {
  12378. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12379. continue;
  12380. }
  12381. var boundTexture = this._boundTexturesCache[key];
  12382. if (boundTexture) {
  12383. this._removeDesignatedSlot(boundTexture);
  12384. }
  12385. this._boundTexturesCache[key] = null;
  12386. }
  12387. if (!this.disableTextureBindingOptimization) {
  12388. this._nextFreeTextureSlots = [];
  12389. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12390. this._nextFreeTextureSlots.push(slot);
  12391. }
  12392. }
  12393. this._currentTextureChannel = -1;
  12394. };
  12395. /**
  12396. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12397. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12398. * @returns true if engine is in deterministic lock step mode
  12399. */
  12400. Engine.prototype.isDeterministicLockStep = function () {
  12401. return this._deterministicLockstep;
  12402. };
  12403. /**
  12404. * Gets the max steps when engine is running in deterministic lock step
  12405. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12406. * @returns the max steps
  12407. */
  12408. Engine.prototype.getLockstepMaxSteps = function () {
  12409. return this._lockstepMaxSteps;
  12410. };
  12411. /**
  12412. * Gets an object containing information about the current webGL context
  12413. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12414. */
  12415. Engine.prototype.getGlInfo = function () {
  12416. return {
  12417. vendor: this._glVendor,
  12418. renderer: this._glRenderer,
  12419. version: this._glVersion
  12420. };
  12421. };
  12422. /**
  12423. * Gets current aspect ratio
  12424. * @param camera defines the camera to use to get the aspect ratio
  12425. * @param useScreen defines if screen size must be used (or the current render target if any)
  12426. * @returns a number defining the aspect ratio
  12427. */
  12428. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12429. if (useScreen === void 0) { useScreen = false; }
  12430. var viewport = camera.viewport;
  12431. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12432. };
  12433. /**
  12434. * Gets current screen aspect ratio
  12435. * @returns a number defining the aspect ratio
  12436. */
  12437. Engine.prototype.getScreenAspectRatio = function () {
  12438. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12439. };
  12440. /**
  12441. * Gets the current render width
  12442. * @param useScreen defines if screen size must be used (or the current render target if any)
  12443. * @returns a number defining the current render width
  12444. */
  12445. Engine.prototype.getRenderWidth = function (useScreen) {
  12446. if (useScreen === void 0) { useScreen = false; }
  12447. if (!useScreen && this._currentRenderTarget) {
  12448. return this._currentRenderTarget.width;
  12449. }
  12450. return this._gl.drawingBufferWidth;
  12451. };
  12452. /**
  12453. * Gets the current render height
  12454. * @param useScreen defines if screen size must be used (or the current render target if any)
  12455. * @returns a number defining the current render height
  12456. */
  12457. Engine.prototype.getRenderHeight = function (useScreen) {
  12458. if (useScreen === void 0) { useScreen = false; }
  12459. if (!useScreen && this._currentRenderTarget) {
  12460. return this._currentRenderTarget.height;
  12461. }
  12462. return this._gl.drawingBufferHeight;
  12463. };
  12464. /**
  12465. * Gets the HTML canvas attached with the current webGL context
  12466. * @returns a HTML canvas
  12467. */
  12468. Engine.prototype.getRenderingCanvas = function () {
  12469. return this._renderingCanvas;
  12470. };
  12471. /**
  12472. * Gets the client rect of the HTML canvas attached with the current webGL context
  12473. * @returns a client rectanglee
  12474. */
  12475. Engine.prototype.getRenderingCanvasClientRect = function () {
  12476. if (!this._renderingCanvas) {
  12477. return null;
  12478. }
  12479. return this._renderingCanvas.getBoundingClientRect();
  12480. };
  12481. /**
  12482. * Defines the hardware scaling level.
  12483. * By default the hardware scaling level is computed from the window device ratio.
  12484. * 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.
  12485. * @param level defines the level to use
  12486. */
  12487. Engine.prototype.setHardwareScalingLevel = function (level) {
  12488. this._hardwareScalingLevel = level;
  12489. this.resize();
  12490. };
  12491. /**
  12492. * Gets the current hardware scaling level.
  12493. * By default the hardware scaling level is computed from the window device ratio.
  12494. * 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.
  12495. * @returns a number indicating the current hardware scaling level
  12496. */
  12497. Engine.prototype.getHardwareScalingLevel = function () {
  12498. return this._hardwareScalingLevel;
  12499. };
  12500. /**
  12501. * Gets the list of loaded textures
  12502. * @returns an array containing all loaded textures
  12503. */
  12504. Engine.prototype.getLoadedTexturesCache = function () {
  12505. return this._internalTexturesCache;
  12506. };
  12507. /**
  12508. * Gets the object containing all engine capabilities
  12509. * @returns the EngineCapabilities object
  12510. */
  12511. Engine.prototype.getCaps = function () {
  12512. return this._caps;
  12513. };
  12514. Object.defineProperty(Engine.prototype, "drawCalls", {
  12515. /** @hidden */
  12516. get: function () {
  12517. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12518. return 0;
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12524. /** @hidden */
  12525. get: function () {
  12526. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12527. return null;
  12528. },
  12529. enumerable: true,
  12530. configurable: true
  12531. });
  12532. /**
  12533. * Gets the current depth function
  12534. * @returns a number defining the depth function
  12535. */
  12536. Engine.prototype.getDepthFunction = function () {
  12537. return this._depthCullingState.depthFunc;
  12538. };
  12539. /**
  12540. * Sets the current depth function
  12541. * @param depthFunc defines the function to use
  12542. */
  12543. Engine.prototype.setDepthFunction = function (depthFunc) {
  12544. this._depthCullingState.depthFunc = depthFunc;
  12545. };
  12546. /**
  12547. * Sets the current depth function to GREATER
  12548. */
  12549. Engine.prototype.setDepthFunctionToGreater = function () {
  12550. this._depthCullingState.depthFunc = this._gl.GREATER;
  12551. };
  12552. /**
  12553. * Sets the current depth function to GEQUAL
  12554. */
  12555. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12556. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12557. };
  12558. /**
  12559. * Sets the current depth function to LESS
  12560. */
  12561. Engine.prototype.setDepthFunctionToLess = function () {
  12562. this._depthCullingState.depthFunc = this._gl.LESS;
  12563. };
  12564. /**
  12565. * Sets the current depth function to LEQUAL
  12566. */
  12567. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12568. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12569. };
  12570. /**
  12571. * Gets a boolean indicating if stencil buffer is enabled
  12572. * @returns the current stencil buffer state
  12573. */
  12574. Engine.prototype.getStencilBuffer = function () {
  12575. return this._stencilState.stencilTest;
  12576. };
  12577. /**
  12578. * Enable or disable the stencil buffer
  12579. * @param enable defines if the stencil buffer must be enabled or disabled
  12580. */
  12581. Engine.prototype.setStencilBuffer = function (enable) {
  12582. this._stencilState.stencilTest = enable;
  12583. };
  12584. /**
  12585. * Gets the current stencil mask
  12586. * @returns a number defining the new stencil mask to use
  12587. */
  12588. Engine.prototype.getStencilMask = function () {
  12589. return this._stencilState.stencilMask;
  12590. };
  12591. /**
  12592. * Sets the current stencil mask
  12593. * @param mask defines the new stencil mask to use
  12594. */
  12595. Engine.prototype.setStencilMask = function (mask) {
  12596. this._stencilState.stencilMask = mask;
  12597. };
  12598. /**
  12599. * Gets the current stencil function
  12600. * @returns a number defining the stencil function to use
  12601. */
  12602. Engine.prototype.getStencilFunction = function () {
  12603. return this._stencilState.stencilFunc;
  12604. };
  12605. /**
  12606. * Gets the current stencil reference value
  12607. * @returns a number defining the stencil reference value to use
  12608. */
  12609. Engine.prototype.getStencilFunctionReference = function () {
  12610. return this._stencilState.stencilFuncRef;
  12611. };
  12612. /**
  12613. * Gets the current stencil mask
  12614. * @returns a number defining the stencil mask to use
  12615. */
  12616. Engine.prototype.getStencilFunctionMask = function () {
  12617. return this._stencilState.stencilFuncMask;
  12618. };
  12619. /**
  12620. * Sets the current stencil function
  12621. * @param stencilFunc defines the new stencil function to use
  12622. */
  12623. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12624. this._stencilState.stencilFunc = stencilFunc;
  12625. };
  12626. /**
  12627. * Sets the current stencil reference
  12628. * @param reference defines the new stencil reference to use
  12629. */
  12630. Engine.prototype.setStencilFunctionReference = function (reference) {
  12631. this._stencilState.stencilFuncRef = reference;
  12632. };
  12633. /**
  12634. * Sets the current stencil mask
  12635. * @param mask defines the new stencil mask to use
  12636. */
  12637. Engine.prototype.setStencilFunctionMask = function (mask) {
  12638. this._stencilState.stencilFuncMask = mask;
  12639. };
  12640. /**
  12641. * Gets the current stencil operation when stencil fails
  12642. * @returns a number defining stencil operation to use when stencil fails
  12643. */
  12644. Engine.prototype.getStencilOperationFail = function () {
  12645. return this._stencilState.stencilOpStencilFail;
  12646. };
  12647. /**
  12648. * Gets the current stencil operation when depth fails
  12649. * @returns a number defining stencil operation to use when depth fails
  12650. */
  12651. Engine.prototype.getStencilOperationDepthFail = function () {
  12652. return this._stencilState.stencilOpDepthFail;
  12653. };
  12654. /**
  12655. * Gets the current stencil operation when stencil passes
  12656. * @returns a number defining stencil operation to use when stencil passes
  12657. */
  12658. Engine.prototype.getStencilOperationPass = function () {
  12659. return this._stencilState.stencilOpStencilDepthPass;
  12660. };
  12661. /**
  12662. * Sets the stencil operation to use when stencil fails
  12663. * @param operation defines the stencil operation to use when stencil fails
  12664. */
  12665. Engine.prototype.setStencilOperationFail = function (operation) {
  12666. this._stencilState.stencilOpStencilFail = operation;
  12667. };
  12668. /**
  12669. * Sets the stencil operation to use when depth fails
  12670. * @param operation defines the stencil operation to use when depth fails
  12671. */
  12672. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12673. this._stencilState.stencilOpDepthFail = operation;
  12674. };
  12675. /**
  12676. * Sets the stencil operation to use when stencil passes
  12677. * @param operation defines the stencil operation to use when stencil passes
  12678. */
  12679. Engine.prototype.setStencilOperationPass = function (operation) {
  12680. this._stencilState.stencilOpStencilDepthPass = operation;
  12681. };
  12682. /**
  12683. * Sets a boolean indicating if the dithering state is enabled or disabled
  12684. * @param value defines the dithering state
  12685. */
  12686. Engine.prototype.setDitheringState = function (value) {
  12687. if (value) {
  12688. this._gl.enable(this._gl.DITHER);
  12689. }
  12690. else {
  12691. this._gl.disable(this._gl.DITHER);
  12692. }
  12693. };
  12694. /**
  12695. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12696. * @param value defines the rasterizer state
  12697. */
  12698. Engine.prototype.setRasterizerState = function (value) {
  12699. if (value) {
  12700. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12701. }
  12702. else {
  12703. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12704. }
  12705. };
  12706. /**
  12707. * stop executing a render loop function and remove it from the execution array
  12708. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12709. */
  12710. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12711. if (!renderFunction) {
  12712. this._activeRenderLoops = [];
  12713. return;
  12714. }
  12715. var index = this._activeRenderLoops.indexOf(renderFunction);
  12716. if (index >= 0) {
  12717. this._activeRenderLoops.splice(index, 1);
  12718. }
  12719. };
  12720. /** @hidden */
  12721. Engine.prototype._renderLoop = function () {
  12722. if (!this._contextWasLost) {
  12723. var shouldRender = true;
  12724. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12725. shouldRender = false;
  12726. }
  12727. if (shouldRender) {
  12728. // Start new frame
  12729. this.beginFrame();
  12730. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12731. var renderFunction = this._activeRenderLoops[index];
  12732. renderFunction();
  12733. }
  12734. // Present
  12735. this.endFrame();
  12736. }
  12737. }
  12738. if (this._activeRenderLoops.length > 0) {
  12739. // Register new frame
  12740. var requester = null;
  12741. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12742. requester = this._vrDisplay;
  12743. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12744. }
  12745. else {
  12746. this._renderingQueueLaunched = false;
  12747. }
  12748. };
  12749. /**
  12750. * Register and execute a render loop. The engine can have more than one render function
  12751. * @param renderFunction defines the function to continuously execute
  12752. */
  12753. Engine.prototype.runRenderLoop = function (renderFunction) {
  12754. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12755. return;
  12756. }
  12757. this._activeRenderLoops.push(renderFunction);
  12758. if (!this._renderingQueueLaunched) {
  12759. this._renderingQueueLaunched = true;
  12760. this._bindedRenderFunction = this._renderLoop.bind(this);
  12761. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12762. }
  12763. };
  12764. /**
  12765. * Toggle full screen mode
  12766. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12767. * @param options defines an option object to be sent to the requestFullscreen function
  12768. */
  12769. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12770. if (this.isFullscreen) {
  12771. BABYLON.Tools.ExitFullscreen();
  12772. }
  12773. else {
  12774. this._pointerLockRequested = requestPointerLock;
  12775. if (this._renderingCanvas) {
  12776. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12777. }
  12778. }
  12779. };
  12780. /**
  12781. * Clear the current render buffer or the current render target (if any is set up)
  12782. * @param color defines the color to use
  12783. * @param backBuffer defines if the back buffer must be cleared
  12784. * @param depth defines if the depth buffer must be cleared
  12785. * @param stencil defines if the stencil buffer must be cleared
  12786. */
  12787. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12788. if (stencil === void 0) { stencil = false; }
  12789. this.applyStates();
  12790. var mode = 0;
  12791. if (backBuffer && color) {
  12792. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12793. mode |= this._gl.COLOR_BUFFER_BIT;
  12794. }
  12795. if (depth) {
  12796. this._gl.clearDepth(1.0);
  12797. mode |= this._gl.DEPTH_BUFFER_BIT;
  12798. }
  12799. if (stencil) {
  12800. this._gl.clearStencil(0);
  12801. mode |= this._gl.STENCIL_BUFFER_BIT;
  12802. }
  12803. this._gl.clear(mode);
  12804. };
  12805. /**
  12806. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12807. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12808. * @param y defines the y-coordinate of the corner of the clear rectangle
  12809. * @param width defines the width of the clear rectangle
  12810. * @param height defines the height of the clear rectangle
  12811. * @param clearColor defines the clear color
  12812. */
  12813. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12814. var gl = this._gl;
  12815. // Save state
  12816. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12817. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12818. // Change state
  12819. gl.enable(gl.SCISSOR_TEST);
  12820. gl.scissor(x, y, width, height);
  12821. // Clear
  12822. this.clear(clearColor, true, true, true);
  12823. // Restore state
  12824. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12825. if (curScissor === true) {
  12826. gl.enable(gl.SCISSOR_TEST);
  12827. }
  12828. else {
  12829. gl.disable(gl.SCISSOR_TEST);
  12830. }
  12831. };
  12832. /**
  12833. * Set the WebGL's viewport
  12834. * @param viewport defines the viewport element to be used
  12835. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12836. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12837. */
  12838. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12839. var width = requiredWidth || this.getRenderWidth();
  12840. var height = requiredHeight || this.getRenderHeight();
  12841. var x = viewport.x || 0;
  12842. var y = viewport.y || 0;
  12843. this._cachedViewport = viewport;
  12844. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12845. };
  12846. /**
  12847. * Directly set the WebGL Viewport
  12848. * @param x defines the x coordinate of the viewport (in screen space)
  12849. * @param y defines the y coordinate of the viewport (in screen space)
  12850. * @param width defines the width of the viewport (in screen space)
  12851. * @param height defines the height of the viewport (in screen space)
  12852. * @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
  12853. */
  12854. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12855. var currentViewport = this._cachedViewport;
  12856. this._cachedViewport = null;
  12857. this._gl.viewport(x, y, width, height);
  12858. return currentViewport;
  12859. };
  12860. /**
  12861. * Begin a new frame
  12862. */
  12863. Engine.prototype.beginFrame = function () {
  12864. this.onBeginFrameObservable.notifyObservers(this);
  12865. this._measureFps();
  12866. };
  12867. /**
  12868. * Enf the current frame
  12869. */
  12870. Engine.prototype.endFrame = function () {
  12871. // Force a flush in case we are using a bad OS.
  12872. if (this._badOS) {
  12873. this.flushFramebuffer();
  12874. }
  12875. // Submit frame to the vr device, if enabled
  12876. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12877. // TODO: We should only submit the frame if we read frameData successfully.
  12878. this._vrDisplay.submitFrame();
  12879. }
  12880. this.onEndFrameObservable.notifyObservers(this);
  12881. };
  12882. /**
  12883. * Resize the view according to the canvas' size
  12884. */
  12885. Engine.prototype.resize = function () {
  12886. // We're not resizing the size of the canvas while in VR mode & presenting
  12887. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12888. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12889. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12890. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12891. }
  12892. };
  12893. /**
  12894. * Force a specific size of the canvas
  12895. * @param width defines the new canvas' width
  12896. * @param height defines the new canvas' height
  12897. */
  12898. Engine.prototype.setSize = function (width, height) {
  12899. if (!this._renderingCanvas) {
  12900. return;
  12901. }
  12902. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12903. return;
  12904. }
  12905. this._renderingCanvas.width = width;
  12906. this._renderingCanvas.height = height;
  12907. for (var index = 0; index < this.scenes.length; index++) {
  12908. var scene = this.scenes[index];
  12909. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12910. var cam = scene.cameras[camIndex];
  12911. cam._currentRenderId = 0;
  12912. }
  12913. }
  12914. if (this.onResizeObservable.hasObservers) {
  12915. this.onResizeObservable.notifyObservers(this);
  12916. }
  12917. };
  12918. // WebVR functions
  12919. /**
  12920. * Gets a boolean indicating if a webVR device was detected
  12921. * @returns true if a webVR device was detected
  12922. */
  12923. Engine.prototype.isVRDevicePresent = function () {
  12924. return !!this._vrDisplay;
  12925. };
  12926. /**
  12927. * Gets the current webVR device
  12928. * @returns the current webVR device (or null)
  12929. */
  12930. Engine.prototype.getVRDevice = function () {
  12931. return this._vrDisplay;
  12932. };
  12933. /**
  12934. * Initializes a webVR display and starts listening to display change events
  12935. * The onVRDisplayChangedObservable will be notified upon these changes
  12936. * @returns The onVRDisplayChangedObservable
  12937. */
  12938. Engine.prototype.initWebVR = function () {
  12939. this.initWebVRAsync();
  12940. return this.onVRDisplayChangedObservable;
  12941. };
  12942. /**
  12943. * Initializes a webVR display and starts listening to display change events
  12944. * The onVRDisplayChangedObservable will be notified upon these changes
  12945. * @returns A promise containing a VRDisplay and if vr is supported
  12946. */
  12947. Engine.prototype.initWebVRAsync = function () {
  12948. var _this = this;
  12949. var notifyObservers = function () {
  12950. var eventArgs = {
  12951. vrDisplay: _this._vrDisplay,
  12952. vrSupported: _this._vrSupported
  12953. };
  12954. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12955. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12956. };
  12957. if (!this._onVrDisplayConnect) {
  12958. this._onVrDisplayConnect = function (event) {
  12959. _this._vrDisplay = event.display;
  12960. notifyObservers();
  12961. };
  12962. this._onVrDisplayDisconnect = function () {
  12963. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12964. _this._vrDisplay = undefined;
  12965. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12966. notifyObservers();
  12967. };
  12968. this._onVrDisplayPresentChange = function () {
  12969. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12970. };
  12971. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12972. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12973. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12974. }
  12975. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12976. this._webVRInitPromise.then(notifyObservers);
  12977. return this._webVRInitPromise;
  12978. };
  12979. /**
  12980. * Call this function to switch to webVR mode
  12981. * Will do nothing if webVR is not supported or if there is no webVR device
  12982. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12983. */
  12984. Engine.prototype.enableVR = function () {
  12985. var _this = this;
  12986. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12987. var onResolved = function () {
  12988. _this.onVRRequestPresentComplete.notifyObservers(true);
  12989. _this._onVRFullScreenTriggered();
  12990. };
  12991. var onRejected = function () {
  12992. _this.onVRRequestPresentComplete.notifyObservers(false);
  12993. };
  12994. this.onVRRequestPresentStart.notifyObservers(this);
  12995. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12996. }
  12997. };
  12998. /**
  12999. * Call this function to leave webVR mode
  13000. * Will do nothing if webVR is not supported or if there is no webVR device
  13001. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13002. */
  13003. Engine.prototype.disableVR = function () {
  13004. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13005. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13006. }
  13007. };
  13008. Engine.prototype._getVRDisplaysAsync = function () {
  13009. var _this = this;
  13010. return new Promise(function (res, rej) {
  13011. if (navigator.getVRDisplays) {
  13012. navigator.getVRDisplays().then(function (devices) {
  13013. _this._vrSupported = true;
  13014. // note that devices may actually be an empty array. This is fine;
  13015. // we expect this._vrDisplay to be undefined in this case.
  13016. _this._vrDisplay = devices[0];
  13017. res({
  13018. vrDisplay: _this._vrDisplay,
  13019. vrSupported: _this._vrSupported
  13020. });
  13021. });
  13022. }
  13023. else {
  13024. _this._vrDisplay = undefined;
  13025. _this._vrSupported = false;
  13026. res({
  13027. vrDisplay: _this._vrDisplay,
  13028. vrSupported: _this._vrSupported
  13029. });
  13030. }
  13031. });
  13032. };
  13033. /**
  13034. * Binds the frame buffer to the specified texture.
  13035. * @param texture The texture to render to or null for the default canvas
  13036. * @param faceIndex The face of the texture to render to in case of cube texture
  13037. * @param requiredWidth The width of the target to render to
  13038. * @param requiredHeight The height of the target to render to
  13039. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13040. * @param depthStencilTexture The depth stencil texture to use to render
  13041. * @param lodLevel defines le lod level to bind to the frame buffer
  13042. */
  13043. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13044. if (lodLevel === void 0) { lodLevel = 0; }
  13045. if (this._currentRenderTarget) {
  13046. this.unBindFramebuffer(this._currentRenderTarget);
  13047. }
  13048. this._currentRenderTarget = texture;
  13049. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13050. var gl = this._gl;
  13051. if (texture.isCube) {
  13052. if (faceIndex === undefined) {
  13053. faceIndex = 0;
  13054. }
  13055. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13056. if (depthStencilTexture) {
  13057. if (depthStencilTexture._generateStencilBuffer) {
  13058. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13059. }
  13060. else {
  13061. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13062. }
  13063. }
  13064. }
  13065. if (this._cachedViewport && !forceFullscreenViewport) {
  13066. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13067. }
  13068. else {
  13069. if (!requiredWidth) {
  13070. requiredWidth = texture.width;
  13071. if (lodLevel) {
  13072. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13073. }
  13074. }
  13075. if (!requiredHeight) {
  13076. requiredHeight = texture.height;
  13077. if (lodLevel) {
  13078. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13079. }
  13080. }
  13081. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13082. }
  13083. this.wipeCaches();
  13084. };
  13085. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13086. if (this._currentFramebuffer !== framebuffer) {
  13087. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13088. this._currentFramebuffer = framebuffer;
  13089. }
  13090. };
  13091. /**
  13092. * Unbind the current render target texture from the webGL context
  13093. * @param texture defines the render target texture to unbind
  13094. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13095. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13096. */
  13097. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13098. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13099. this._currentRenderTarget = null;
  13100. // If MSAA, we need to bitblt back to main texture
  13101. var gl = this._gl;
  13102. if (texture._MSAAFramebuffer) {
  13103. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13104. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13105. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13106. }
  13107. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13108. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13109. gl.generateMipmap(gl.TEXTURE_2D);
  13110. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13111. }
  13112. if (onBeforeUnbind) {
  13113. if (texture._MSAAFramebuffer) {
  13114. // Bind the correct framebuffer
  13115. this.bindUnboundFramebuffer(texture._framebuffer);
  13116. }
  13117. onBeforeUnbind();
  13118. }
  13119. this.bindUnboundFramebuffer(null);
  13120. };
  13121. /**
  13122. * Unbind a list of render target textures from the webGL context
  13123. * This is used only when drawBuffer extension or webGL2 are active
  13124. * @param textures defines the render target textures to unbind
  13125. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13126. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13127. */
  13128. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13129. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13130. this._currentRenderTarget = null;
  13131. // If MSAA, we need to bitblt back to main texture
  13132. var gl = this._gl;
  13133. if (textures[0]._MSAAFramebuffer) {
  13134. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13135. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13136. var attachments = textures[0]._attachments;
  13137. if (!attachments) {
  13138. attachments = new Array(textures.length);
  13139. textures[0]._attachments = attachments;
  13140. }
  13141. for (var i = 0; i < textures.length; i++) {
  13142. var texture = textures[i];
  13143. for (var j = 0; j < attachments.length; j++) {
  13144. attachments[j] = gl.NONE;
  13145. }
  13146. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13147. gl.readBuffer(attachments[i]);
  13148. gl.drawBuffers(attachments);
  13149. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13150. }
  13151. for (var i = 0; i < attachments.length; i++) {
  13152. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13153. }
  13154. gl.drawBuffers(attachments);
  13155. }
  13156. for (var i = 0; i < textures.length; i++) {
  13157. var texture = textures[i];
  13158. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13159. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13160. gl.generateMipmap(gl.TEXTURE_2D);
  13161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13162. }
  13163. }
  13164. if (onBeforeUnbind) {
  13165. if (textures[0]._MSAAFramebuffer) {
  13166. // Bind the correct framebuffer
  13167. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13168. }
  13169. onBeforeUnbind();
  13170. }
  13171. this.bindUnboundFramebuffer(null);
  13172. };
  13173. /**
  13174. * Force the mipmap generation for the given render target texture
  13175. * @param texture defines the render target texture to use
  13176. */
  13177. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13178. if (texture.generateMipMaps) {
  13179. var gl = this._gl;
  13180. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13181. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13182. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13183. }
  13184. };
  13185. /**
  13186. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13187. */
  13188. Engine.prototype.flushFramebuffer = function () {
  13189. this._gl.flush();
  13190. };
  13191. /**
  13192. * Unbind the current render target and bind the default framebuffer
  13193. */
  13194. Engine.prototype.restoreDefaultFramebuffer = function () {
  13195. if (this._currentRenderTarget) {
  13196. this.unBindFramebuffer(this._currentRenderTarget);
  13197. }
  13198. else {
  13199. this.bindUnboundFramebuffer(null);
  13200. }
  13201. if (this._cachedViewport) {
  13202. this.setViewport(this._cachedViewport);
  13203. }
  13204. this.wipeCaches();
  13205. };
  13206. // UBOs
  13207. /**
  13208. * Create an uniform buffer
  13209. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13210. * @param elements defines the content of the uniform buffer
  13211. * @returns the webGL uniform buffer
  13212. */
  13213. Engine.prototype.createUniformBuffer = function (elements) {
  13214. var ubo = this._gl.createBuffer();
  13215. if (!ubo) {
  13216. throw new Error("Unable to create uniform buffer");
  13217. }
  13218. this.bindUniformBuffer(ubo);
  13219. if (elements instanceof Float32Array) {
  13220. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13221. }
  13222. else {
  13223. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13224. }
  13225. this.bindUniformBuffer(null);
  13226. ubo.references = 1;
  13227. return ubo;
  13228. };
  13229. /**
  13230. * Create a dynamic uniform buffer
  13231. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13232. * @param elements defines the content of the uniform buffer
  13233. * @returns the webGL uniform buffer
  13234. */
  13235. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13236. var ubo = this._gl.createBuffer();
  13237. if (!ubo) {
  13238. throw new Error("Unable to create dynamic uniform buffer");
  13239. }
  13240. this.bindUniformBuffer(ubo);
  13241. if (elements instanceof Float32Array) {
  13242. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13243. }
  13244. else {
  13245. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13246. }
  13247. this.bindUniformBuffer(null);
  13248. ubo.references = 1;
  13249. return ubo;
  13250. };
  13251. /**
  13252. * Update an existing uniform buffer
  13253. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13254. * @param uniformBuffer defines the target uniform buffer
  13255. * @param elements defines the content to update
  13256. * @param offset defines the offset in the uniform buffer where update should start
  13257. * @param count defines the size of the data to update
  13258. */
  13259. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13260. this.bindUniformBuffer(uniformBuffer);
  13261. if (offset === undefined) {
  13262. offset = 0;
  13263. }
  13264. if (count === undefined) {
  13265. if (elements instanceof Float32Array) {
  13266. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13267. }
  13268. else {
  13269. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13270. }
  13271. }
  13272. else {
  13273. if (elements instanceof Float32Array) {
  13274. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13275. }
  13276. else {
  13277. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13278. }
  13279. }
  13280. this.bindUniformBuffer(null);
  13281. };
  13282. // VBOs
  13283. Engine.prototype._resetVertexBufferBinding = function () {
  13284. this.bindArrayBuffer(null);
  13285. this._cachedVertexBuffers = null;
  13286. };
  13287. /**
  13288. * Creates a vertex buffer
  13289. * @param data the data for the vertex buffer
  13290. * @returns the new WebGL static buffer
  13291. */
  13292. Engine.prototype.createVertexBuffer = function (data) {
  13293. var vbo = this._gl.createBuffer();
  13294. if (!vbo) {
  13295. throw new Error("Unable to create vertex buffer");
  13296. }
  13297. this.bindArrayBuffer(vbo);
  13298. if (data instanceof Array) {
  13299. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13300. }
  13301. else {
  13302. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13303. }
  13304. this._resetVertexBufferBinding();
  13305. vbo.references = 1;
  13306. return vbo;
  13307. };
  13308. /**
  13309. * Creates a dynamic vertex buffer
  13310. * @param data the data for the dynamic vertex buffer
  13311. * @returns the new WebGL dynamic buffer
  13312. */
  13313. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13314. var vbo = this._gl.createBuffer();
  13315. if (!vbo) {
  13316. throw new Error("Unable to create dynamic vertex buffer");
  13317. }
  13318. this.bindArrayBuffer(vbo);
  13319. if (data instanceof Array) {
  13320. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13321. }
  13322. else {
  13323. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13324. }
  13325. this._resetVertexBufferBinding();
  13326. vbo.references = 1;
  13327. return vbo;
  13328. };
  13329. /**
  13330. * Update a dynamic index buffer
  13331. * @param indexBuffer defines the target index buffer
  13332. * @param indices defines the data to update
  13333. * @param offset defines the offset in the target index buffer where update should start
  13334. */
  13335. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13336. if (offset === void 0) { offset = 0; }
  13337. // Force cache update
  13338. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13339. this.bindIndexBuffer(indexBuffer);
  13340. var arrayBuffer;
  13341. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13342. arrayBuffer = indices;
  13343. }
  13344. else {
  13345. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13346. }
  13347. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13348. this._resetIndexBufferBinding();
  13349. };
  13350. /**
  13351. * Updates a dynamic vertex buffer.
  13352. * @param vertexBuffer the vertex buffer to update
  13353. * @param data the data used to update the vertex buffer
  13354. * @param byteOffset the byte offset of the data
  13355. * @param byteLength the byte length of the data
  13356. */
  13357. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13358. this.bindArrayBuffer(vertexBuffer);
  13359. if (byteOffset === undefined) {
  13360. byteOffset = 0;
  13361. }
  13362. if (byteLength === undefined) {
  13363. if (data instanceof Array) {
  13364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13365. }
  13366. else {
  13367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13368. }
  13369. }
  13370. else {
  13371. if (data instanceof Array) {
  13372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13373. }
  13374. else {
  13375. if (data instanceof ArrayBuffer) {
  13376. data = new Uint8Array(data, byteOffset, byteLength);
  13377. }
  13378. else {
  13379. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13380. }
  13381. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13382. }
  13383. }
  13384. this._resetVertexBufferBinding();
  13385. };
  13386. Engine.prototype._resetIndexBufferBinding = function () {
  13387. this.bindIndexBuffer(null);
  13388. this._cachedIndexBuffer = null;
  13389. };
  13390. /**
  13391. * Creates a new index buffer
  13392. * @param indices defines the content of the index buffer
  13393. * @param updatable defines if the index buffer must be updatable
  13394. * @returns a new webGL buffer
  13395. */
  13396. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13397. var vbo = this._gl.createBuffer();
  13398. if (!vbo) {
  13399. throw new Error("Unable to create index buffer");
  13400. }
  13401. this.bindIndexBuffer(vbo);
  13402. // Check for 32 bits indices
  13403. var arrayBuffer;
  13404. var need32Bits = false;
  13405. if (indices instanceof Uint16Array) {
  13406. arrayBuffer = indices;
  13407. }
  13408. else {
  13409. //check 32 bit support
  13410. if (this._caps.uintIndices) {
  13411. if (indices instanceof Uint32Array) {
  13412. arrayBuffer = indices;
  13413. need32Bits = true;
  13414. }
  13415. else {
  13416. //number[] or Int32Array, check if 32 bit is necessary
  13417. for (var index = 0; index < indices.length; index++) {
  13418. if (indices[index] > 65535) {
  13419. need32Bits = true;
  13420. break;
  13421. }
  13422. }
  13423. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13424. }
  13425. }
  13426. else {
  13427. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13428. arrayBuffer = new Uint16Array(indices);
  13429. }
  13430. }
  13431. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13432. this._resetIndexBufferBinding();
  13433. vbo.references = 1;
  13434. vbo.is32Bits = need32Bits;
  13435. return vbo;
  13436. };
  13437. /**
  13438. * Bind a webGL buffer to the webGL context
  13439. * @param buffer defines the buffer to bind
  13440. */
  13441. Engine.prototype.bindArrayBuffer = function (buffer) {
  13442. if (!this._vaoRecordInProgress) {
  13443. this._unbindVertexArrayObject();
  13444. }
  13445. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13446. };
  13447. /**
  13448. * Bind an uniform buffer to the current webGL context
  13449. * @param buffer defines the buffer to bind
  13450. */
  13451. Engine.prototype.bindUniformBuffer = function (buffer) {
  13452. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13453. };
  13454. /**
  13455. * Bind a buffer to the current webGL context at a given location
  13456. * @param buffer defines the buffer to bind
  13457. * @param location defines the index where to bind the buffer
  13458. */
  13459. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13460. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13461. };
  13462. /**
  13463. * Bind a specific block at a given index in a specific shader program
  13464. * @param shaderProgram defines the shader program
  13465. * @param blockName defines the block name
  13466. * @param index defines the index where to bind the block
  13467. */
  13468. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13469. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13470. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13471. };
  13472. ;
  13473. Engine.prototype.bindIndexBuffer = function (buffer) {
  13474. if (!this._vaoRecordInProgress) {
  13475. this._unbindVertexArrayObject();
  13476. }
  13477. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13478. };
  13479. Engine.prototype.bindBuffer = function (buffer, target) {
  13480. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13481. this._gl.bindBuffer(target, buffer);
  13482. this._currentBoundBuffer[target] = buffer;
  13483. }
  13484. };
  13485. /**
  13486. * update the bound buffer with the given data
  13487. * @param data defines the data to update
  13488. */
  13489. Engine.prototype.updateArrayBuffer = function (data) {
  13490. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13491. };
  13492. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13493. var pointer = this._currentBufferPointers[indx];
  13494. var changed = false;
  13495. if (!pointer.active) {
  13496. changed = true;
  13497. pointer.active = true;
  13498. pointer.index = indx;
  13499. pointer.size = size;
  13500. pointer.type = type;
  13501. pointer.normalized = normalized;
  13502. pointer.stride = stride;
  13503. pointer.offset = offset;
  13504. pointer.buffer = buffer;
  13505. }
  13506. else {
  13507. if (pointer.buffer !== buffer) {
  13508. pointer.buffer = buffer;
  13509. changed = true;
  13510. }
  13511. if (pointer.size !== size) {
  13512. pointer.size = size;
  13513. changed = true;
  13514. }
  13515. if (pointer.type !== type) {
  13516. pointer.type = type;
  13517. changed = true;
  13518. }
  13519. if (pointer.normalized !== normalized) {
  13520. pointer.normalized = normalized;
  13521. changed = true;
  13522. }
  13523. if (pointer.stride !== stride) {
  13524. pointer.stride = stride;
  13525. changed = true;
  13526. }
  13527. if (pointer.offset !== offset) {
  13528. pointer.offset = offset;
  13529. changed = true;
  13530. }
  13531. }
  13532. if (changed || this._vaoRecordInProgress) {
  13533. this.bindArrayBuffer(buffer);
  13534. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13535. }
  13536. };
  13537. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13538. if (indexBuffer == null) {
  13539. return;
  13540. }
  13541. if (this._cachedIndexBuffer !== indexBuffer) {
  13542. this._cachedIndexBuffer = indexBuffer;
  13543. this.bindIndexBuffer(indexBuffer);
  13544. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13545. }
  13546. };
  13547. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13548. var attributes = effect.getAttributesNames();
  13549. if (!this._vaoRecordInProgress) {
  13550. this._unbindVertexArrayObject();
  13551. }
  13552. this.unbindAllAttributes();
  13553. for (var index = 0; index < attributes.length; index++) {
  13554. var order = effect.getAttributeLocation(index);
  13555. if (order >= 0) {
  13556. var vertexBuffer = vertexBuffers[attributes[index]];
  13557. if (!vertexBuffer) {
  13558. continue;
  13559. }
  13560. this._gl.enableVertexAttribArray(order);
  13561. if (!this._vaoRecordInProgress) {
  13562. this._vertexAttribArraysEnabled[order] = true;
  13563. }
  13564. var buffer = vertexBuffer.getBuffer();
  13565. if (buffer) {
  13566. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13567. if (vertexBuffer.getIsInstanced()) {
  13568. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13569. if (!this._vaoRecordInProgress) {
  13570. this._currentInstanceLocations.push(order);
  13571. this._currentInstanceBuffers.push(buffer);
  13572. }
  13573. }
  13574. }
  13575. }
  13576. }
  13577. };
  13578. /**
  13579. * Records a vertex array object
  13580. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13581. * @param vertexBuffers defines the list of vertex buffers to store
  13582. * @param indexBuffer defines the index buffer to store
  13583. * @param effect defines the effect to store
  13584. * @returns the new vertex array object
  13585. */
  13586. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13587. var vao = this._gl.createVertexArray();
  13588. this._vaoRecordInProgress = true;
  13589. this._gl.bindVertexArray(vao);
  13590. this._mustWipeVertexAttributes = true;
  13591. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13592. this.bindIndexBuffer(indexBuffer);
  13593. this._vaoRecordInProgress = false;
  13594. this._gl.bindVertexArray(null);
  13595. return vao;
  13596. };
  13597. /**
  13598. * Bind a specific vertex array object
  13599. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13600. * @param vertexArrayObject defines the vertex array object to bind
  13601. * @param indexBuffer defines the index buffer to bind
  13602. */
  13603. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13604. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13605. this._cachedVertexArrayObject = vertexArrayObject;
  13606. this._gl.bindVertexArray(vertexArrayObject);
  13607. this._cachedVertexBuffers = null;
  13608. this._cachedIndexBuffer = null;
  13609. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13610. this._mustWipeVertexAttributes = true;
  13611. }
  13612. };
  13613. /**
  13614. * Bind webGl buffers directly to the webGL context
  13615. * @param vertexBuffer defines the vertex buffer to bind
  13616. * @param indexBuffer defines the index buffer to bind
  13617. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13618. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13619. * @param effect defines the effect associated with the vertex buffer
  13620. */
  13621. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13622. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13623. this._cachedVertexBuffers = vertexBuffer;
  13624. this._cachedEffectForVertexBuffers = effect;
  13625. var attributesCount = effect.getAttributesCount();
  13626. this._unbindVertexArrayObject();
  13627. this.unbindAllAttributes();
  13628. var offset = 0;
  13629. for (var index = 0; index < attributesCount; index++) {
  13630. if (index < vertexDeclaration.length) {
  13631. var order = effect.getAttributeLocation(index);
  13632. if (order >= 0) {
  13633. this._gl.enableVertexAttribArray(order);
  13634. this._vertexAttribArraysEnabled[order] = true;
  13635. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13636. }
  13637. offset += vertexDeclaration[index] * 4;
  13638. }
  13639. }
  13640. }
  13641. this._bindIndexBufferWithCache(indexBuffer);
  13642. };
  13643. Engine.prototype._unbindVertexArrayObject = function () {
  13644. if (!this._cachedVertexArrayObject) {
  13645. return;
  13646. }
  13647. this._cachedVertexArrayObject = null;
  13648. this._gl.bindVertexArray(null);
  13649. };
  13650. /**
  13651. * Bind a list of vertex buffers to the webGL context
  13652. * @param vertexBuffers defines the list of vertex buffers to bind
  13653. * @param indexBuffer defines the index buffer to bind
  13654. * @param effect defines the effect associated with the vertex buffers
  13655. */
  13656. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13657. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13658. this._cachedVertexBuffers = vertexBuffers;
  13659. this._cachedEffectForVertexBuffers = effect;
  13660. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13661. }
  13662. this._bindIndexBufferWithCache(indexBuffer);
  13663. };
  13664. /**
  13665. * Unbind all instance attributes
  13666. */
  13667. Engine.prototype.unbindInstanceAttributes = function () {
  13668. var boundBuffer;
  13669. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13670. var instancesBuffer = this._currentInstanceBuffers[i];
  13671. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13672. boundBuffer = instancesBuffer;
  13673. this.bindArrayBuffer(instancesBuffer);
  13674. }
  13675. var offsetLocation = this._currentInstanceLocations[i];
  13676. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13677. }
  13678. this._currentInstanceBuffers.length = 0;
  13679. this._currentInstanceLocations.length = 0;
  13680. };
  13681. /**
  13682. * Release and free the memory of a vertex array object
  13683. * @param vao defines the vertex array object to delete
  13684. */
  13685. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13686. this._gl.deleteVertexArray(vao);
  13687. };
  13688. /** @hidden */
  13689. Engine.prototype._releaseBuffer = function (buffer) {
  13690. buffer.references--;
  13691. if (buffer.references === 0) {
  13692. this._gl.deleteBuffer(buffer);
  13693. return true;
  13694. }
  13695. return false;
  13696. };
  13697. /**
  13698. * Creates a webGL buffer to use with instanciation
  13699. * @param capacity defines the size of the buffer
  13700. * @returns the webGL buffer
  13701. */
  13702. Engine.prototype.createInstancesBuffer = function (capacity) {
  13703. var buffer = this._gl.createBuffer();
  13704. if (!buffer) {
  13705. throw new Error("Unable to create instance buffer");
  13706. }
  13707. buffer.capacity = capacity;
  13708. this.bindArrayBuffer(buffer);
  13709. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13710. return buffer;
  13711. };
  13712. /**
  13713. * Delete a webGL buffer used with instanciation
  13714. * @param buffer defines the webGL buffer to delete
  13715. */
  13716. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13717. this._gl.deleteBuffer(buffer);
  13718. };
  13719. /**
  13720. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13721. * @param instancesBuffer defines the webGL buffer to update and bind
  13722. * @param data defines the data to store in the buffer
  13723. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13724. */
  13725. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13726. this.bindArrayBuffer(instancesBuffer);
  13727. if (data) {
  13728. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13729. }
  13730. if (offsetLocations[0].index !== undefined) {
  13731. var stride = 0;
  13732. for (var i = 0; i < offsetLocations.length; i++) {
  13733. var ai = offsetLocations[i];
  13734. stride += ai.attributeSize * 4;
  13735. }
  13736. for (var i = 0; i < offsetLocations.length; i++) {
  13737. var ai = offsetLocations[i];
  13738. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13739. this._gl.enableVertexAttribArray(ai.index);
  13740. this._vertexAttribArraysEnabled[ai.index] = true;
  13741. }
  13742. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13743. this._gl.vertexAttribDivisor(ai.index, 1);
  13744. this._currentInstanceLocations.push(ai.index);
  13745. this._currentInstanceBuffers.push(instancesBuffer);
  13746. }
  13747. }
  13748. else {
  13749. for (var index = 0; index < 4; index++) {
  13750. var offsetLocation = offsetLocations[index];
  13751. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13752. this._gl.enableVertexAttribArray(offsetLocation);
  13753. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13754. }
  13755. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13756. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13757. this._currentInstanceLocations.push(offsetLocation);
  13758. this._currentInstanceBuffers.push(instancesBuffer);
  13759. }
  13760. }
  13761. };
  13762. /**
  13763. * Apply all cached states (depth, culling, stencil and alpha)
  13764. */
  13765. Engine.prototype.applyStates = function () {
  13766. this._depthCullingState.apply(this._gl);
  13767. this._stencilState.apply(this._gl);
  13768. this._alphaState.apply(this._gl);
  13769. };
  13770. /**
  13771. * Send a draw order
  13772. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13773. * @param indexStart defines the starting index
  13774. * @param indexCount defines the number of index to draw
  13775. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13776. */
  13777. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13778. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13779. };
  13780. /**
  13781. * Draw a list of points
  13782. * @param verticesStart defines the index of first vertex to draw
  13783. * @param verticesCount defines the count of vertices to draw
  13784. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13785. */
  13786. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13787. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13788. };
  13789. /**
  13790. * Draw a list of unindexed primitives
  13791. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13792. * @param verticesStart defines the index of first vertex to draw
  13793. * @param verticesCount defines the count of vertices to draw
  13794. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13795. */
  13796. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13797. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13798. };
  13799. /**
  13800. * Draw a list of indexed primitives
  13801. * @param fillMode defines the primitive to use
  13802. * @param indexStart defines the starting index
  13803. * @param indexCount defines the number of index to draw
  13804. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13805. */
  13806. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13807. // Apply states
  13808. this.applyStates();
  13809. this._drawCalls.addCount(1, false);
  13810. // Render
  13811. var drawMode = this._drawMode(fillMode);
  13812. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13813. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13814. if (instancesCount) {
  13815. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13816. }
  13817. else {
  13818. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13819. }
  13820. };
  13821. /**
  13822. * Draw a list of unindexed primitives
  13823. * @param fillMode defines the primitive to use
  13824. * @param verticesStart defines the index of first vertex to draw
  13825. * @param verticesCount defines the count of vertices to draw
  13826. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13827. */
  13828. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13829. // Apply states
  13830. this.applyStates();
  13831. this._drawCalls.addCount(1, false);
  13832. var drawMode = this._drawMode(fillMode);
  13833. if (instancesCount) {
  13834. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13835. }
  13836. else {
  13837. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13838. }
  13839. };
  13840. Engine.prototype._drawMode = function (fillMode) {
  13841. switch (fillMode) {
  13842. // Triangle views
  13843. case BABYLON.Material.TriangleFillMode:
  13844. return this._gl.TRIANGLES;
  13845. case BABYLON.Material.PointFillMode:
  13846. return this._gl.POINTS;
  13847. case BABYLON.Material.WireFrameFillMode:
  13848. return this._gl.LINES;
  13849. // Draw modes
  13850. case BABYLON.Material.PointListDrawMode:
  13851. return this._gl.POINTS;
  13852. case BABYLON.Material.LineListDrawMode:
  13853. return this._gl.LINES;
  13854. case BABYLON.Material.LineLoopDrawMode:
  13855. return this._gl.LINE_LOOP;
  13856. case BABYLON.Material.LineStripDrawMode:
  13857. return this._gl.LINE_STRIP;
  13858. case BABYLON.Material.TriangleStripDrawMode:
  13859. return this._gl.TRIANGLE_STRIP;
  13860. case BABYLON.Material.TriangleFanDrawMode:
  13861. return this._gl.TRIANGLE_FAN;
  13862. default:
  13863. return this._gl.TRIANGLES;
  13864. }
  13865. };
  13866. // Shaders
  13867. /** @hidden */
  13868. Engine.prototype._releaseEffect = function (effect) {
  13869. if (this._compiledEffects[effect._key]) {
  13870. delete this._compiledEffects[effect._key];
  13871. this._deleteProgram(effect.getProgram());
  13872. }
  13873. };
  13874. /** @hidden */
  13875. Engine.prototype._deleteProgram = function (program) {
  13876. if (program) {
  13877. program.__SPECTOR_rebuildProgram = null;
  13878. if (program.transformFeedback) {
  13879. this.deleteTransformFeedback(program.transformFeedback);
  13880. program.transformFeedback = null;
  13881. }
  13882. this._gl.deleteProgram(program);
  13883. }
  13884. };
  13885. /**
  13886. * Create a new effect (used to store vertex/fragment shaders)
  13887. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13888. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13889. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13890. * @param samplers defines an array of string used to represent textures
  13891. * @param defines defines the string containing the defines to use to compile the shaders
  13892. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13893. * @param onCompiled defines a function to call when the effect creation is successful
  13894. * @param onError defines a function to call when the effect creation has failed
  13895. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13896. * @returns the new Effect
  13897. */
  13898. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13899. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13900. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13901. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13902. if (this._compiledEffects[name]) {
  13903. var compiledEffect = this._compiledEffects[name];
  13904. if (onCompiled && compiledEffect.isReady()) {
  13905. onCompiled(compiledEffect);
  13906. }
  13907. return compiledEffect;
  13908. }
  13909. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13910. effect._key = name;
  13911. this._compiledEffects[name] = effect;
  13912. return effect;
  13913. };
  13914. /**
  13915. * Create an effect to use with particle systems
  13916. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13917. * @param uniformsNames defines a list of attribute names
  13918. * @param samplers defines an array of string used to represent textures
  13919. * @param defines defines the string containing the defines to use to compile the shaders
  13920. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13921. * @param onCompiled defines a function to call when the effect creation is successful
  13922. * @param onError defines a function to call when the effect creation has failed
  13923. * @returns the new Effect
  13924. */
  13925. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13926. if (uniformsNames === void 0) { uniformsNames = []; }
  13927. if (samplers === void 0) { samplers = []; }
  13928. if (defines === void 0) { defines = ""; }
  13929. return this.createEffect({
  13930. vertex: "particles",
  13931. fragmentElement: fragmentName
  13932. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13933. };
  13934. /**
  13935. * Directly creates a webGL program
  13936. * @param vertexCode defines the vertex shader code to use
  13937. * @param fragmentCode defines the fragment shader code to use
  13938. * @param context defines the webGL context to use (if not set, the current one will be used)
  13939. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13940. * @returns the new webGL program
  13941. */
  13942. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13943. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13944. context = context || this._gl;
  13945. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13946. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13947. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13948. };
  13949. /**
  13950. * Creates a webGL program
  13951. * @param vertexCode defines the vertex shader code to use
  13952. * @param fragmentCode defines the fragment shader code to use
  13953. * @param defines defines the string containing the defines to use to compile the shaders
  13954. * @param context defines the webGL context to use (if not set, the current one will be used)
  13955. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13956. * @returns the new webGL program
  13957. */
  13958. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13959. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13960. context = context || this._gl;
  13961. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13962. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13963. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13964. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13965. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13966. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13967. return program;
  13968. };
  13969. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13970. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13971. var shaderProgram = context.createProgram();
  13972. if (!shaderProgram) {
  13973. throw new Error("Unable to create program");
  13974. }
  13975. context.attachShader(shaderProgram, vertexShader);
  13976. context.attachShader(shaderProgram, fragmentShader);
  13977. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13978. var transformFeedback = this.createTransformFeedback();
  13979. this.bindTransformFeedback(transformFeedback);
  13980. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13981. shaderProgram.transformFeedback = transformFeedback;
  13982. }
  13983. context.linkProgram(shaderProgram);
  13984. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13985. this.bindTransformFeedback(null);
  13986. }
  13987. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13988. if (!linked) {
  13989. context.validateProgram(shaderProgram);
  13990. var error = context.getProgramInfoLog(shaderProgram);
  13991. if (error) {
  13992. throw new Error(error);
  13993. }
  13994. }
  13995. context.deleteShader(vertexShader);
  13996. context.deleteShader(fragmentShader);
  13997. return shaderProgram;
  13998. };
  13999. /**
  14000. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14001. * @param shaderProgram defines the webGL program to use
  14002. * @param uniformsNames defines the list of uniform names
  14003. * @returns an array of webGL uniform locations
  14004. */
  14005. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14006. var results = new Array();
  14007. for (var index = 0; index < uniformsNames.length; index++) {
  14008. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14009. }
  14010. return results;
  14011. };
  14012. /**
  14013. * Gets the lsit of active attributes for a given webGL program
  14014. * @param shaderProgram defines the webGL program to use
  14015. * @param attributesNames defines the list of attribute names to get
  14016. * @returns an array of indices indicating the offset of each attribute
  14017. */
  14018. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14019. var results = [];
  14020. for (var index = 0; index < attributesNames.length; index++) {
  14021. try {
  14022. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14023. }
  14024. catch (e) {
  14025. results.push(-1);
  14026. }
  14027. }
  14028. return results;
  14029. };
  14030. /**
  14031. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14032. * @param effect defines the effect to activate
  14033. */
  14034. Engine.prototype.enableEffect = function (effect) {
  14035. if (!effect) {
  14036. return;
  14037. }
  14038. // Use program
  14039. this.bindSamplers(effect);
  14040. this._currentEffect = effect;
  14041. if (effect.onBind) {
  14042. effect.onBind(effect);
  14043. }
  14044. effect.onBindObservable.notifyObservers(effect);
  14045. };
  14046. /**
  14047. * Set the value of an uniform to an array of int32
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param array defines the array of int32 to store
  14050. */
  14051. Engine.prototype.setIntArray = function (uniform, array) {
  14052. if (!uniform)
  14053. return;
  14054. this._gl.uniform1iv(uniform, array);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of int32 (stored as vec2)
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param array defines the array of int32 to store
  14060. */
  14061. Engine.prototype.setIntArray2 = function (uniform, array) {
  14062. if (!uniform || array.length % 2 !== 0)
  14063. return;
  14064. this._gl.uniform2iv(uniform, array);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of int32 (stored as vec3)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param array defines the array of int32 to store
  14070. */
  14071. Engine.prototype.setIntArray3 = function (uniform, array) {
  14072. if (!uniform || array.length % 3 !== 0)
  14073. return;
  14074. this._gl.uniform3iv(uniform, array);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to an array of int32 (stored as vec4)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param array defines the array of int32 to store
  14080. */
  14081. Engine.prototype.setIntArray4 = function (uniform, array) {
  14082. if (!uniform || array.length % 4 !== 0)
  14083. return;
  14084. this._gl.uniform4iv(uniform, array);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to an array of float32
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param array defines the array of float32 to store
  14090. */
  14091. Engine.prototype.setFloatArray = function (uniform, array) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniform1fv(uniform, array);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to an array of float32 (stored as vec2)
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param array defines the array of float32 to store
  14100. */
  14101. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14102. if (!uniform || array.length % 2 !== 0)
  14103. return;
  14104. this._gl.uniform2fv(uniform, array);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to an array of float32 (stored as vec3)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param array defines the array of float32 to store
  14110. */
  14111. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14112. if (!uniform || array.length % 3 !== 0)
  14113. return;
  14114. this._gl.uniform3fv(uniform, array);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to an array of float32 (stored as vec4)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param array defines the array of float32 to store
  14120. */
  14121. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14122. if (!uniform || array.length % 4 !== 0)
  14123. return;
  14124. this._gl.uniform4fv(uniform, array);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to an array of number
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param array defines the array of number to store
  14130. */
  14131. Engine.prototype.setArray = function (uniform, array) {
  14132. if (!uniform)
  14133. return;
  14134. this._gl.uniform1fv(uniform, array);
  14135. };
  14136. /**
  14137. * Set the value of an uniform to an array of number (stored as vec2)
  14138. * @param uniform defines the webGL uniform location where to store the value
  14139. * @param array defines the array of number to store
  14140. */
  14141. Engine.prototype.setArray2 = function (uniform, array) {
  14142. if (!uniform || array.length % 2 !== 0)
  14143. return;
  14144. this._gl.uniform2fv(uniform, array);
  14145. };
  14146. /**
  14147. * Set the value of an uniform to an array of number (stored as vec3)
  14148. * @param uniform defines the webGL uniform location where to store the value
  14149. * @param array defines the array of number to store
  14150. */
  14151. Engine.prototype.setArray3 = function (uniform, array) {
  14152. if (!uniform || array.length % 3 !== 0)
  14153. return;
  14154. this._gl.uniform3fv(uniform, array);
  14155. };
  14156. /**
  14157. * Set the value of an uniform to an array of number (stored as vec4)
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param array defines the array of number to store
  14160. */
  14161. Engine.prototype.setArray4 = function (uniform, array) {
  14162. if (!uniform || array.length % 4 !== 0)
  14163. return;
  14164. this._gl.uniform4fv(uniform, array);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to an array of float32 (stored as matrices)
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param matrices defines the array of float32 to store
  14170. */
  14171. Engine.prototype.setMatrices = function (uniform, matrices) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to a matrix
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param matrix defines the matrix to store
  14180. */
  14181. Engine.prototype.setMatrix = function (uniform, matrix) {
  14182. if (!uniform)
  14183. return;
  14184. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14185. };
  14186. /**
  14187. * Set the value of an uniform to a matrix (3x3)
  14188. * @param uniform defines the webGL uniform location where to store the value
  14189. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14190. */
  14191. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14192. if (!uniform)
  14193. return;
  14194. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14195. };
  14196. /**
  14197. * Set the value of an uniform to a matrix (2x2)
  14198. * @param uniform defines the webGL uniform location where to store the value
  14199. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14200. */
  14201. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a number (int)
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param value defines the int number to store
  14210. */
  14211. Engine.prototype.setInt = function (uniform, value) {
  14212. if (!uniform)
  14213. return;
  14214. this._gl.uniform1i(uniform, value);
  14215. };
  14216. /**
  14217. * Set the value of an uniform to a number (float)
  14218. * @param uniform defines the webGL uniform location where to store the value
  14219. * @param value defines the float number to store
  14220. */
  14221. Engine.prototype.setFloat = function (uniform, value) {
  14222. if (!uniform)
  14223. return;
  14224. this._gl.uniform1f(uniform, value);
  14225. };
  14226. /**
  14227. * Set the value of an uniform to a vec2
  14228. * @param uniform defines the webGL uniform location where to store the value
  14229. * @param x defines the 1st component of the value
  14230. * @param y defines the 2nd component of the value
  14231. */
  14232. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14233. if (!uniform)
  14234. return;
  14235. this._gl.uniform2f(uniform, x, y);
  14236. };
  14237. /**
  14238. * Set the value of an uniform to a vec3
  14239. * @param uniform defines the webGL uniform location where to store the value
  14240. * @param x defines the 1st component of the value
  14241. * @param y defines the 2nd component of the value
  14242. * @param z defines the 3rd component of the value
  14243. */
  14244. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14245. if (!uniform)
  14246. return;
  14247. this._gl.uniform3f(uniform, x, y, z);
  14248. };
  14249. /**
  14250. * Set the value of an uniform to a boolean
  14251. * @param uniform defines the webGL uniform location where to store the value
  14252. * @param bool defines the boolean to store
  14253. */
  14254. Engine.prototype.setBool = function (uniform, bool) {
  14255. if (!uniform)
  14256. return;
  14257. this._gl.uniform1i(uniform, bool);
  14258. };
  14259. /**
  14260. * Set the value of an uniform to a vec4
  14261. * @param uniform defines the webGL uniform location where to store the value
  14262. * @param x defines the 1st component of the value
  14263. * @param y defines the 2nd component of the value
  14264. * @param z defines the 3rd component of the value
  14265. * @param w defines the 4th component of the value
  14266. */
  14267. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14268. if (!uniform)
  14269. return;
  14270. this._gl.uniform4f(uniform, x, y, z, w);
  14271. };
  14272. /**
  14273. * Set the value of an uniform to a Color3
  14274. * @param uniform defines the webGL uniform location where to store the value
  14275. * @param color3 defines the color to store
  14276. */
  14277. Engine.prototype.setColor3 = function (uniform, color3) {
  14278. if (!uniform)
  14279. return;
  14280. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14281. };
  14282. /**
  14283. * Set the value of an uniform to a Color3 and an alpha value
  14284. * @param uniform defines the webGL uniform location where to store the value
  14285. * @param color3 defines the color to store
  14286. * @param alpha defines the alpha component to store
  14287. */
  14288. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14289. if (!uniform)
  14290. return;
  14291. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14292. };
  14293. /**
  14294. * Sets a Color4 on a uniform variable
  14295. * @param uniform defines the uniform location
  14296. * @param color4 defines the value to be set
  14297. */
  14298. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14299. if (!uniform)
  14300. return;
  14301. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14302. };
  14303. // States
  14304. /**
  14305. * Set various states to the webGL context
  14306. * @param culling defines backface culling state
  14307. * @param zOffset defines the value to apply to zOffset (0 by default)
  14308. * @param force defines if states must be applied even if cache is up to date
  14309. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14310. */
  14311. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14312. if (zOffset === void 0) { zOffset = 0; }
  14313. if (reverseSide === void 0) { reverseSide = false; }
  14314. // Culling
  14315. if (this._depthCullingState.cull !== culling || force) {
  14316. this._depthCullingState.cull = culling;
  14317. }
  14318. // Cull face
  14319. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14320. if (this._depthCullingState.cullFace !== cullFace || force) {
  14321. this._depthCullingState.cullFace = cullFace;
  14322. }
  14323. // Z offset
  14324. this.setZOffset(zOffset);
  14325. // Front face
  14326. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14327. if (this._depthCullingState.frontFace !== frontFace || force) {
  14328. this._depthCullingState.frontFace = frontFace;
  14329. }
  14330. };
  14331. /**
  14332. * Set the z offset to apply to current rendering
  14333. * @param value defines the offset to apply
  14334. */
  14335. Engine.prototype.setZOffset = function (value) {
  14336. this._depthCullingState.zOffset = value;
  14337. };
  14338. /**
  14339. * Gets the current value of the zOffset
  14340. * @returns the current zOffset state
  14341. */
  14342. Engine.prototype.getZOffset = function () {
  14343. return this._depthCullingState.zOffset;
  14344. };
  14345. /**
  14346. * Enable or disable depth buffering
  14347. * @param enable defines the state to set
  14348. */
  14349. Engine.prototype.setDepthBuffer = function (enable) {
  14350. this._depthCullingState.depthTest = enable;
  14351. };
  14352. /**
  14353. * Gets a boolean indicating if depth writing is enabled
  14354. * @returns the current depth writing state
  14355. */
  14356. Engine.prototype.getDepthWrite = function () {
  14357. return this._depthCullingState.depthMask;
  14358. };
  14359. /**
  14360. * Enable or disable depth writing
  14361. * @param enable defines the state to set
  14362. */
  14363. Engine.prototype.setDepthWrite = function (enable) {
  14364. this._depthCullingState.depthMask = enable;
  14365. };
  14366. /**
  14367. * Enable or disable color writing
  14368. * @param enable defines the state to set
  14369. */
  14370. Engine.prototype.setColorWrite = function (enable) {
  14371. this._gl.colorMask(enable, enable, enable, enable);
  14372. this._colorWrite = enable;
  14373. };
  14374. /**
  14375. * Gets a boolean indicating if color writing is enabled
  14376. * @returns the current color writing state
  14377. */
  14378. Engine.prototype.getColorWrite = function () {
  14379. return this._colorWrite;
  14380. };
  14381. /**
  14382. * Sets alpha constants used by some alpha blending modes
  14383. * @param r defines the red component
  14384. * @param g defines the green component
  14385. * @param b defines the blue component
  14386. * @param a defines the alpha component
  14387. */
  14388. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14389. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14390. };
  14391. /**
  14392. * Sets the current alpha mode
  14393. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14394. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14395. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14396. */
  14397. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14398. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14399. if (this._alphaMode === mode) {
  14400. return;
  14401. }
  14402. switch (mode) {
  14403. case Engine.ALPHA_DISABLE:
  14404. this._alphaState.alphaBlend = false;
  14405. break;
  14406. case Engine.ALPHA_PREMULTIPLIED:
  14407. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14408. this._alphaState.alphaBlend = true;
  14409. break;
  14410. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14411. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14412. this._alphaState.alphaBlend = true;
  14413. break;
  14414. case Engine.ALPHA_COMBINE:
  14415. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14416. this._alphaState.alphaBlend = true;
  14417. break;
  14418. case Engine.ALPHA_ONEONE:
  14419. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14420. this._alphaState.alphaBlend = true;
  14421. break;
  14422. case Engine.ALPHA_ADD:
  14423. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14424. this._alphaState.alphaBlend = true;
  14425. break;
  14426. case Engine.ALPHA_SUBTRACT:
  14427. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14428. this._alphaState.alphaBlend = true;
  14429. break;
  14430. case Engine.ALPHA_MULTIPLY:
  14431. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14432. this._alphaState.alphaBlend = true;
  14433. break;
  14434. case Engine.ALPHA_MAXIMIZED:
  14435. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14436. this._alphaState.alphaBlend = true;
  14437. break;
  14438. case Engine.ALPHA_INTERPOLATE:
  14439. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14440. this._alphaState.alphaBlend = true;
  14441. break;
  14442. case Engine.ALPHA_SCREENMODE:
  14443. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14444. this._alphaState.alphaBlend = true;
  14445. break;
  14446. }
  14447. if (!noDepthWriteChange) {
  14448. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14449. }
  14450. this._alphaMode = mode;
  14451. };
  14452. /**
  14453. * Gets the current alpha mode
  14454. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14455. * @returns the current alpha mode
  14456. */
  14457. Engine.prototype.getAlphaMode = function () {
  14458. return this._alphaMode;
  14459. };
  14460. // Textures
  14461. /**
  14462. * Clears the list of texture accessible through engine.
  14463. * This can help preventing texture load conflict due to name collision.
  14464. */
  14465. Engine.prototype.clearInternalTexturesCache = function () {
  14466. this._internalTexturesCache = [];
  14467. };
  14468. /**
  14469. * Force the entire cache to be cleared
  14470. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14471. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14472. */
  14473. Engine.prototype.wipeCaches = function (bruteForce) {
  14474. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14475. return;
  14476. }
  14477. this._currentEffect = null;
  14478. if (bruteForce) {
  14479. this.resetTextureCache();
  14480. this._currentProgram = null;
  14481. this._stencilState.reset();
  14482. this._depthCullingState.reset();
  14483. this.setDepthFunctionToLessOrEqual();
  14484. this._alphaState.reset();
  14485. }
  14486. this._resetVertexBufferBinding();
  14487. this._cachedIndexBuffer = null;
  14488. this._cachedEffectForVertexBuffers = null;
  14489. this._unbindVertexArrayObject();
  14490. this.bindIndexBuffer(null);
  14491. };
  14492. /**
  14493. * Set the compressed texture format to use, based on the formats you have, and the formats
  14494. * supported by the hardware / browser.
  14495. *
  14496. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14497. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14498. * to API arguments needed to compressed textures. This puts the burden on the container
  14499. * generator to house the arcane code for determining these for current & future formats.
  14500. *
  14501. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14502. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14503. *
  14504. * Note: The result of this call is not taken into account when a texture is base64.
  14505. *
  14506. * @param formatsAvailable defines the list of those format families you have created
  14507. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14508. *
  14509. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14510. * @returns The extension selected.
  14511. */
  14512. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14513. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14514. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14515. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14516. return this._textureFormatInUse = this._texturesSupported[i];
  14517. }
  14518. }
  14519. }
  14520. // actively set format to nothing, to allow this to be called more than once
  14521. // and possibly fail the 2nd time
  14522. this._textureFormatInUse = null;
  14523. return null;
  14524. };
  14525. /** @hidden */
  14526. Engine.prototype._createTexture = function () {
  14527. var texture = this._gl.createTexture();
  14528. if (!texture) {
  14529. throw new Error("Unable to create texture");
  14530. }
  14531. return texture;
  14532. };
  14533. /**
  14534. * Usually called from BABYLON.Texture.ts.
  14535. * Passed information to create a WebGLTexture
  14536. * @param urlArg defines a value which contains one of the following:
  14537. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14538. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14539. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14540. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14541. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14542. * @param scene needed for loading to the correct scene
  14543. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14544. * @param onLoad optional callback to be called upon successful completion
  14545. * @param onError optional callback to be called upon failure
  14546. * @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
  14547. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14548. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14549. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14550. */
  14551. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14552. var _this = this;
  14553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14554. if (onLoad === void 0) { onLoad = null; }
  14555. if (onError === void 0) { onError = null; }
  14556. if (buffer === void 0) { buffer = null; }
  14557. if (fallback === void 0) { fallback = null; }
  14558. if (format === void 0) { format = null; }
  14559. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14560. var fromData = url.substr(0, 5) === "data:";
  14561. var fromBlob = url.substr(0, 5) === "blob:";
  14562. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14563. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14564. // establish the file extension, if possible
  14565. var lastDot = url.lastIndexOf('.');
  14566. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14567. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14568. var isTGA = (extension.indexOf(".tga") === 0);
  14569. // determine if a ktx file should be substituted
  14570. var isKTX = false;
  14571. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14572. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14573. isKTX = true;
  14574. }
  14575. if (scene) {
  14576. scene._addPendingData(texture);
  14577. }
  14578. texture.url = url;
  14579. texture.generateMipMaps = !noMipmap;
  14580. texture.samplingMode = samplingMode;
  14581. texture.invertY = invertY;
  14582. if (!this._doNotHandleContextLost) {
  14583. // Keep a link to the buffer only if we plan to handle context lost
  14584. texture._buffer = buffer;
  14585. }
  14586. var onLoadObserver = null;
  14587. if (onLoad && !fallback) {
  14588. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14589. }
  14590. if (!fallback)
  14591. this._internalTexturesCache.push(texture);
  14592. var onerror = function (message, exception) {
  14593. if (scene) {
  14594. scene._removePendingData(texture);
  14595. }
  14596. if (onLoadObserver) {
  14597. texture.onLoadedObservable.remove(onLoadObserver);
  14598. }
  14599. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14600. if (isKTX) {
  14601. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14602. }
  14603. else if (BABYLON.Tools.UseFallbackTexture) {
  14604. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14605. }
  14606. if (onError) {
  14607. onError(message || "Unknown error", exception);
  14608. }
  14609. };
  14610. var callback = null;
  14611. // processing for non-image formats
  14612. if (isKTX || isTGA || isDDS) {
  14613. if (isKTX) {
  14614. callback = function (data) {
  14615. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14616. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14617. ktx.uploadLevels(_this._gl, !noMipmap);
  14618. return false;
  14619. }, samplingMode);
  14620. };
  14621. }
  14622. else if (isTGA) {
  14623. callback = function (arrayBuffer) {
  14624. var data = new Uint8Array(arrayBuffer);
  14625. var header = BABYLON.TGATools.GetTGAHeader(data);
  14626. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14627. BABYLON.TGATools.UploadContent(_this._gl, data);
  14628. return false;
  14629. }, samplingMode);
  14630. };
  14631. }
  14632. else if (isDDS) {
  14633. callback = function (data) {
  14634. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14635. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14636. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14637. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14638. return false;
  14639. }, samplingMode);
  14640. };
  14641. }
  14642. if (!buffer) {
  14643. this._loadFile(url, function (data) {
  14644. if (callback) {
  14645. callback(data);
  14646. }
  14647. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14648. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14649. });
  14650. }
  14651. else {
  14652. if (callback) {
  14653. callback(buffer);
  14654. }
  14655. }
  14656. // image format processing
  14657. }
  14658. else {
  14659. var onload = function (img) {
  14660. if (fromBlob && !_this._doNotHandleContextLost) {
  14661. // We need to store the image if we need to rebuild the texture
  14662. // in case of a webgl context lost
  14663. texture._buffer = img;
  14664. }
  14665. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14666. var gl = _this._gl;
  14667. var isPot = (img.width === potWidth && img.height === potHeight);
  14668. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14669. if (isPot) {
  14670. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14671. return false;
  14672. }
  14673. // Using shaders to rescale because canvas.drawImage is lossy
  14674. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14675. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14676. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14681. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14682. _this._releaseTexture(source);
  14683. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14684. continuationCallback();
  14685. });
  14686. return true;
  14687. }, samplingMode);
  14688. };
  14689. if (!fromData || isBase64) {
  14690. if (buffer instanceof HTMLImageElement) {
  14691. onload(buffer);
  14692. }
  14693. else {
  14694. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14695. }
  14696. }
  14697. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14698. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14699. }
  14700. else {
  14701. onload(buffer);
  14702. }
  14703. }
  14704. return texture;
  14705. };
  14706. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14707. var _this = this;
  14708. var rtt = this.createRenderTargetTexture({
  14709. width: destination.width,
  14710. height: destination.height,
  14711. }, {
  14712. generateMipMaps: false,
  14713. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14714. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14715. generateDepthBuffer: false,
  14716. generateStencilBuffer: false
  14717. });
  14718. if (!this._rescalePostProcess) {
  14719. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14720. }
  14721. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14722. _this._rescalePostProcess.onApply = function (effect) {
  14723. effect._bindTexture("textureSampler", source);
  14724. };
  14725. var hostingScene = scene;
  14726. if (!hostingScene) {
  14727. hostingScene = _this.scenes[_this.scenes.length - 1];
  14728. }
  14729. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14730. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14731. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14732. _this.unBindFramebuffer(rtt);
  14733. _this._releaseTexture(rtt);
  14734. if (onComplete) {
  14735. onComplete();
  14736. }
  14737. });
  14738. };
  14739. /**
  14740. * Update a raw texture
  14741. * @param texture defines the texture to update
  14742. * @param data defines the data to store in the texture
  14743. * @param format defines the format of the data
  14744. * @param invertY defines if data must be stored with Y axis inverted
  14745. * @param compression defines the compression used (null by default)
  14746. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14747. */
  14748. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14749. if (compression === void 0) { compression = null; }
  14750. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14751. if (!texture) {
  14752. return;
  14753. }
  14754. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14755. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14756. // babylon's internalFormat but gl's texImage2D format
  14757. var internalFormat = this._getInternalFormat(format);
  14758. var textureType = this._getWebGLTextureType(type);
  14759. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14760. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14761. if (!this._doNotHandleContextLost) {
  14762. texture._bufferView = data;
  14763. texture.format = format;
  14764. texture.type = type;
  14765. texture.invertY = invertY;
  14766. texture._compression = compression;
  14767. }
  14768. if (texture.width % 4 !== 0) {
  14769. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14770. }
  14771. if (compression && data) {
  14772. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14773. }
  14774. else {
  14775. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14776. }
  14777. if (texture.generateMipMaps) {
  14778. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14779. }
  14780. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14781. // this.resetTextureCache();
  14782. texture.isReady = true;
  14783. };
  14784. /**
  14785. * Creates a raw texture
  14786. * @param data defines the data to store in the texture
  14787. * @param width defines the width of the texture
  14788. * @param height defines the height of the texture
  14789. * @param format defines the format of the data
  14790. * @param generateMipMaps defines if the engine should generate the mip levels
  14791. * @param invertY defines if data must be stored with Y axis inverted
  14792. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14793. * @param compression defines the compression used (null by default)
  14794. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14795. * @returns the raw texture inside an InternalTexture
  14796. */
  14797. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14798. if (compression === void 0) { compression = null; }
  14799. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14800. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14801. texture.baseWidth = width;
  14802. texture.baseHeight = height;
  14803. texture.width = width;
  14804. texture.height = height;
  14805. texture.format = format;
  14806. texture.generateMipMaps = generateMipMaps;
  14807. texture.samplingMode = samplingMode;
  14808. texture.invertY = invertY;
  14809. texture._compression = compression;
  14810. texture.type = type;
  14811. if (!this._doNotHandleContextLost) {
  14812. texture._bufferView = data;
  14813. }
  14814. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14815. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14816. // Filters
  14817. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14818. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14819. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14820. if (generateMipMaps) {
  14821. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14822. }
  14823. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14824. this._internalTexturesCache.push(texture);
  14825. return texture;
  14826. };
  14827. /**
  14828. * Creates a dynamic texture
  14829. * @param width defines the width of the texture
  14830. * @param height defines the height of the texture
  14831. * @param generateMipMaps defines if the engine should generate the mip levels
  14832. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14833. * @returns the dynamic texture inside an InternalTexture
  14834. */
  14835. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14836. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14837. texture.baseWidth = width;
  14838. texture.baseHeight = height;
  14839. if (generateMipMaps) {
  14840. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14841. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14842. }
  14843. // this.resetTextureCache();
  14844. texture.width = width;
  14845. texture.height = height;
  14846. texture.isReady = false;
  14847. texture.generateMipMaps = generateMipMaps;
  14848. texture.samplingMode = samplingMode;
  14849. this.updateTextureSamplingMode(samplingMode, texture);
  14850. this._internalTexturesCache.push(texture);
  14851. return texture;
  14852. };
  14853. /**
  14854. * Update the sampling mode of a given texture
  14855. * @param samplingMode defines the required sampling mode
  14856. * @param texture defines the texture to update
  14857. */
  14858. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14859. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14860. if (texture.isCube) {
  14861. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14862. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14863. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14864. }
  14865. else if (texture.is3D) {
  14866. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14867. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14868. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14869. }
  14870. else {
  14871. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14872. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14873. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14874. }
  14875. texture.samplingMode = samplingMode;
  14876. };
  14877. /**
  14878. * Update the content of a dynamic texture
  14879. * @param texture defines the texture to update
  14880. * @param canvas defines the canvas containing the source
  14881. * @param invertY defines if data must be stored with Y axis inverted
  14882. * @param premulAlpha defines if alpha is stored as premultiplied
  14883. * @param format defines the format of the data
  14884. */
  14885. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14886. if (premulAlpha === void 0) { premulAlpha = false; }
  14887. if (!texture) {
  14888. return;
  14889. }
  14890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14891. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14892. if (premulAlpha) {
  14893. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14894. }
  14895. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14897. if (texture.generateMipMaps) {
  14898. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14899. }
  14900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14901. if (premulAlpha) {
  14902. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14903. }
  14904. texture.isReady = true;
  14905. };
  14906. /**
  14907. * Update a video texture
  14908. * @param texture defines the texture to update
  14909. * @param video defines the video element to use
  14910. * @param invertY defines if data must be stored with Y axis inverted
  14911. */
  14912. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14913. if (!texture || texture._isDisabled) {
  14914. return;
  14915. }
  14916. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14917. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14918. try {
  14919. // Testing video texture support
  14920. if (this._videoTextureSupported === undefined) {
  14921. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14922. if (this._gl.getError() !== 0) {
  14923. this._videoTextureSupported = false;
  14924. }
  14925. else {
  14926. this._videoTextureSupported = true;
  14927. }
  14928. }
  14929. // Copy video through the current working canvas if video texture is not supported
  14930. if (!this._videoTextureSupported) {
  14931. if (!texture._workingCanvas) {
  14932. texture._workingCanvas = document.createElement("canvas");
  14933. var context = texture._workingCanvas.getContext("2d");
  14934. if (!context) {
  14935. throw new Error("Unable to get 2d context");
  14936. }
  14937. texture._workingContext = context;
  14938. texture._workingCanvas.width = texture.width;
  14939. texture._workingCanvas.height = texture.height;
  14940. }
  14941. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14942. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14943. }
  14944. else {
  14945. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14946. }
  14947. if (texture.generateMipMaps) {
  14948. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14949. }
  14950. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14951. // this.resetTextureCache();
  14952. texture.isReady = true;
  14953. }
  14954. catch (ex) {
  14955. // Something unexpected
  14956. // Let's disable the texture
  14957. texture._isDisabled = true;
  14958. }
  14959. };
  14960. /**
  14961. * Updates a depth texture Comparison Mode and Function.
  14962. * If the comparison Function is equal to 0, the mode will be set to none.
  14963. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14964. * @param texture The texture to set the comparison function for
  14965. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14966. */
  14967. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14968. if (this.webGLVersion === 1) {
  14969. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14970. return;
  14971. }
  14972. var gl = this._gl;
  14973. if (texture.isCube) {
  14974. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14975. if (comparisonFunction === 0) {
  14976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14978. }
  14979. else {
  14980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14982. }
  14983. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14984. }
  14985. else {
  14986. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14987. if (comparisonFunction === 0) {
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14990. }
  14991. else {
  14992. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14994. }
  14995. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14996. }
  14997. texture._comparisonFunction = comparisonFunction;
  14998. };
  14999. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15000. var width = size.width || size;
  15001. var height = size.height || size;
  15002. internalTexture.baseWidth = width;
  15003. internalTexture.baseHeight = height;
  15004. internalTexture.width = width;
  15005. internalTexture.height = height;
  15006. internalTexture.isReady = true;
  15007. internalTexture.samples = 1;
  15008. internalTexture.generateMipMaps = false;
  15009. internalTexture._generateDepthBuffer = true;
  15010. internalTexture._generateStencilBuffer = generateStencil;
  15011. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15012. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15013. internalTexture._comparisonFunction = comparisonFunction;
  15014. var gl = this._gl;
  15015. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15016. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15017. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15018. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15019. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15020. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15021. if (comparisonFunction === 0) {
  15022. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15023. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15024. }
  15025. else {
  15026. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15027. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15028. }
  15029. };
  15030. /**
  15031. * Creates a depth stencil texture.
  15032. * This is only available in WebGL 2 or with the depth texture extension available.
  15033. * @param size The size of face edge in the texture.
  15034. * @param options The options defining the texture.
  15035. * @returns The texture
  15036. */
  15037. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15038. if (options.isCube) {
  15039. var width = size.width || size;
  15040. return this._createDepthStencilCubeTexture(width, options);
  15041. }
  15042. else {
  15043. return this._createDepthStencilTexture(size, options);
  15044. }
  15045. };
  15046. /**
  15047. * Creates a depth stencil texture.
  15048. * This is only available in WebGL 2 or with the depth texture extension available.
  15049. * @param size The size of face edge in the texture.
  15050. * @param options The options defining the texture.
  15051. * @returns The texture
  15052. */
  15053. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15054. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15055. if (!this._caps.depthTextureExtension) {
  15056. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15057. return internalTexture;
  15058. }
  15059. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15060. var gl = this._gl;
  15061. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15062. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15063. if (this.webGLVersion > 1) {
  15064. if (internalOptions.generateStencil) {
  15065. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15066. }
  15067. else {
  15068. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15069. }
  15070. }
  15071. else {
  15072. if (internalOptions.generateStencil) {
  15073. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15074. }
  15075. else {
  15076. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15077. }
  15078. }
  15079. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15080. return internalTexture;
  15081. };
  15082. /**
  15083. * Creates a depth stencil cube texture.
  15084. * This is only available in WebGL 2.
  15085. * @param size The size of face edge in the cube texture.
  15086. * @param options The options defining the cube texture.
  15087. * @returns The cube texture
  15088. */
  15089. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15090. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15091. internalTexture.isCube = true;
  15092. if (this.webGLVersion === 1) {
  15093. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15094. return internalTexture;
  15095. }
  15096. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15097. var gl = this._gl;
  15098. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15099. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15100. // Create the depth/stencil buffer
  15101. for (var face = 0; face < 6; face++) {
  15102. if (internalOptions.generateStencil) {
  15103. 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);
  15104. }
  15105. else {
  15106. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15107. }
  15108. }
  15109. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15110. return internalTexture;
  15111. };
  15112. /**
  15113. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15114. * @param renderTarget The render target to set the frame buffer for
  15115. */
  15116. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15117. // Create the framebuffer
  15118. var internalTexture = renderTarget.getInternalTexture();
  15119. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15120. return;
  15121. }
  15122. var gl = this._gl;
  15123. var depthStencilTexture = renderTarget.depthStencilTexture;
  15124. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15125. if (depthStencilTexture.isCube) {
  15126. if (depthStencilTexture._generateStencilBuffer) {
  15127. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15128. }
  15129. else {
  15130. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15131. }
  15132. }
  15133. else {
  15134. if (depthStencilTexture._generateStencilBuffer) {
  15135. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15136. }
  15137. else {
  15138. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15139. }
  15140. }
  15141. this.bindUnboundFramebuffer(null);
  15142. };
  15143. /**
  15144. * Creates a new render target texture
  15145. * @param size defines the size of the texture
  15146. * @param options defines the options used to create the texture
  15147. * @returns a new render target texture stored in an InternalTexture
  15148. */
  15149. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15150. var fullOptions = new RenderTargetCreationOptions();
  15151. if (options !== undefined && typeof options === "object") {
  15152. fullOptions.generateMipMaps = options.generateMipMaps;
  15153. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15154. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15155. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15156. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15157. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15158. }
  15159. else {
  15160. fullOptions.generateMipMaps = options;
  15161. fullOptions.generateDepthBuffer = true;
  15162. fullOptions.generateStencilBuffer = false;
  15163. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15164. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15165. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15166. }
  15167. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15168. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15169. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15170. }
  15171. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15172. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15173. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15174. }
  15175. var gl = this._gl;
  15176. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15177. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15178. var width = size.width || size;
  15179. var height = size.height || size;
  15180. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15181. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15182. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15183. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15184. }
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15189. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15190. // Create the framebuffer
  15191. var currentFrameBuffer = this._currentFramebuffer;
  15192. var framebuffer = gl.createFramebuffer();
  15193. this.bindUnboundFramebuffer(framebuffer);
  15194. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15195. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15196. if (fullOptions.generateMipMaps) {
  15197. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15198. }
  15199. // Unbind
  15200. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15201. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15202. this.bindUnboundFramebuffer(currentFrameBuffer);
  15203. texture._framebuffer = framebuffer;
  15204. texture.baseWidth = width;
  15205. texture.baseHeight = height;
  15206. texture.width = width;
  15207. texture.height = height;
  15208. texture.isReady = true;
  15209. texture.samples = 1;
  15210. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15211. texture.samplingMode = fullOptions.samplingMode;
  15212. texture.type = fullOptions.type;
  15213. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15214. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15215. // this.resetTextureCache();
  15216. this._internalTexturesCache.push(texture);
  15217. return texture;
  15218. };
  15219. /**
  15220. * Create a multi render target texture
  15221. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15222. * @param size defines the size of the texture
  15223. * @param options defines the creation options
  15224. * @returns the cube texture as an InternalTexture
  15225. */
  15226. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15227. var generateMipMaps = false;
  15228. var generateDepthBuffer = true;
  15229. var generateStencilBuffer = false;
  15230. var generateDepthTexture = false;
  15231. var textureCount = 1;
  15232. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15233. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15234. var types = new Array();
  15235. var samplingModes = new Array();
  15236. if (options !== undefined) {
  15237. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15238. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15239. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15240. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15241. textureCount = options.textureCount || 1;
  15242. if (options.types) {
  15243. types = options.types;
  15244. }
  15245. if (options.samplingModes) {
  15246. samplingModes = options.samplingModes;
  15247. }
  15248. }
  15249. var gl = this._gl;
  15250. // Create the framebuffer
  15251. var framebuffer = gl.createFramebuffer();
  15252. this.bindUnboundFramebuffer(framebuffer);
  15253. var width = size.width || size;
  15254. var height = size.height || size;
  15255. var textures = [];
  15256. var attachments = [];
  15257. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15258. for (var i = 0; i < textureCount; i++) {
  15259. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15260. var type = types[i] || defaultType;
  15261. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15262. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15263. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15264. }
  15265. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15266. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15267. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15268. }
  15269. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15270. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15271. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15272. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15273. }
  15274. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15275. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15276. textures.push(texture);
  15277. attachments.push(attachment);
  15278. gl.activeTexture(gl["TEXTURE" + i]);
  15279. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15284. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15285. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15286. if (generateMipMaps) {
  15287. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15288. }
  15289. // Unbind
  15290. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15291. texture._framebuffer = framebuffer;
  15292. texture._depthStencilBuffer = depthStencilBuffer;
  15293. texture.baseWidth = width;
  15294. texture.baseHeight = height;
  15295. texture.width = width;
  15296. texture.height = height;
  15297. texture.isReady = true;
  15298. texture.samples = 1;
  15299. texture.generateMipMaps = generateMipMaps;
  15300. texture.samplingMode = samplingMode;
  15301. texture.type = type;
  15302. texture._generateDepthBuffer = generateDepthBuffer;
  15303. texture._generateStencilBuffer = generateStencilBuffer;
  15304. texture._attachments = attachments;
  15305. this._internalTexturesCache.push(texture);
  15306. }
  15307. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15308. // Depth texture
  15309. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15310. gl.activeTexture(gl.TEXTURE0);
  15311. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15314. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15316. 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);
  15317. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15318. depthTexture._framebuffer = framebuffer;
  15319. depthTexture.baseWidth = width;
  15320. depthTexture.baseHeight = height;
  15321. depthTexture.width = width;
  15322. depthTexture.height = height;
  15323. depthTexture.isReady = true;
  15324. depthTexture.samples = 1;
  15325. depthTexture.generateMipMaps = generateMipMaps;
  15326. depthTexture.samplingMode = gl.NEAREST;
  15327. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15328. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15329. textures.push(depthTexture);
  15330. this._internalTexturesCache.push(depthTexture);
  15331. }
  15332. gl.drawBuffers(attachments);
  15333. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15334. this.bindUnboundFramebuffer(null);
  15335. this.resetTextureCache();
  15336. return textures;
  15337. };
  15338. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15339. if (samples === void 0) { samples = 1; }
  15340. var depthStencilBuffer = null;
  15341. var gl = this._gl;
  15342. // Create the depth/stencil buffer
  15343. if (generateStencilBuffer) {
  15344. depthStencilBuffer = gl.createRenderbuffer();
  15345. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15346. if (samples > 1) {
  15347. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15348. }
  15349. else {
  15350. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15351. }
  15352. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15353. }
  15354. else if (generateDepthBuffer) {
  15355. depthStencilBuffer = gl.createRenderbuffer();
  15356. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15357. if (samples > 1) {
  15358. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15359. }
  15360. else {
  15361. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15362. }
  15363. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15364. }
  15365. return depthStencilBuffer;
  15366. };
  15367. /**
  15368. * Updates the sample count of a render target texture
  15369. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15370. * @param texture defines the texture to update
  15371. * @param samples defines the sample count to set
  15372. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15373. */
  15374. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15375. if (this.webGLVersion < 2 || !texture) {
  15376. return 1;
  15377. }
  15378. if (texture.samples === samples) {
  15379. return samples;
  15380. }
  15381. var gl = this._gl;
  15382. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15383. // Dispose previous render buffers
  15384. if (texture._depthStencilBuffer) {
  15385. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15386. texture._depthStencilBuffer = null;
  15387. }
  15388. if (texture._MSAAFramebuffer) {
  15389. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15390. texture._MSAAFramebuffer = null;
  15391. }
  15392. if (texture._MSAARenderBuffer) {
  15393. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15394. texture._MSAARenderBuffer = null;
  15395. }
  15396. if (samples > 1) {
  15397. var framebuffer = gl.createFramebuffer();
  15398. if (!framebuffer) {
  15399. throw new Error("Unable to create multi sampled framebuffer");
  15400. }
  15401. texture._MSAAFramebuffer = framebuffer;
  15402. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15403. var colorRenderbuffer = gl.createRenderbuffer();
  15404. if (!colorRenderbuffer) {
  15405. throw new Error("Unable to create multi sampled framebuffer");
  15406. }
  15407. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15408. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15409. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15410. texture._MSAARenderBuffer = colorRenderbuffer;
  15411. }
  15412. else {
  15413. this.bindUnboundFramebuffer(texture._framebuffer);
  15414. }
  15415. texture.samples = samples;
  15416. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15417. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15418. this.bindUnboundFramebuffer(null);
  15419. return samples;
  15420. };
  15421. /**
  15422. * Update the sample count for a given multiple render target texture
  15423. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15424. * @param textures defines the textures to update
  15425. * @param samples defines the sample count to set
  15426. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15427. */
  15428. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15429. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15430. return 1;
  15431. }
  15432. if (textures[0].samples === samples) {
  15433. return samples;
  15434. }
  15435. var gl = this._gl;
  15436. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15437. // Dispose previous render buffers
  15438. if (textures[0]._depthStencilBuffer) {
  15439. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15440. textures[0]._depthStencilBuffer = null;
  15441. }
  15442. if (textures[0]._MSAAFramebuffer) {
  15443. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15444. textures[0]._MSAAFramebuffer = null;
  15445. }
  15446. for (var i = 0; i < textures.length; i++) {
  15447. if (textures[i]._MSAARenderBuffer) {
  15448. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15449. textures[i]._MSAARenderBuffer = null;
  15450. }
  15451. }
  15452. if (samples > 1) {
  15453. var framebuffer = gl.createFramebuffer();
  15454. if (!framebuffer) {
  15455. throw new Error("Unable to create multi sampled framebuffer");
  15456. }
  15457. this.bindUnboundFramebuffer(framebuffer);
  15458. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15459. var attachments = [];
  15460. for (var i = 0; i < textures.length; i++) {
  15461. var texture = textures[i];
  15462. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15463. var colorRenderbuffer = gl.createRenderbuffer();
  15464. if (!colorRenderbuffer) {
  15465. throw new Error("Unable to create multi sampled framebuffer");
  15466. }
  15467. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15468. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15469. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15470. texture._MSAAFramebuffer = framebuffer;
  15471. texture._MSAARenderBuffer = colorRenderbuffer;
  15472. texture.samples = samples;
  15473. texture._depthStencilBuffer = depthStencilBuffer;
  15474. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15475. attachments.push(attachment);
  15476. }
  15477. gl.drawBuffers(attachments);
  15478. }
  15479. else {
  15480. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15481. }
  15482. this.bindUnboundFramebuffer(null);
  15483. return samples;
  15484. };
  15485. /** @hidden */
  15486. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15487. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15488. };
  15489. /** @hidden */
  15490. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15491. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15492. };
  15493. /** @hidden */
  15494. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15495. var gl = this._gl;
  15496. var textureType = this._getWebGLTextureType(texture.type);
  15497. var format = this._getInternalFormat(texture.format);
  15498. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15499. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15500. this._bindTextureDirectly(bindTarget, texture, true);
  15501. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15502. var target = gl.TEXTURE_2D;
  15503. if (texture.isCube) {
  15504. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15505. }
  15506. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15507. this._bindTextureDirectly(bindTarget, null, true);
  15508. };
  15509. /**
  15510. * Creates a new render target cube texture
  15511. * @param size defines the size of the texture
  15512. * @param options defines the options used to create the texture
  15513. * @returns a new render target cube texture stored in an InternalTexture
  15514. */
  15515. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15516. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15517. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15518. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15519. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15520. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15521. }
  15522. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15523. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15524. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15525. }
  15526. var gl = this._gl;
  15527. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15528. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15529. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15530. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15531. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15532. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15533. }
  15534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15538. for (var face = 0; face < 6; face++) {
  15539. 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);
  15540. }
  15541. // Create the framebuffer
  15542. var framebuffer = gl.createFramebuffer();
  15543. this.bindUnboundFramebuffer(framebuffer);
  15544. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15545. // MipMaps
  15546. if (fullOptions.generateMipMaps) {
  15547. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15548. }
  15549. // Unbind
  15550. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15551. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15552. this.bindUnboundFramebuffer(null);
  15553. texture._framebuffer = framebuffer;
  15554. texture.width = size;
  15555. texture.height = size;
  15556. texture.isReady = true;
  15557. texture.isCube = true;
  15558. texture.samples = 1;
  15559. texture.generateMipMaps = fullOptions.generateMipMaps;
  15560. texture.samplingMode = fullOptions.samplingMode;
  15561. texture.type = fullOptions.type;
  15562. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15563. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15564. this._internalTexturesCache.push(texture);
  15565. return texture;
  15566. };
  15567. /**
  15568. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15569. * @param rootUrl defines the url where the file to load is located
  15570. * @param scene defines the current scene
  15571. * @param lodScale defines scale to apply to the mip map selection
  15572. * @param lodOffset defines offset to apply to the mip map selection
  15573. * @param onLoad defines an optional callback raised when the texture is loaded
  15574. * @param onError defines an optional callback raised if there is an issue to load the texture
  15575. * @param format defines the format of the data
  15576. * @param forcedExtension defines the extension to use to pick the right loader
  15577. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15578. * @returns the cube texture as an InternalTexture
  15579. */
  15580. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15581. var _this = this;
  15582. if (onLoad === void 0) { onLoad = null; }
  15583. if (onError === void 0) { onError = null; }
  15584. if (forcedExtension === void 0) { forcedExtension = null; }
  15585. if (createPolynomials === void 0) { createPolynomials = true; }
  15586. var callback = function (loadData) {
  15587. if (!loadData) {
  15588. if (onLoad) {
  15589. onLoad(null);
  15590. }
  15591. return;
  15592. }
  15593. var texture = loadData.texture;
  15594. if (!createPolynomials) {
  15595. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15596. }
  15597. else if (loadData.info.sphericalPolynomial) {
  15598. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15599. }
  15600. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15601. if (_this._caps.textureLOD) {
  15602. // Do not add extra process if texture lod is supported.
  15603. if (onLoad) {
  15604. onLoad(texture);
  15605. }
  15606. return;
  15607. }
  15608. var mipSlices = 3;
  15609. var gl = _this._gl;
  15610. var width = loadData.width;
  15611. if (!width) {
  15612. return;
  15613. }
  15614. var textures = [];
  15615. for (var i = 0; i < mipSlices; i++) {
  15616. //compute LOD from even spacing in smoothness (matching shader calculation)
  15617. var smoothness = i / (mipSlices - 1);
  15618. var roughness = 1 - smoothness;
  15619. var minLODIndex = lodOffset; // roughness = 0
  15620. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15621. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15622. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15623. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15624. glTextureFromLod.isCube = true;
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15630. if (loadData.isDDS) {
  15631. var info = loadData.info;
  15632. var data = loadData.data;
  15633. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15634. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15635. }
  15636. else {
  15637. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15638. }
  15639. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15640. // Wrap in a base texture for easy binding.
  15641. var lodTexture = new BABYLON.BaseTexture(scene);
  15642. lodTexture.isCube = true;
  15643. lodTexture._texture = glTextureFromLod;
  15644. glTextureFromLod.isReady = true;
  15645. textures.push(lodTexture);
  15646. }
  15647. texture._lodTextureHigh = textures[2];
  15648. texture._lodTextureMid = textures[1];
  15649. texture._lodTextureLow = textures[0];
  15650. if (onLoad) {
  15651. onLoad(texture);
  15652. }
  15653. };
  15654. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15655. };
  15656. /**
  15657. * Creates a cube texture
  15658. * @param rootUrl defines the url where the files to load is located
  15659. * @param scene defines the current scene
  15660. * @param files defines the list of files to load (1 per face)
  15661. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15662. * @param onLoad defines an optional callback raised when the texture is loaded
  15663. * @param onError defines an optional callback raised if there is an issue to load the texture
  15664. * @param format defines the format of the data
  15665. * @param forcedExtension defines the extension to use to pick the right loader
  15666. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15667. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15668. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15669. * @returns the cube texture as an InternalTexture
  15670. */
  15671. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15672. var _this = this;
  15673. if (onLoad === void 0) { onLoad = null; }
  15674. if (onError === void 0) { onError = null; }
  15675. if (forcedExtension === void 0) { forcedExtension = null; }
  15676. if (createPolynomials === void 0) { createPolynomials = false; }
  15677. if (lodScale === void 0) { lodScale = 0; }
  15678. if (lodOffset === void 0) { lodOffset = 0; }
  15679. var gl = this._gl;
  15680. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15681. texture.isCube = true;
  15682. texture.url = rootUrl;
  15683. texture.generateMipMaps = !noMipmap;
  15684. texture._lodGenerationScale = lodScale;
  15685. texture._lodGenerationOffset = lodOffset;
  15686. if (!this._doNotHandleContextLost) {
  15687. texture._extension = forcedExtension;
  15688. texture._files = files;
  15689. }
  15690. var isKTX = false;
  15691. var isDDS = false;
  15692. var isEnv = false;
  15693. var lastDot = rootUrl.lastIndexOf('.');
  15694. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15695. if (this._textureFormatInUse) {
  15696. extension = this._textureFormatInUse;
  15697. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15698. isKTX = true;
  15699. }
  15700. else {
  15701. isDDS = (extension === ".dds");
  15702. isEnv = (extension === ".env");
  15703. }
  15704. var onerror = function (request, exception) {
  15705. if (onError && request) {
  15706. onError(request.status + " " + request.statusText, exception);
  15707. }
  15708. };
  15709. if (isKTX) {
  15710. this._loadFile(rootUrl, function (data) {
  15711. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15712. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15713. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15714. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15715. ktx.uploadLevels(_this._gl, !noMipmap);
  15716. _this.setCubeMapTextureParams(gl, loadMipmap);
  15717. texture.width = ktx.pixelWidth;
  15718. texture.height = ktx.pixelHeight;
  15719. texture.isReady = true;
  15720. }, undefined, undefined, true, onerror);
  15721. }
  15722. else if (isEnv) {
  15723. this._loadFile(rootUrl, function (data) {
  15724. data = data;
  15725. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15726. if (info) {
  15727. texture.width = info.width;
  15728. texture.height = info.width;
  15729. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15730. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15731. texture.isReady = true;
  15732. if (onLoad) {
  15733. onLoad();
  15734. }
  15735. });
  15736. }
  15737. else if (onError) {
  15738. onError("Can not parse the environment file", null);
  15739. }
  15740. }, undefined, undefined, true, onerror);
  15741. }
  15742. else if (isDDS) {
  15743. if (files && files.length === 6) {
  15744. this._cascadeLoadFiles(scene, function (imgs) {
  15745. var info;
  15746. var loadMipmap = false;
  15747. var width = 0;
  15748. for (var index = 0; index < imgs.length; index++) {
  15749. var data = imgs[index];
  15750. info = BABYLON.DDSTools.GetDDSInfo(data);
  15751. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15752. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15753. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15754. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15755. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15756. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15757. }
  15758. texture.width = info.width;
  15759. texture.height = info.height;
  15760. texture.type = info.textureType;
  15761. width = info.width;
  15762. }
  15763. _this.setCubeMapTextureParams(gl, loadMipmap);
  15764. texture.isReady = true;
  15765. if (onLoad) {
  15766. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15767. }
  15768. }, files, onError);
  15769. }
  15770. else {
  15771. this._loadFile(rootUrl, function (data) {
  15772. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15773. if (createPolynomials) {
  15774. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15775. }
  15776. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15777. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15778. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15779. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15780. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15781. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15782. }
  15783. _this.setCubeMapTextureParams(gl, loadMipmap);
  15784. texture.width = info.width;
  15785. texture.height = info.height;
  15786. texture.isReady = true;
  15787. texture.type = info.textureType;
  15788. if (onLoad) {
  15789. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15790. }
  15791. }, undefined, undefined, true, onerror);
  15792. }
  15793. }
  15794. else {
  15795. if (!files) {
  15796. throw new Error("Cannot load cubemap because files were not defined");
  15797. }
  15798. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15799. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15800. var height = width;
  15801. _this._prepareWorkingCanvas();
  15802. if (!_this._workingCanvas || !_this._workingContext) {
  15803. return;
  15804. }
  15805. _this._workingCanvas.width = width;
  15806. _this._workingCanvas.height = height;
  15807. var faces = [
  15808. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15809. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15810. ];
  15811. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15812. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15813. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15814. for (var index = 0; index < faces.length; index++) {
  15815. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15816. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15817. }
  15818. if (!noMipmap) {
  15819. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15820. }
  15821. _this.setCubeMapTextureParams(gl, !noMipmap);
  15822. texture.width = width;
  15823. texture.height = height;
  15824. texture.isReady = true;
  15825. if (format) {
  15826. texture.format = format;
  15827. }
  15828. texture.onLoadedObservable.notifyObservers(texture);
  15829. texture.onLoadedObservable.clear();
  15830. if (onLoad) {
  15831. onLoad();
  15832. }
  15833. }, files, onError);
  15834. }
  15835. this._internalTexturesCache.push(texture);
  15836. return texture;
  15837. };
  15838. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15843. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15844. // this.resetTextureCache();
  15845. };
  15846. /**
  15847. * Update a raw cube texture
  15848. * @param texture defines the texture to udpdate
  15849. * @param data defines the data to store
  15850. * @param format defines the data format
  15851. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15852. * @param invertY defines if data must be stored with Y axis inverted
  15853. * @param compression defines the compression used (null by default)
  15854. * @param level defines which level of the texture to update
  15855. */
  15856. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15857. if (compression === void 0) { compression = null; }
  15858. if (level === void 0) { level = 0; }
  15859. texture._bufferViewArray = data;
  15860. texture.format = format;
  15861. texture.type = type;
  15862. texture.invertY = invertY;
  15863. texture._compression = compression;
  15864. var gl = this._gl;
  15865. var textureType = this._getWebGLTextureType(type);
  15866. var internalFormat = this._getInternalFormat(format);
  15867. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15868. var needConversion = false;
  15869. if (internalFormat === gl.RGB) {
  15870. internalFormat = gl.RGBA;
  15871. needConversion = true;
  15872. }
  15873. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15874. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15875. if (texture.width % 4 !== 0) {
  15876. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15877. }
  15878. // Data are known to be in +X +Y +Z -X -Y -Z
  15879. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15880. var faceData = data[faceIndex];
  15881. if (compression) {
  15882. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15883. }
  15884. else {
  15885. if (needConversion) {
  15886. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15887. }
  15888. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15889. }
  15890. }
  15891. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15892. if (isPot && texture.generateMipMaps && level === 0) {
  15893. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15894. }
  15895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15896. // this.resetTextureCache();
  15897. texture.isReady = true;
  15898. };
  15899. /**
  15900. * Creates a new raw cube texture
  15901. * @param data defines the array of data to use to create each face
  15902. * @param size defines the size of the textures
  15903. * @param format defines the format of the data
  15904. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15905. * @param generateMipMaps defines if the engine should generate the mip levels
  15906. * @param invertY defines if data must be stored with Y axis inverted
  15907. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15908. * @param compression defines the compression used (null by default)
  15909. * @returns the cube texture as an InternalTexture
  15910. */
  15911. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15912. if (compression === void 0) { compression = null; }
  15913. var gl = this._gl;
  15914. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15915. texture.isCube = true;
  15916. texture.generateMipMaps = generateMipMaps;
  15917. texture.format = format;
  15918. texture.type = type;
  15919. if (!this._doNotHandleContextLost) {
  15920. texture._bufferViewArray = data;
  15921. }
  15922. var textureType = this._getWebGLTextureType(type);
  15923. var internalFormat = this._getInternalFormat(format);
  15924. if (internalFormat === gl.RGB) {
  15925. internalFormat = gl.RGBA;
  15926. }
  15927. var width = size;
  15928. var height = width;
  15929. texture.width = width;
  15930. texture.height = height;
  15931. // Double check on POT to generate Mips.
  15932. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15933. if (!isPot) {
  15934. generateMipMaps = false;
  15935. }
  15936. // Upload data if needed. The texture won't be ready until then.
  15937. if (data) {
  15938. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15939. }
  15940. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15941. // Filters
  15942. if (data && generateMipMaps) {
  15943. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15944. }
  15945. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15947. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15948. }
  15949. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15952. }
  15953. else {
  15954. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15957. }
  15958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15960. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15961. return texture;
  15962. };
  15963. /**
  15964. * Creates a new raw cube texture from a specified url
  15965. * @param url defines the url where the data is located
  15966. * @param scene defines the current scene
  15967. * @param size defines the size of the textures
  15968. * @param format defines the format of the data
  15969. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15970. * @param noMipmap defines if the engine should avoid generating the mip levels
  15971. * @param callback defines a callback used to extract texture data from loaded data
  15972. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15973. * @param onLoad defines a callback called when texture is loaded
  15974. * @param onError defines a callback called if there is an error
  15975. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15976. * @param invertY defines if data must be stored with Y axis inverted
  15977. * @returns the cube texture as an InternalTexture
  15978. */
  15979. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15980. var _this = this;
  15981. if (onLoad === void 0) { onLoad = null; }
  15982. if (onError === void 0) { onError = null; }
  15983. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15984. if (invertY === void 0) { invertY = false; }
  15985. var gl = this._gl;
  15986. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15987. scene._addPendingData(texture);
  15988. texture.url = url;
  15989. this._internalTexturesCache.push(texture);
  15990. var onerror = function (request, exception) {
  15991. scene._removePendingData(texture);
  15992. if (onError && request) {
  15993. onError(request.status + " " + request.statusText, exception);
  15994. }
  15995. };
  15996. var internalCallback = function (data) {
  15997. var width = texture.width;
  15998. var faceDataArrays = callback(data);
  15999. if (!faceDataArrays) {
  16000. return;
  16001. }
  16002. if (mipmapGenerator) {
  16003. var textureType = _this._getWebGLTextureType(type);
  16004. var internalFormat = _this._getInternalFormat(format);
  16005. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16006. var needConversion = false;
  16007. if (internalFormat === gl.RGB) {
  16008. internalFormat = gl.RGBA;
  16009. needConversion = true;
  16010. }
  16011. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16012. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16013. var mipData = mipmapGenerator(faceDataArrays);
  16014. for (var level = 0; level < mipData.length; level++) {
  16015. var mipSize = width >> level;
  16016. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16017. var mipFaceData = mipData[level][faceIndex];
  16018. if (needConversion) {
  16019. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16020. }
  16021. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16022. }
  16023. }
  16024. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16025. }
  16026. else {
  16027. texture.generateMipMaps = !noMipmap;
  16028. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16029. }
  16030. texture.isReady = true;
  16031. // this.resetTextureCache();
  16032. scene._removePendingData(texture);
  16033. if (onLoad) {
  16034. onLoad();
  16035. }
  16036. };
  16037. this._loadFile(url, function (data) {
  16038. internalCallback(data);
  16039. }, undefined, scene.database, true, onerror);
  16040. return texture;
  16041. };
  16042. ;
  16043. /**
  16044. * Update a raw 3D texture
  16045. * @param texture defines the texture to update
  16046. * @param data defines the data to store
  16047. * @param format defines the data format
  16048. * @param invertY defines if data must be stored with Y axis inverted
  16049. * @param compression defines the used compression (can be null)
  16050. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16051. */
  16052. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16053. if (compression === void 0) { compression = null; }
  16054. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16055. var internalType = this._getWebGLTextureType(textureType);
  16056. var internalFormat = this._getInternalFormat(format);
  16057. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16058. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16059. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16060. if (!this._doNotHandleContextLost) {
  16061. texture._bufferView = data;
  16062. texture.format = format;
  16063. texture.invertY = invertY;
  16064. texture._compression = compression;
  16065. }
  16066. if (texture.width % 4 !== 0) {
  16067. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16068. }
  16069. if (compression && data) {
  16070. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16071. }
  16072. else {
  16073. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16074. }
  16075. if (texture.generateMipMaps) {
  16076. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16077. }
  16078. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16079. // this.resetTextureCache();
  16080. texture.isReady = true;
  16081. };
  16082. /**
  16083. * Creates a new raw 3D texture
  16084. * @param data defines the data used to create the texture
  16085. * @param width defines the width of the texture
  16086. * @param height defines the height of the texture
  16087. * @param depth defines the depth of the texture
  16088. * @param format defines the format of the texture
  16089. * @param generateMipMaps defines if the engine must generate mip levels
  16090. * @param invertY defines if data must be stored with Y axis inverted
  16091. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16092. * @param compression defines the compressed used (can be null)
  16093. * @param textureType defines the compressed used (can be null)
  16094. * @returns a new raw 3D texture (stored in an InternalTexture)
  16095. */
  16096. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16097. if (compression === void 0) { compression = null; }
  16098. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16099. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16100. texture.baseWidth = width;
  16101. texture.baseHeight = height;
  16102. texture.baseDepth = depth;
  16103. texture.width = width;
  16104. texture.height = height;
  16105. texture.depth = depth;
  16106. texture.format = format;
  16107. texture.type = textureType;
  16108. texture.generateMipMaps = generateMipMaps;
  16109. texture.samplingMode = samplingMode;
  16110. texture.is3D = true;
  16111. if (!this._doNotHandleContextLost) {
  16112. texture._bufferView = data;
  16113. }
  16114. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16115. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16116. // Filters
  16117. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16118. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16119. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16120. if (generateMipMaps) {
  16121. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16122. }
  16123. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16124. this._internalTexturesCache.push(texture);
  16125. return texture;
  16126. };
  16127. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16128. var gl = this._gl;
  16129. if (!gl) {
  16130. return;
  16131. }
  16132. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16135. if (!noMipmap && !isCompressed) {
  16136. gl.generateMipmap(gl.TEXTURE_2D);
  16137. }
  16138. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16139. // this.resetTextureCache();
  16140. if (scene) {
  16141. scene._removePendingData(texture);
  16142. }
  16143. texture.onLoadedObservable.notifyObservers(texture);
  16144. texture.onLoadedObservable.clear();
  16145. };
  16146. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16147. var _this = this;
  16148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16149. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16150. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16151. var gl = this._gl;
  16152. if (!gl) {
  16153. return;
  16154. }
  16155. if (!texture._webGLTexture) {
  16156. // this.resetTextureCache();
  16157. if (scene) {
  16158. scene._removePendingData(texture);
  16159. }
  16160. return;
  16161. }
  16162. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16163. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16164. texture.baseWidth = width;
  16165. texture.baseHeight = height;
  16166. texture.width = potWidth;
  16167. texture.height = potHeight;
  16168. texture.isReady = true;
  16169. if (processFunction(potWidth, potHeight, function () {
  16170. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16171. })) {
  16172. // Returning as texture needs extra async steps
  16173. return;
  16174. }
  16175. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16176. };
  16177. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16178. // Create new RGBA data container.
  16179. var rgbaData;
  16180. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16181. rgbaData = new Float32Array(width * height * 4);
  16182. }
  16183. else {
  16184. rgbaData = new Uint32Array(width * height * 4);
  16185. }
  16186. // Convert each pixel.
  16187. for (var x = 0; x < width; x++) {
  16188. for (var y = 0; y < height; y++) {
  16189. var index = (y * width + x) * 3;
  16190. var newIndex = (y * width + x) * 4;
  16191. // Map Old Value to new value.
  16192. rgbaData[newIndex + 0] = rgbData[index + 0];
  16193. rgbaData[newIndex + 1] = rgbData[index + 1];
  16194. rgbaData[newIndex + 2] = rgbData[index + 2];
  16195. // Add fully opaque alpha channel.
  16196. rgbaData[newIndex + 3] = 1;
  16197. }
  16198. }
  16199. return rgbaData;
  16200. };
  16201. /** @hidden */
  16202. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16203. var gl = this._gl;
  16204. if (texture._framebuffer) {
  16205. gl.deleteFramebuffer(texture._framebuffer);
  16206. texture._framebuffer = null;
  16207. }
  16208. if (texture._depthStencilBuffer) {
  16209. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16210. texture._depthStencilBuffer = null;
  16211. }
  16212. if (texture._MSAAFramebuffer) {
  16213. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16214. texture._MSAAFramebuffer = null;
  16215. }
  16216. if (texture._MSAARenderBuffer) {
  16217. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16218. texture._MSAARenderBuffer = null;
  16219. }
  16220. };
  16221. /** @hidden */
  16222. Engine.prototype._releaseTexture = function (texture) {
  16223. var gl = this._gl;
  16224. this._releaseFramebufferObjects(texture);
  16225. gl.deleteTexture(texture._webGLTexture);
  16226. // Unbind channels
  16227. this.unbindAllTextures();
  16228. var index = this._internalTexturesCache.indexOf(texture);
  16229. if (index !== -1) {
  16230. this._internalTexturesCache.splice(index, 1);
  16231. }
  16232. // Integrated fixed lod samplers.
  16233. if (texture._lodTextureHigh) {
  16234. texture._lodTextureHigh.dispose();
  16235. }
  16236. if (texture._lodTextureMid) {
  16237. texture._lodTextureMid.dispose();
  16238. }
  16239. if (texture._lodTextureLow) {
  16240. texture._lodTextureLow.dispose();
  16241. }
  16242. // Set output texture of post process to null if the texture has been released/disposed
  16243. this.scenes.forEach(function (scene) {
  16244. scene.postProcesses.forEach(function (postProcess) {
  16245. if (postProcess._outputTexture == texture) {
  16246. postProcess._outputTexture = null;
  16247. }
  16248. });
  16249. scene.cameras.forEach(function (camera) {
  16250. camera._postProcesses.forEach(function (postProcess) {
  16251. if (postProcess) {
  16252. if (postProcess._outputTexture == texture) {
  16253. postProcess._outputTexture = null;
  16254. }
  16255. }
  16256. });
  16257. });
  16258. });
  16259. };
  16260. Engine.prototype.setProgram = function (program) {
  16261. if (this._currentProgram !== program) {
  16262. this._gl.useProgram(program);
  16263. this._currentProgram = program;
  16264. }
  16265. };
  16266. /**
  16267. * Binds an effect to the webGL context
  16268. * @param effect defines the effect to bind
  16269. */
  16270. Engine.prototype.bindSamplers = function (effect) {
  16271. this.setProgram(effect.getProgram());
  16272. var samplers = effect.getSamplers();
  16273. for (var index = 0; index < samplers.length; index++) {
  16274. var uniform = effect.getUniform(samplers[index]);
  16275. if (uniform) {
  16276. this._boundUniforms[index] = uniform;
  16277. }
  16278. }
  16279. this._currentEffect = null;
  16280. };
  16281. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16282. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16283. return;
  16284. }
  16285. // Remove
  16286. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16287. // Bind last to it
  16288. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16289. // Bind to dummy
  16290. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16291. };
  16292. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16293. if (!internalTexture) {
  16294. return -1;
  16295. }
  16296. internalTexture._initialSlot = channel;
  16297. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16298. if (channel !== internalTexture._designatedSlot) {
  16299. this._textureCollisions.addCount(1, false);
  16300. }
  16301. }
  16302. else {
  16303. if (channel !== internalTexture._designatedSlot) {
  16304. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16305. return internalTexture._designatedSlot;
  16306. }
  16307. else {
  16308. // No slot for this texture, let's pick a new one (if we find a free slot)
  16309. if (this._nextFreeTextureSlots.length) {
  16310. return this._nextFreeTextureSlots[0];
  16311. }
  16312. // We need to recycle the oldest bound texture, sorry.
  16313. this._textureCollisions.addCount(1, false);
  16314. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16315. }
  16316. }
  16317. }
  16318. return channel;
  16319. };
  16320. Engine.prototype._linkTrackers = function (previous, next) {
  16321. previous.next = next;
  16322. next.previous = previous;
  16323. };
  16324. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16325. var currentSlot = internalTexture._designatedSlot;
  16326. if (currentSlot === -1) {
  16327. return -1;
  16328. }
  16329. internalTexture._designatedSlot = -1;
  16330. if (this.disableTextureBindingOptimization) {
  16331. return -1;
  16332. }
  16333. // Remove from bound list
  16334. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16335. // Free the slot
  16336. this._boundTexturesCache[currentSlot] = null;
  16337. this._nextFreeTextureSlots.push(currentSlot);
  16338. return currentSlot;
  16339. };
  16340. Engine.prototype._activateCurrentTexture = function () {
  16341. if (this._currentTextureChannel !== this._activeChannel) {
  16342. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16343. this._currentTextureChannel = this._activeChannel;
  16344. }
  16345. };
  16346. /** @hidden */
  16347. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16348. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16349. if (force === void 0) { force = false; }
  16350. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16351. this._activeChannel = texture._designatedSlot;
  16352. }
  16353. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16354. var isTextureForRendering = texture && texture._initialSlot > -1;
  16355. if (currentTextureBound !== texture || force) {
  16356. if (currentTextureBound) {
  16357. this._removeDesignatedSlot(currentTextureBound);
  16358. }
  16359. this._activateCurrentTexture();
  16360. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16361. this._boundTexturesCache[this._activeChannel] = texture;
  16362. if (texture) {
  16363. if (!this.disableTextureBindingOptimization) {
  16364. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16365. if (slotIndex > -1) {
  16366. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16367. }
  16368. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16369. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16370. }
  16371. texture._designatedSlot = this._activeChannel;
  16372. }
  16373. }
  16374. else if (forTextureDataUpdate) {
  16375. this._activateCurrentTexture();
  16376. }
  16377. if (isTextureForRendering && !forTextureDataUpdate) {
  16378. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16379. }
  16380. };
  16381. /** @hidden */
  16382. Engine.prototype._bindTexture = function (channel, texture) {
  16383. if (channel < 0) {
  16384. return;
  16385. }
  16386. if (texture) {
  16387. channel = this._getCorrectTextureChannel(channel, texture);
  16388. }
  16389. this._activeChannel = channel;
  16390. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16391. };
  16392. /**
  16393. * Sets a texture to the webGL context from a postprocess
  16394. * @param channel defines the channel to use
  16395. * @param postProcess defines the source postprocess
  16396. */
  16397. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16398. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16399. };
  16400. /**
  16401. * Binds the output of the passed in post process to the texture channel specified
  16402. * @param channel The channel the texture should be bound to
  16403. * @param postProcess The post process which's output should be bound
  16404. */
  16405. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16406. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16407. };
  16408. /**
  16409. * Unbind all textures from the webGL context
  16410. */
  16411. Engine.prototype.unbindAllTextures = function () {
  16412. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16413. this._activeChannel = channel;
  16414. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16415. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16416. if (this.webGLVersion > 1) {
  16417. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16418. }
  16419. }
  16420. };
  16421. /**
  16422. * Sets a texture to the according uniform.
  16423. * @param channel The texture channel
  16424. * @param uniform The uniform to set
  16425. * @param texture The texture to apply
  16426. */
  16427. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16428. if (channel < 0) {
  16429. return;
  16430. }
  16431. if (uniform) {
  16432. this._boundUniforms[channel] = uniform;
  16433. }
  16434. this._setTexture(channel, texture);
  16435. };
  16436. /**
  16437. * Sets a depth stencil texture from a render target to the according uniform.
  16438. * @param channel The texture channel
  16439. * @param uniform The uniform to set
  16440. * @param texture The render target texture containing the depth stencil texture to apply
  16441. */
  16442. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16443. if (channel < 0) {
  16444. return;
  16445. }
  16446. if (uniform) {
  16447. this._boundUniforms[channel] = uniform;
  16448. }
  16449. if (!texture || !texture.depthStencilTexture) {
  16450. this._setTexture(channel, null);
  16451. }
  16452. else {
  16453. this._setTexture(channel, texture, false, true);
  16454. }
  16455. };
  16456. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16457. var uniform = this._boundUniforms[sourceSlot];
  16458. if (uniform._currentState === destination) {
  16459. return;
  16460. }
  16461. this._gl.uniform1i(uniform, destination);
  16462. uniform._currentState = destination;
  16463. };
  16464. Engine.prototype._getTextureWrapMode = function (mode) {
  16465. switch (mode) {
  16466. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16467. return this._gl.REPEAT;
  16468. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16469. return this._gl.CLAMP_TO_EDGE;
  16470. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16471. return this._gl.MIRRORED_REPEAT;
  16472. }
  16473. return this._gl.REPEAT;
  16474. };
  16475. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16476. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16477. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16478. // Not ready?
  16479. if (!texture) {
  16480. if (this._boundTexturesCache[channel] != null) {
  16481. this._activeChannel = channel;
  16482. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16483. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16484. if (this.webGLVersion > 1) {
  16485. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16486. }
  16487. }
  16488. return false;
  16489. }
  16490. // Video
  16491. if (texture.video) {
  16492. this._activeChannel = channel;
  16493. texture.update();
  16494. }
  16495. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16496. texture.delayLoad();
  16497. return false;
  16498. }
  16499. var internalTexture;
  16500. if (depthStencilTexture) {
  16501. internalTexture = texture.depthStencilTexture;
  16502. }
  16503. else if (texture.isReady()) {
  16504. internalTexture = texture.getInternalTexture();
  16505. }
  16506. else if (texture.isCube) {
  16507. internalTexture = this.emptyCubeTexture;
  16508. }
  16509. else if (texture.is3D) {
  16510. internalTexture = this.emptyTexture3D;
  16511. }
  16512. else {
  16513. internalTexture = this.emptyTexture;
  16514. }
  16515. if (!isPartOfTextureArray) {
  16516. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16517. }
  16518. var needToBind = true;
  16519. if (this._boundTexturesCache[channel] === internalTexture) {
  16520. this._moveBoundTextureOnTop(internalTexture);
  16521. if (!isPartOfTextureArray) {
  16522. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16523. }
  16524. needToBind = false;
  16525. }
  16526. this._activeChannel = channel;
  16527. if (internalTexture && internalTexture.is3D) {
  16528. if (needToBind) {
  16529. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16530. }
  16531. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16532. internalTexture._cachedWrapU = texture.wrapU;
  16533. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16534. }
  16535. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16536. internalTexture._cachedWrapV = texture.wrapV;
  16537. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16538. }
  16539. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16540. internalTexture._cachedWrapR = texture.wrapR;
  16541. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16542. }
  16543. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16544. }
  16545. else if (internalTexture && internalTexture.isCube) {
  16546. if (needToBind) {
  16547. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16548. }
  16549. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16550. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16551. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16552. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16553. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16554. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16555. }
  16556. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16557. }
  16558. else {
  16559. if (needToBind) {
  16560. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16561. }
  16562. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16563. internalTexture._cachedWrapU = texture.wrapU;
  16564. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16565. }
  16566. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16567. internalTexture._cachedWrapV = texture.wrapV;
  16568. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16569. }
  16570. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16571. }
  16572. return true;
  16573. };
  16574. /**
  16575. * Sets an array of texture to the webGL context
  16576. * @param channel defines the channel where the texture array must be set
  16577. * @param uniform defines the associated uniform location
  16578. * @param textures defines the array of textures to bind
  16579. */
  16580. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16581. if (channel < 0 || !uniform) {
  16582. return;
  16583. }
  16584. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16585. this._textureUnits = new Int32Array(textures.length);
  16586. }
  16587. for (var i = 0; i < textures.length; i++) {
  16588. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16589. }
  16590. this._gl.uniform1iv(uniform, this._textureUnits);
  16591. for (var index = 0; index < textures.length; index++) {
  16592. this._setTexture(this._textureUnits[index], textures[index], true);
  16593. }
  16594. };
  16595. /** @hidden */
  16596. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16597. var internalTexture = texture.getInternalTexture();
  16598. if (!internalTexture) {
  16599. return;
  16600. }
  16601. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16602. var value = texture.anisotropicFilteringLevel;
  16603. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16604. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16605. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16606. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16607. }
  16608. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16609. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16610. internalTexture._cachedAnisotropicFilteringLevel = value;
  16611. }
  16612. };
  16613. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16614. this._bindTextureDirectly(target, texture, true, true);
  16615. this._gl.texParameterf(target, parameter, value);
  16616. };
  16617. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16618. if (texture) {
  16619. this._bindTextureDirectly(target, texture, true, true);
  16620. }
  16621. this._gl.texParameteri(target, parameter, value);
  16622. };
  16623. /**
  16624. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16625. * @param x defines the x coordinate of the rectangle where pixels must be read
  16626. * @param y defines the y coordinate of the rectangle where pixels must be read
  16627. * @param width defines the width of the rectangle where pixels must be read
  16628. * @param height defines the height of the rectangle where pixels must be read
  16629. * @returns a Uint8Array containing RGBA colors
  16630. */
  16631. Engine.prototype.readPixels = function (x, y, width, height) {
  16632. var data = new Uint8Array(height * width * 4);
  16633. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16634. return data;
  16635. };
  16636. /**
  16637. * Add an externaly attached data from its key.
  16638. * This method call will fail and return false, if such key already exists.
  16639. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16640. * @param key the unique key that identifies the data
  16641. * @param data the data object to associate to the key for this Engine instance
  16642. * @return true if no such key were already present and the data was added successfully, false otherwise
  16643. */
  16644. Engine.prototype.addExternalData = function (key, data) {
  16645. if (!this._externalData) {
  16646. this._externalData = new BABYLON.StringDictionary();
  16647. }
  16648. return this._externalData.add(key, data);
  16649. };
  16650. /**
  16651. * Get an externaly attached data from its key
  16652. * @param key the unique key that identifies the data
  16653. * @return the associated data, if present (can be null), or undefined if not present
  16654. */
  16655. Engine.prototype.getExternalData = function (key) {
  16656. if (!this._externalData) {
  16657. this._externalData = new BABYLON.StringDictionary();
  16658. }
  16659. return this._externalData.get(key);
  16660. };
  16661. /**
  16662. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16663. * @param key the unique key that identifies the data
  16664. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16665. * @return the associated data, can be null if the factory returned null.
  16666. */
  16667. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16668. if (!this._externalData) {
  16669. this._externalData = new BABYLON.StringDictionary();
  16670. }
  16671. return this._externalData.getOrAddWithFactory(key, factory);
  16672. };
  16673. /**
  16674. * Remove an externaly attached data from the Engine instance
  16675. * @param key the unique key that identifies the data
  16676. * @return true if the data was successfully removed, false if it doesn't exist
  16677. */
  16678. Engine.prototype.removeExternalData = function (key) {
  16679. if (!this._externalData) {
  16680. this._externalData = new BABYLON.StringDictionary();
  16681. }
  16682. return this._externalData.remove(key);
  16683. };
  16684. /**
  16685. * Unbind all vertex attributes from the webGL context
  16686. */
  16687. Engine.prototype.unbindAllAttributes = function () {
  16688. if (this._mustWipeVertexAttributes) {
  16689. this._mustWipeVertexAttributes = false;
  16690. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16691. this._gl.disableVertexAttribArray(i);
  16692. this._vertexAttribArraysEnabled[i] = false;
  16693. this._currentBufferPointers[i].active = false;
  16694. }
  16695. return;
  16696. }
  16697. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16698. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16699. continue;
  16700. }
  16701. this._gl.disableVertexAttribArray(i);
  16702. this._vertexAttribArraysEnabled[i] = false;
  16703. this._currentBufferPointers[i].active = false;
  16704. }
  16705. };
  16706. /**
  16707. * 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
  16708. */
  16709. Engine.prototype.releaseEffects = function () {
  16710. for (var name in this._compiledEffects) {
  16711. this._deleteProgram(this._compiledEffects[name]._program);
  16712. }
  16713. this._compiledEffects = {};
  16714. };
  16715. /**
  16716. * Dispose and release all associated resources
  16717. */
  16718. Engine.prototype.dispose = function () {
  16719. this.hideLoadingUI();
  16720. this.stopRenderLoop();
  16721. // Release postProcesses
  16722. while (this.postProcesses.length) {
  16723. this.postProcesses[0].dispose();
  16724. }
  16725. // Empty texture
  16726. if (this._emptyTexture) {
  16727. this._releaseTexture(this._emptyTexture);
  16728. this._emptyTexture = null;
  16729. }
  16730. if (this._emptyCubeTexture) {
  16731. this._releaseTexture(this._emptyCubeTexture);
  16732. this._emptyCubeTexture = null;
  16733. }
  16734. // Rescale PP
  16735. if (this._rescalePostProcess) {
  16736. this._rescalePostProcess.dispose();
  16737. }
  16738. // Release scenes
  16739. while (this.scenes.length) {
  16740. this.scenes[0].dispose();
  16741. }
  16742. // Release audio engine
  16743. if (Engine.audioEngine) {
  16744. Engine.audioEngine.dispose();
  16745. }
  16746. // Release effects
  16747. this.releaseEffects();
  16748. // Unbind
  16749. this.unbindAllAttributes();
  16750. this._boundUniforms = [];
  16751. if (this._dummyFramebuffer) {
  16752. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16753. }
  16754. //WebVR
  16755. this.disableVR();
  16756. // Events
  16757. if (BABYLON.Tools.IsWindowObjectExist()) {
  16758. window.removeEventListener("blur", this._onBlur);
  16759. window.removeEventListener("focus", this._onFocus);
  16760. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16761. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16762. if (this._renderingCanvas) {
  16763. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16764. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16765. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16766. if (!this._doNotHandleContextLost) {
  16767. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16768. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16769. }
  16770. }
  16771. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16772. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16773. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16774. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16775. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16776. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16777. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16778. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16779. if (this._onVrDisplayConnect) {
  16780. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16781. if (this._onVrDisplayDisconnect) {
  16782. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16783. }
  16784. if (this._onVrDisplayPresentChange) {
  16785. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16786. }
  16787. this._onVrDisplayConnect = null;
  16788. this._onVrDisplayDisconnect = null;
  16789. }
  16790. }
  16791. // Remove from Instances
  16792. var index = Engine.Instances.indexOf(this);
  16793. if (index >= 0) {
  16794. Engine.Instances.splice(index, 1);
  16795. }
  16796. this._workingCanvas = null;
  16797. this._workingContext = null;
  16798. this._currentBufferPointers = [];
  16799. this._renderingCanvas = null;
  16800. this._currentProgram = null;
  16801. this._bindedRenderFunction = null;
  16802. this.onResizeObservable.clear();
  16803. this.onCanvasBlurObservable.clear();
  16804. this.onCanvasFocusObservable.clear();
  16805. this.onCanvasPointerOutObservable.clear();
  16806. this.onBeginFrameObservable.clear();
  16807. this.onEndFrameObservable.clear();
  16808. BABYLON.Effect.ResetCache();
  16809. // Abort active requests
  16810. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16811. var request = _a[_i];
  16812. request.abort();
  16813. }
  16814. };
  16815. // Loading screen
  16816. /**
  16817. * Display the loading screen
  16818. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16819. */
  16820. Engine.prototype.displayLoadingUI = function () {
  16821. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16822. return;
  16823. }
  16824. var loadingScreen = this.loadingScreen;
  16825. if (loadingScreen) {
  16826. loadingScreen.displayLoadingUI();
  16827. }
  16828. };
  16829. /**
  16830. * Hide the loading screen
  16831. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16832. */
  16833. Engine.prototype.hideLoadingUI = function () {
  16834. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16835. return;
  16836. }
  16837. var loadingScreen = this.loadingScreen;
  16838. if (loadingScreen) {
  16839. loadingScreen.hideLoadingUI();
  16840. }
  16841. };
  16842. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16843. /**
  16844. * Gets the current loading screen object
  16845. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16846. */
  16847. get: function () {
  16848. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16849. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16850. return this._loadingScreen;
  16851. },
  16852. /**
  16853. * Sets the current loading screen object
  16854. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16855. */
  16856. set: function (loadingScreen) {
  16857. this._loadingScreen = loadingScreen;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16863. /**
  16864. * Sets the current loading screen text
  16865. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16866. */
  16867. set: function (text) {
  16868. this.loadingScreen.loadingUIText = text;
  16869. },
  16870. enumerable: true,
  16871. configurable: true
  16872. });
  16873. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16874. /**
  16875. * Sets the current loading screen background color
  16876. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16877. */
  16878. set: function (color) {
  16879. this.loadingScreen.loadingUIBackgroundColor = color;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. /**
  16885. * Attach a new callback raised when context lost event is fired
  16886. * @param callback defines the callback to call
  16887. */
  16888. Engine.prototype.attachContextLostEvent = function (callback) {
  16889. if (this._renderingCanvas) {
  16890. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16891. }
  16892. };
  16893. /**
  16894. * Attach a new callback raised when context restored event is fired
  16895. * @param callback defines the callback to call
  16896. */
  16897. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16898. if (this._renderingCanvas) {
  16899. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16900. }
  16901. };
  16902. /**
  16903. * Gets the source code of the vertex shader associated with a specific webGL program
  16904. * @param program defines the program to use
  16905. * @returns a string containing the source code of the vertex shader associated with the program
  16906. */
  16907. Engine.prototype.getVertexShaderSource = function (program) {
  16908. var shaders = this._gl.getAttachedShaders(program);
  16909. if (!shaders) {
  16910. return null;
  16911. }
  16912. return this._gl.getShaderSource(shaders[0]);
  16913. };
  16914. /**
  16915. * Gets the source code of the fragment shader associated with a specific webGL program
  16916. * @param program defines the program to use
  16917. * @returns a string containing the source code of the fragment shader associated with the program
  16918. */
  16919. Engine.prototype.getFragmentShaderSource = function (program) {
  16920. var shaders = this._gl.getAttachedShaders(program);
  16921. if (!shaders) {
  16922. return null;
  16923. }
  16924. return this._gl.getShaderSource(shaders[1]);
  16925. };
  16926. /**
  16927. * Get the current error code of the webGL context
  16928. * @returns the error code
  16929. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16930. */
  16931. Engine.prototype.getError = function () {
  16932. return this._gl.getError();
  16933. };
  16934. // FPS
  16935. /**
  16936. * Gets the current framerate
  16937. * @returns a number representing the framerate
  16938. */
  16939. Engine.prototype.getFps = function () {
  16940. return this._fps;
  16941. };
  16942. /**
  16943. * Gets the time spent between current and previous frame
  16944. * @returns a number representing the delta time in ms
  16945. */
  16946. Engine.prototype.getDeltaTime = function () {
  16947. return this._deltaTime;
  16948. };
  16949. Engine.prototype._measureFps = function () {
  16950. this._performanceMonitor.sampleFrame();
  16951. this._fps = this._performanceMonitor.averageFPS;
  16952. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16953. };
  16954. /** @hidden */
  16955. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16956. if (faceIndex === void 0) { faceIndex = -1; }
  16957. if (level === void 0) { level = 0; }
  16958. var gl = this._gl;
  16959. if (!this._dummyFramebuffer) {
  16960. var dummy = gl.createFramebuffer();
  16961. if (!dummy) {
  16962. throw new Error("Unable to create dummy framebuffer");
  16963. }
  16964. this._dummyFramebuffer = dummy;
  16965. }
  16966. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16967. if (faceIndex > -1) {
  16968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16969. }
  16970. else {
  16971. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16972. }
  16973. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16974. var buffer;
  16975. switch (readType) {
  16976. case gl.UNSIGNED_BYTE:
  16977. buffer = new Uint8Array(4 * width * height);
  16978. readType = gl.UNSIGNED_BYTE;
  16979. break;
  16980. default:
  16981. buffer = new Float32Array(4 * width * height);
  16982. readType = gl.FLOAT;
  16983. break;
  16984. }
  16985. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16986. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16987. return buffer;
  16988. };
  16989. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16990. if (this._webGLVersion > 1) {
  16991. return this._caps.colorBufferFloat;
  16992. }
  16993. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16994. };
  16995. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16996. if (this._webGLVersion > 1) {
  16997. return this._caps.colorBufferFloat;
  16998. }
  16999. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17000. };
  17001. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17002. Engine.prototype._canRenderToFramebuffer = function (type) {
  17003. var gl = this._gl;
  17004. //clear existing errors
  17005. while (gl.getError() !== gl.NO_ERROR) { }
  17006. var successful = true;
  17007. var texture = gl.createTexture();
  17008. gl.bindTexture(gl.TEXTURE_2D, texture);
  17009. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17012. var fb = gl.createFramebuffer();
  17013. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17014. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17015. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17016. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17017. successful = successful && (gl.getError() === gl.NO_ERROR);
  17018. //try render by clearing frame buffer's color buffer
  17019. if (successful) {
  17020. gl.clear(gl.COLOR_BUFFER_BIT);
  17021. successful = successful && (gl.getError() === gl.NO_ERROR);
  17022. }
  17023. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17024. if (successful) {
  17025. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17026. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17027. var readFormat = gl.RGBA;
  17028. var readType = gl.UNSIGNED_BYTE;
  17029. var buffer = new Uint8Array(4);
  17030. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17031. successful = successful && (gl.getError() === gl.NO_ERROR);
  17032. }
  17033. //clean up
  17034. gl.deleteTexture(texture);
  17035. gl.deleteFramebuffer(fb);
  17036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17037. //clear accumulated errors
  17038. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17039. return successful;
  17040. };
  17041. /** @hidden */
  17042. Engine.prototype._getWebGLTextureType = function (type) {
  17043. if (type === Engine.TEXTURETYPE_FLOAT) {
  17044. return this._gl.FLOAT;
  17045. }
  17046. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17047. // Add Half Float Constant.
  17048. return this._gl.HALF_FLOAT_OES;
  17049. }
  17050. return this._gl.UNSIGNED_BYTE;
  17051. };
  17052. ;
  17053. Engine.prototype._getInternalFormat = function (format) {
  17054. var internalFormat = this._gl.RGBA;
  17055. switch (format) {
  17056. case Engine.TEXTUREFORMAT_ALPHA:
  17057. internalFormat = this._gl.ALPHA;
  17058. break;
  17059. case Engine.TEXTUREFORMAT_LUMINANCE:
  17060. internalFormat = this._gl.LUMINANCE;
  17061. break;
  17062. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17063. internalFormat = this._gl.LUMINANCE_ALPHA;
  17064. break;
  17065. case Engine.TEXTUREFORMAT_RGB:
  17066. internalFormat = this._gl.RGB;
  17067. break;
  17068. case Engine.TEXTUREFORMAT_RGBA:
  17069. internalFormat = this._gl.RGBA;
  17070. break;
  17071. case Engine.TEXTUREFORMAT_R:
  17072. internalFormat = this._gl.RED;
  17073. break;
  17074. case Engine.TEXTUREFORMAT_RG:
  17075. internalFormat = this._gl.RG;
  17076. break;
  17077. }
  17078. return internalFormat;
  17079. };
  17080. /** @hidden */
  17081. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17082. if (this._webGLVersion === 1) {
  17083. if (format !== undefined) {
  17084. switch (format) {
  17085. case Engine.TEXTUREFORMAT_LUMINANCE:
  17086. return this._gl.LUMINANCE;
  17087. case Engine.TEXTUREFORMAT_ALPHA:
  17088. return this._gl.ALPHA;
  17089. }
  17090. }
  17091. return this._gl.RGBA;
  17092. }
  17093. if (type === Engine.TEXTURETYPE_FLOAT) {
  17094. if (format !== undefined) {
  17095. switch (format) {
  17096. case Engine.TEXTUREFORMAT_R:
  17097. return this._gl.R32F;
  17098. case Engine.TEXTUREFORMAT_RG:
  17099. return this._gl.RG32F;
  17100. case Engine.TEXTUREFORMAT_RGB:
  17101. return this._gl.RGB32F;
  17102. }
  17103. }
  17104. return this._gl.RGBA32F;
  17105. }
  17106. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17107. if (format) {
  17108. switch (format) {
  17109. case Engine.TEXTUREFORMAT_R:
  17110. return this._gl.R16F;
  17111. case Engine.TEXTUREFORMAT_RG:
  17112. return this._gl.RG16F;
  17113. case Engine.TEXTUREFORMAT_RGB:
  17114. return this._gl.RGB16F;
  17115. }
  17116. }
  17117. return this._gl.RGBA16F;
  17118. }
  17119. if (format !== undefined) {
  17120. switch (format) {
  17121. case Engine.TEXTUREFORMAT_LUMINANCE:
  17122. return this._gl.LUMINANCE;
  17123. case Engine.TEXTUREFORMAT_RGB:
  17124. return this._gl.RGB;
  17125. case Engine.TEXTUREFORMAT_R:
  17126. return this._gl.R8;
  17127. case Engine.TEXTUREFORMAT_RG:
  17128. return this._gl.RG8;
  17129. case Engine.TEXTUREFORMAT_ALPHA:
  17130. return this._gl.ALPHA;
  17131. }
  17132. }
  17133. return this._gl.RGBA;
  17134. };
  17135. ;
  17136. /** @hidden */
  17137. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17138. if (type === Engine.TEXTURETYPE_FLOAT) {
  17139. return this._gl.RGBA32F;
  17140. }
  17141. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17142. return this._gl.RGBA16F;
  17143. }
  17144. return this._gl.RGBA8;
  17145. };
  17146. ;
  17147. /**
  17148. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17149. * @return the new query
  17150. */
  17151. Engine.prototype.createQuery = function () {
  17152. return this._gl.createQuery();
  17153. };
  17154. /**
  17155. * Delete and release a webGL query
  17156. * @param query defines the query to delete
  17157. * @return the current engine
  17158. */
  17159. Engine.prototype.deleteQuery = function (query) {
  17160. this._gl.deleteQuery(query);
  17161. return this;
  17162. };
  17163. /**
  17164. * Check if a given query has resolved and got its value
  17165. * @param query defines the query to check
  17166. * @returns true if the query got its value
  17167. */
  17168. Engine.prototype.isQueryResultAvailable = function (query) {
  17169. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17170. };
  17171. /**
  17172. * Gets the value of a given query
  17173. * @param query defines the query to check
  17174. * @returns the value of the query
  17175. */
  17176. Engine.prototype.getQueryResult = function (query) {
  17177. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17178. };
  17179. /**
  17180. * Initiates an occlusion query
  17181. * @param algorithmType defines the algorithm to use
  17182. * @param query defines the query to use
  17183. * @returns the current engine
  17184. * @see http://doc.babylonjs.com/features/occlusionquery
  17185. */
  17186. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17187. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17188. this._gl.beginQuery(glAlgorithm, query);
  17189. return this;
  17190. };
  17191. /**
  17192. * Ends an occlusion query
  17193. * @see http://doc.babylonjs.com/features/occlusionquery
  17194. * @param algorithmType defines the algorithm to use
  17195. * @returns the current engine
  17196. */
  17197. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17198. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17199. this._gl.endQuery(glAlgorithm);
  17200. return this;
  17201. };
  17202. /* Time queries */
  17203. Engine.prototype._createTimeQuery = function () {
  17204. var timerQuery = this._caps.timerQuery;
  17205. if (timerQuery.createQueryEXT) {
  17206. return timerQuery.createQueryEXT();
  17207. }
  17208. return this.createQuery();
  17209. };
  17210. Engine.prototype._deleteTimeQuery = function (query) {
  17211. var timerQuery = this._caps.timerQuery;
  17212. if (timerQuery.deleteQueryEXT) {
  17213. timerQuery.deleteQueryEXT(query);
  17214. return;
  17215. }
  17216. this.deleteQuery(query);
  17217. };
  17218. Engine.prototype._getTimeQueryResult = function (query) {
  17219. var timerQuery = this._caps.timerQuery;
  17220. if (timerQuery.getQueryObjectEXT) {
  17221. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17222. }
  17223. return this.getQueryResult(query);
  17224. };
  17225. Engine.prototype._getTimeQueryAvailability = function (query) {
  17226. var timerQuery = this._caps.timerQuery;
  17227. if (timerQuery.getQueryObjectEXT) {
  17228. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17229. }
  17230. return this.isQueryResultAvailable(query);
  17231. };
  17232. /**
  17233. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17234. * Please note that only one query can be issued at a time
  17235. * @returns a time token used to track the time span
  17236. */
  17237. Engine.prototype.startTimeQuery = function () {
  17238. var timerQuery = this._caps.timerQuery;
  17239. if (!timerQuery) {
  17240. return null;
  17241. }
  17242. var token = new BABYLON._TimeToken();
  17243. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17244. if (this._caps.canUseTimestampForTimerQuery) {
  17245. token._startTimeQuery = this._createTimeQuery();
  17246. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17247. }
  17248. else {
  17249. if (this._currentNonTimestampToken) {
  17250. return this._currentNonTimestampToken;
  17251. }
  17252. token._timeElapsedQuery = this._createTimeQuery();
  17253. if (timerQuery.beginQueryEXT) {
  17254. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17255. }
  17256. else {
  17257. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17258. }
  17259. this._currentNonTimestampToken = token;
  17260. }
  17261. return token;
  17262. };
  17263. /**
  17264. * Ends a time query
  17265. * @param token defines the token used to measure the time span
  17266. * @returns the time spent (in ns)
  17267. */
  17268. Engine.prototype.endTimeQuery = function (token) {
  17269. var timerQuery = this._caps.timerQuery;
  17270. if (!timerQuery || !token) {
  17271. return -1;
  17272. }
  17273. if (this._caps.canUseTimestampForTimerQuery) {
  17274. if (!token._startTimeQuery) {
  17275. return -1;
  17276. }
  17277. if (!token._endTimeQuery) {
  17278. token._endTimeQuery = this._createTimeQuery();
  17279. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17280. }
  17281. }
  17282. else if (!token._timeElapsedQueryEnded) {
  17283. if (!token._timeElapsedQuery) {
  17284. return -1;
  17285. }
  17286. if (timerQuery.endQueryEXT) {
  17287. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17288. }
  17289. else {
  17290. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17291. }
  17292. token._timeElapsedQueryEnded = true;
  17293. }
  17294. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17295. var available = false;
  17296. if (token._endTimeQuery) {
  17297. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17298. }
  17299. else if (token._timeElapsedQuery) {
  17300. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17301. }
  17302. if (available && !disjoint) {
  17303. var result = 0;
  17304. if (this._caps.canUseTimestampForTimerQuery) {
  17305. if (!token._startTimeQuery || !token._endTimeQuery) {
  17306. return -1;
  17307. }
  17308. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17309. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17310. result = timeEnd - timeStart;
  17311. this._deleteTimeQuery(token._startTimeQuery);
  17312. this._deleteTimeQuery(token._endTimeQuery);
  17313. token._startTimeQuery = null;
  17314. token._endTimeQuery = null;
  17315. }
  17316. else {
  17317. if (!token._timeElapsedQuery) {
  17318. return -1;
  17319. }
  17320. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17321. this._deleteTimeQuery(token._timeElapsedQuery);
  17322. token._timeElapsedQuery = null;
  17323. token._timeElapsedQueryEnded = false;
  17324. this._currentNonTimestampToken = null;
  17325. }
  17326. return result;
  17327. }
  17328. return -1;
  17329. };
  17330. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17331. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17332. };
  17333. // Transform feedback
  17334. /**
  17335. * Creates a webGL transform feedback object
  17336. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17337. * @returns the webGL transform feedback object
  17338. */
  17339. Engine.prototype.createTransformFeedback = function () {
  17340. return this._gl.createTransformFeedback();
  17341. };
  17342. /**
  17343. * Delete a webGL transform feedback object
  17344. * @param value defines the webGL transform feedback object to delete
  17345. */
  17346. Engine.prototype.deleteTransformFeedback = function (value) {
  17347. this._gl.deleteTransformFeedback(value);
  17348. };
  17349. /**
  17350. * Bind a webGL transform feedback object to the webgl context
  17351. * @param value defines the webGL transform feedback object to bind
  17352. */
  17353. Engine.prototype.bindTransformFeedback = function (value) {
  17354. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17355. };
  17356. /**
  17357. * Begins a transform feedback operation
  17358. * @param usePoints defines if points or triangles must be used
  17359. */
  17360. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17361. if (usePoints === void 0) { usePoints = true; }
  17362. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17363. };
  17364. /**
  17365. * Ends a transform feedback operation
  17366. */
  17367. Engine.prototype.endTransformFeedback = function () {
  17368. this._gl.endTransformFeedback();
  17369. };
  17370. /**
  17371. * Specify the varyings to use with transform feedback
  17372. * @param program defines the associated webGL program
  17373. * @param value defines the list of strings representing the varying names
  17374. */
  17375. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17376. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17377. };
  17378. /**
  17379. * Bind a webGL buffer for a transform feedback operation
  17380. * @param value defines the webGL buffer to bind
  17381. */
  17382. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17383. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17384. };
  17385. /** @hidden */
  17386. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17387. var _this = this;
  17388. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17389. this._activeRequests.push(request);
  17390. request.onCompleteObservable.add(function (request) {
  17391. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17392. });
  17393. return request;
  17394. };
  17395. /** @hidden */
  17396. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17397. var _this = this;
  17398. return new Promise(function (resolve, reject) {
  17399. _this._loadFile(url, function (data) {
  17400. resolve(data);
  17401. }, undefined, database, useArrayBuffer, function (request, exception) {
  17402. reject(exception);
  17403. });
  17404. });
  17405. };
  17406. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17407. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17408. var onload = function (data) {
  17409. loadedFiles[index] = data;
  17410. loadedFiles._internalCount++;
  17411. if (loadedFiles._internalCount === 6) {
  17412. onfinish(loadedFiles);
  17413. }
  17414. };
  17415. var onerror = function (request, exception) {
  17416. if (onErrorCallBack && request) {
  17417. onErrorCallBack(request.status + " " + request.statusText, exception);
  17418. }
  17419. };
  17420. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17421. };
  17422. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17423. if (onError === void 0) { onError = null; }
  17424. var loadedFiles = [];
  17425. loadedFiles._internalCount = 0;
  17426. for (var index = 0; index < 6; index++) {
  17427. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17428. }
  17429. };
  17430. // Statics
  17431. /**
  17432. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17433. * @returns true if the engine can be created
  17434. * @ignorenaming
  17435. */
  17436. Engine.isSupported = function () {
  17437. try {
  17438. var tempcanvas = document.createElement("canvas");
  17439. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17440. return gl != null && !!window.WebGLRenderingContext;
  17441. }
  17442. catch (e) {
  17443. return false;
  17444. }
  17445. };
  17446. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17447. Engine.ExceptionList = [
  17448. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17449. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17450. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17451. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17452. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17453. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17454. ];
  17455. /** Gets the list of created engines */
  17456. Engine.Instances = new Array();
  17457. // Const statics
  17458. Engine._ALPHA_DISABLE = 0;
  17459. Engine._ALPHA_ADD = 1;
  17460. Engine._ALPHA_COMBINE = 2;
  17461. Engine._ALPHA_SUBTRACT = 3;
  17462. Engine._ALPHA_MULTIPLY = 4;
  17463. Engine._ALPHA_MAXIMIZED = 5;
  17464. Engine._ALPHA_ONEONE = 6;
  17465. Engine._ALPHA_PREMULTIPLIED = 7;
  17466. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17467. Engine._ALPHA_INTERPOLATE = 9;
  17468. Engine._ALPHA_SCREENMODE = 10;
  17469. Engine._DELAYLOADSTATE_NONE = 0;
  17470. Engine._DELAYLOADSTATE_LOADED = 1;
  17471. Engine._DELAYLOADSTATE_LOADING = 2;
  17472. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17473. Engine._TEXTUREFORMAT_ALPHA = 0;
  17474. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17475. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17476. Engine._TEXTUREFORMAT_RGB = 4;
  17477. Engine._TEXTUREFORMAT_RGBA = 5;
  17478. Engine._TEXTUREFORMAT_R = 6;
  17479. Engine._TEXTUREFORMAT_RG = 7;
  17480. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17481. Engine._TEXTURETYPE_FLOAT = 1;
  17482. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17483. // Depht or Stencil test Constants.
  17484. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17485. 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.
  17486. 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.
  17487. 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.
  17488. 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.
  17489. 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.
  17490. 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.
  17491. 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.
  17492. // Stencil Actions Constants.
  17493. Engine._KEEP = 0x1E00;
  17494. Engine._REPLACE = 0x1E01;
  17495. Engine._INCR = 0x1E02;
  17496. Engine._DECR = 0x1E03;
  17497. Engine._INVERT = 0x150A;
  17498. Engine._INCR_WRAP = 0x8507;
  17499. Engine._DECR_WRAP = 0x8508;
  17500. // Texture rescaling mode
  17501. Engine._SCALEMODE_FLOOR = 1;
  17502. Engine._SCALEMODE_NEAREST = 2;
  17503. Engine._SCALEMODE_CEILING = 3;
  17504. // Updatable statics so stick with vars here
  17505. /**
  17506. * Gets or sets the epsilon value used by collision engine
  17507. */
  17508. Engine.CollisionsEpsilon = 0.001;
  17509. /**
  17510. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17511. */
  17512. Engine.CodeRepository = "src/";
  17513. /**
  17514. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17515. */
  17516. Engine.ShadersRepository = "src/Shaders/";
  17517. return Engine;
  17518. }());
  17519. BABYLON.Engine = Engine;
  17520. })(BABYLON || (BABYLON = {}));
  17521. //# sourceMappingURL=babylon.engine.js.map
  17522. var BABYLON;
  17523. (function (BABYLON) {
  17524. /**
  17525. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17526. */
  17527. var Node = /** @class */ (function () {
  17528. /**
  17529. * Creates a new Node
  17530. * @param {string} name - the name and id to be given to this node
  17531. * @param {BABYLON.Scene} the scene this node will be added to
  17532. */
  17533. function Node(name, scene) {
  17534. if (scene === void 0) { scene = null; }
  17535. /**
  17536. * Gets or sets a string used to store user defined state for the node
  17537. */
  17538. this.state = "";
  17539. /**
  17540. * Gets or sets an object used to store user defined information for the node
  17541. */
  17542. this.metadata = null;
  17543. /**
  17544. * Gets or sets a boolean used to define if the node must be serialized
  17545. */
  17546. this.doNotSerialize = false;
  17547. /** @hidden */
  17548. this._isDisposed = false;
  17549. /**
  17550. * Gets a list of Animations associated with the node
  17551. */
  17552. this.animations = new Array();
  17553. this._ranges = {};
  17554. this._isEnabled = true;
  17555. this._isReady = true;
  17556. /** @hidden */
  17557. this._currentRenderId = -1;
  17558. this._parentRenderId = -1;
  17559. this._childRenderId = -1;
  17560. this._animationPropertiesOverride = null;
  17561. /**
  17562. * An event triggered when the mesh is disposed
  17563. */
  17564. this.onDisposeObservable = new BABYLON.Observable();
  17565. // Behaviors
  17566. this._behaviors = new Array();
  17567. this.name = name;
  17568. this.id = name;
  17569. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17570. this.uniqueId = this._scene.getUniqueId();
  17571. this._initCache();
  17572. }
  17573. /**
  17574. * Gets a boolean indicating if the node has been disposed
  17575. * @returns true if the node was disposed
  17576. */
  17577. Node.prototype.isDisposed = function () {
  17578. return this._isDisposed;
  17579. };
  17580. Object.defineProperty(Node.prototype, "parent", {
  17581. get: function () {
  17582. return this._parentNode;
  17583. },
  17584. /**
  17585. * Gets or sets the parent of the node
  17586. */
  17587. set: function (parent) {
  17588. if (this._parentNode === parent) {
  17589. return;
  17590. }
  17591. // Remove self from list of children of parent
  17592. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17593. var index = this._parentNode._children.indexOf(this);
  17594. if (index !== -1) {
  17595. this._parentNode._children.splice(index, 1);
  17596. }
  17597. }
  17598. // Store new parent
  17599. this._parentNode = parent;
  17600. // Add as child to new parent
  17601. if (this._parentNode) {
  17602. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17603. this._parentNode._children = new Array();
  17604. }
  17605. this._parentNode._children.push(this);
  17606. }
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17612. /**
  17613. * Gets or sets the animation properties override
  17614. */
  17615. get: function () {
  17616. if (!this._animationPropertiesOverride) {
  17617. return this._scene.animationPropertiesOverride;
  17618. }
  17619. return this._animationPropertiesOverride;
  17620. },
  17621. set: function (value) {
  17622. this._animationPropertiesOverride = value;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. /**
  17628. * Gets a string idenfifying the name of the class
  17629. * @returns "Node" string
  17630. */
  17631. Node.prototype.getClassName = function () {
  17632. return "Node";
  17633. };
  17634. Object.defineProperty(Node.prototype, "onDispose", {
  17635. /**
  17636. * Sets a callback that will be raised when the node will be disposed
  17637. */
  17638. set: function (callback) {
  17639. if (this._onDisposeObserver) {
  17640. this.onDisposeObservable.remove(this._onDisposeObserver);
  17641. }
  17642. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. /**
  17648. * Gets the scene of the node
  17649. * @returns a {BABYLON.Scene}
  17650. */
  17651. Node.prototype.getScene = function () {
  17652. return this._scene;
  17653. };
  17654. /**
  17655. * Gets the engine of the node
  17656. * @returns a {BABYLON.Engine}
  17657. */
  17658. Node.prototype.getEngine = function () {
  17659. return this._scene.getEngine();
  17660. };
  17661. /**
  17662. * Attach a behavior to the node
  17663. * @see http://doc.babylonjs.com/features/behaviour
  17664. * @param behavior defines the behavior to attach
  17665. * @returns the current Node
  17666. */
  17667. Node.prototype.addBehavior = function (behavior) {
  17668. var _this = this;
  17669. var index = this._behaviors.indexOf(behavior);
  17670. if (index !== -1) {
  17671. return this;
  17672. }
  17673. behavior.init();
  17674. if (this._scene.isLoading) {
  17675. // We defer the attach when the scene will be loaded
  17676. this._scene.onDataLoadedObservable.addOnce(function () {
  17677. behavior.attach(_this);
  17678. });
  17679. }
  17680. else {
  17681. behavior.attach(this);
  17682. }
  17683. this._behaviors.push(behavior);
  17684. return this;
  17685. };
  17686. /**
  17687. * Remove an attached behavior
  17688. * @see http://doc.babylonjs.com/features/behaviour
  17689. * @param behavior defines the behavior to attach
  17690. * @returns the current Node
  17691. */
  17692. Node.prototype.removeBehavior = function (behavior) {
  17693. var index = this._behaviors.indexOf(behavior);
  17694. if (index === -1) {
  17695. return this;
  17696. }
  17697. this._behaviors[index].detach();
  17698. this._behaviors.splice(index, 1);
  17699. return this;
  17700. };
  17701. Object.defineProperty(Node.prototype, "behaviors", {
  17702. /**
  17703. * Gets the list of attached behaviors
  17704. * @see http://doc.babylonjs.com/features/behaviour
  17705. */
  17706. get: function () {
  17707. return this._behaviors;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. /**
  17713. * Gets an attached behavior by name
  17714. * @param name defines the name of the behavior to look for
  17715. * @see http://doc.babylonjs.com/features/behaviour
  17716. * @returns null if behavior was not found else the requested behavior
  17717. */
  17718. Node.prototype.getBehaviorByName = function (name) {
  17719. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17720. var behavior = _a[_i];
  17721. if (behavior.name === name) {
  17722. return behavior;
  17723. }
  17724. }
  17725. return null;
  17726. };
  17727. /**
  17728. * Returns the world matrix of the node
  17729. * @returns a matrix containing the node's world matrix
  17730. */
  17731. Node.prototype.getWorldMatrix = function () {
  17732. return BABYLON.Matrix.Identity();
  17733. };
  17734. /** @hidden */
  17735. Node.prototype._getWorldMatrixDeterminant = function () {
  17736. return 1;
  17737. };
  17738. // override it in derived class if you add new variables to the cache
  17739. // and call the parent class method
  17740. /** @hidden */
  17741. Node.prototype._initCache = function () {
  17742. this._cache = {};
  17743. this._cache.parent = undefined;
  17744. };
  17745. /** @hidden */
  17746. Node.prototype.updateCache = function (force) {
  17747. if (!force && this.isSynchronized())
  17748. return;
  17749. this._cache.parent = this.parent;
  17750. this._updateCache();
  17751. };
  17752. // override it in derived class if you add new variables to the cache
  17753. // and call the parent class method if !ignoreParentClass
  17754. /** @hidden */
  17755. Node.prototype._updateCache = function (ignoreParentClass) {
  17756. };
  17757. // override it in derived class if you add new variables to the cache
  17758. /** @hidden */
  17759. Node.prototype._isSynchronized = function () {
  17760. return true;
  17761. };
  17762. /** @hidden */
  17763. Node.prototype._markSyncedWithParent = function () {
  17764. if (this.parent) {
  17765. this._parentRenderId = this.parent._childRenderId;
  17766. }
  17767. };
  17768. /** @hidden */
  17769. Node.prototype.isSynchronizedWithParent = function () {
  17770. if (!this.parent) {
  17771. return true;
  17772. }
  17773. if (this._parentRenderId !== this.parent._childRenderId) {
  17774. return false;
  17775. }
  17776. return this.parent.isSynchronized();
  17777. };
  17778. /** @hidden */
  17779. Node.prototype.isSynchronized = function (updateCache) {
  17780. var check = this.hasNewParent();
  17781. check = check || !this.isSynchronizedWithParent();
  17782. check = check || !this._isSynchronized();
  17783. if (updateCache)
  17784. this.updateCache(true);
  17785. return !check;
  17786. };
  17787. /** @hidden */
  17788. Node.prototype.hasNewParent = function (update) {
  17789. if (this._cache.parent === this.parent)
  17790. return false;
  17791. if (update)
  17792. this._cache.parent = this.parent;
  17793. return true;
  17794. };
  17795. /**
  17796. * Is this node ready to be used/rendered
  17797. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17798. * @return true if the node is ready
  17799. */
  17800. Node.prototype.isReady = function (completeCheck) {
  17801. if (completeCheck === void 0) { completeCheck = false; }
  17802. return this._isReady;
  17803. };
  17804. /**
  17805. * Is this node enabled?
  17806. * 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
  17807. * @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
  17808. * @return whether this node (and its parent) is enabled
  17809. */
  17810. Node.prototype.isEnabled = function (checkAncestors) {
  17811. if (checkAncestors === void 0) { checkAncestors = true; }
  17812. if (checkAncestors === false) {
  17813. return this._isEnabled;
  17814. }
  17815. if (this._isEnabled === false) {
  17816. return false;
  17817. }
  17818. if (this.parent !== undefined && this.parent !== null) {
  17819. return this.parent.isEnabled(checkAncestors);
  17820. }
  17821. return true;
  17822. };
  17823. /**
  17824. * Set the enabled state of this node
  17825. * @param value defines the new enabled state
  17826. */
  17827. Node.prototype.setEnabled = function (value) {
  17828. this._isEnabled = value;
  17829. };
  17830. /**
  17831. * Is this node a descendant of the given node?
  17832. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17833. * @param ancestor defines the parent node to inspect
  17834. * @returns a boolean indicating if this node is a descendant of the given node
  17835. */
  17836. Node.prototype.isDescendantOf = function (ancestor) {
  17837. if (this.parent) {
  17838. if (this.parent === ancestor) {
  17839. return true;
  17840. }
  17841. return this.parent.isDescendantOf(ancestor);
  17842. }
  17843. return false;
  17844. };
  17845. /** @hidden */
  17846. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17847. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17848. if (!this._children) {
  17849. return;
  17850. }
  17851. for (var index = 0; index < this._children.length; index++) {
  17852. var item = this._children[index];
  17853. if (!predicate || predicate(item)) {
  17854. results.push(item);
  17855. }
  17856. if (!directDescendantsOnly) {
  17857. item._getDescendants(results, false, predicate);
  17858. }
  17859. }
  17860. };
  17861. /**
  17862. * Will return all nodes that have this node as ascendant
  17863. * @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
  17864. * @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
  17865. * @return all children nodes of all types
  17866. */
  17867. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17868. var results = new Array();
  17869. this._getDescendants(results, directDescendantsOnly, predicate);
  17870. return results;
  17871. };
  17872. /**
  17873. * Get all child-meshes of this node
  17874. * @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
  17875. * @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
  17876. * @returns an array of {BABYLON.AbstractMesh}
  17877. */
  17878. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17879. var results = [];
  17880. this._getDescendants(results, directDescendantsOnly, function (node) {
  17881. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17882. });
  17883. return results;
  17884. };
  17885. /**
  17886. * Get all child-transformNodes of this node
  17887. * @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
  17888. * @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
  17889. * @returns an array of {BABYLON.TransformNode}
  17890. */
  17891. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17892. var results = [];
  17893. this._getDescendants(results, directDescendantsOnly, function (node) {
  17894. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17895. });
  17896. return results;
  17897. };
  17898. /**
  17899. * Get all direct children of this node
  17900. * @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
  17901. * @returns an array of {BABYLON.Node}
  17902. */
  17903. Node.prototype.getChildren = function (predicate) {
  17904. return this.getDescendants(true, predicate);
  17905. };
  17906. /** @hidden */
  17907. Node.prototype._setReady = function (state) {
  17908. if (state === this._isReady) {
  17909. return;
  17910. }
  17911. if (!state) {
  17912. this._isReady = false;
  17913. return;
  17914. }
  17915. if (this.onReady) {
  17916. this.onReady(this);
  17917. }
  17918. this._isReady = true;
  17919. };
  17920. /**
  17921. * Get an animation by name
  17922. * @param name defines the name of the animation to look for
  17923. * @returns null if not found else the requested animation
  17924. */
  17925. Node.prototype.getAnimationByName = function (name) {
  17926. for (var i = 0; i < this.animations.length; i++) {
  17927. var animation = this.animations[i];
  17928. if (animation.name === name) {
  17929. return animation;
  17930. }
  17931. }
  17932. return null;
  17933. };
  17934. /**
  17935. * Creates an animation range for this node
  17936. * @param name defines the name of the range
  17937. * @param from defines the starting key
  17938. * @param to defines the end key
  17939. */
  17940. Node.prototype.createAnimationRange = function (name, from, to) {
  17941. // check name not already in use
  17942. if (!this._ranges[name]) {
  17943. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].createRange(name, from, to);
  17947. }
  17948. }
  17949. }
  17950. };
  17951. /**
  17952. * Delete a specific animation range
  17953. * @param name defines the name of the range to delete
  17954. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17955. */
  17956. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17957. if (deleteFrames === void 0) { deleteFrames = true; }
  17958. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17959. if (this.animations[i]) {
  17960. this.animations[i].deleteRange(name, deleteFrames);
  17961. }
  17962. }
  17963. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17964. };
  17965. /**
  17966. * Get an animation range by name
  17967. * @param name defines the name of the animation range to look for
  17968. * @returns null if not found else the requested animation range
  17969. */
  17970. Node.prototype.getAnimationRange = function (name) {
  17971. return this._ranges[name];
  17972. };
  17973. /**
  17974. * Will start the animation sequence
  17975. * @param name defines the range frames for animation sequence
  17976. * @param loop defines if the animation should loop (false by default)
  17977. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17978. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17979. * @returns the object created for this animation. If range does not exist, it will return null
  17980. */
  17981. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17982. var range = this.getAnimationRange(name);
  17983. if (!range) {
  17984. return null;
  17985. }
  17986. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17987. };
  17988. /**
  17989. * Serialize animation ranges into a JSON compatible object
  17990. * @returns serialization object
  17991. */
  17992. Node.prototype.serializeAnimationRanges = function () {
  17993. var serializationRanges = [];
  17994. for (var name in this._ranges) {
  17995. var localRange = this._ranges[name];
  17996. if (!localRange) {
  17997. continue;
  17998. }
  17999. var range = {};
  18000. range.name = name;
  18001. range.from = localRange.from;
  18002. range.to = localRange.to;
  18003. serializationRanges.push(range);
  18004. }
  18005. return serializationRanges;
  18006. };
  18007. /**
  18008. * Computes the world matrix of the node
  18009. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18010. * @returns the world matrix
  18011. */
  18012. Node.prototype.computeWorldMatrix = function (force) {
  18013. return BABYLON.Matrix.Identity();
  18014. };
  18015. /**
  18016. * Releases resources associated with this node.
  18017. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18018. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18019. */
  18020. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18021. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18022. if (!doNotRecurse) {
  18023. var nodes = this.getDescendants(true);
  18024. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18025. var node = nodes_1[_i];
  18026. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18027. }
  18028. }
  18029. else {
  18030. var transformNodes = this.getChildTransformNodes(true);
  18031. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18032. var transformNode = transformNodes_1[_a];
  18033. transformNode.parent = null;
  18034. transformNode.computeWorldMatrix(true);
  18035. }
  18036. }
  18037. this.parent = null;
  18038. // Callback
  18039. this.onDisposeObservable.notifyObservers(this);
  18040. this.onDisposeObservable.clear();
  18041. // Behaviors
  18042. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18043. var behavior = _c[_b];
  18044. behavior.detach();
  18045. }
  18046. this._behaviors = [];
  18047. this._isDisposed = true;
  18048. };
  18049. /**
  18050. * Parse animation range data from a serialization object and store them into a given node
  18051. * @param node defines where to store the animation ranges
  18052. * @param parsedNode defines the serialization object to read data from
  18053. * @param scene defines the hosting scene
  18054. */
  18055. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18056. if (parsedNode.ranges) {
  18057. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18058. var data = parsedNode.ranges[index];
  18059. node.createAnimationRange(data.name, data.from, data.to);
  18060. }
  18061. }
  18062. };
  18063. __decorate([
  18064. BABYLON.serialize()
  18065. ], Node.prototype, "name", void 0);
  18066. __decorate([
  18067. BABYLON.serialize()
  18068. ], Node.prototype, "id", void 0);
  18069. __decorate([
  18070. BABYLON.serialize()
  18071. ], Node.prototype, "uniqueId", void 0);
  18072. __decorate([
  18073. BABYLON.serialize()
  18074. ], Node.prototype, "state", void 0);
  18075. __decorate([
  18076. BABYLON.serialize()
  18077. ], Node.prototype, "metadata", void 0);
  18078. return Node;
  18079. }());
  18080. BABYLON.Node = Node;
  18081. })(BABYLON || (BABYLON = {}));
  18082. //# sourceMappingURL=babylon.node.js.map
  18083. var BABYLON;
  18084. (function (BABYLON) {
  18085. var BoundingSphere = /** @class */ (function () {
  18086. /**
  18087. * Creates a new bounding sphere
  18088. * @param min defines the minimum vector (in local space)
  18089. * @param max defines the maximum vector (in local space)
  18090. */
  18091. function BoundingSphere(min, max) {
  18092. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18093. this.reConstruct(min, max);
  18094. }
  18095. /**
  18096. * Recreates the entire bounding sphere from scratch
  18097. * @param min defines the new minimum vector (in local space)
  18098. * @param max defines the new maximum vector (in local space)
  18099. */
  18100. BoundingSphere.prototype.reConstruct = function (min, max) {
  18101. this.minimum = min.clone();
  18102. this.maximum = max.clone();
  18103. var distance = BABYLON.Vector3.Distance(min, max);
  18104. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18105. this.radius = distance * 0.5;
  18106. this.centerWorld = BABYLON.Vector3.Zero();
  18107. this._update(BABYLON.Matrix.Identity());
  18108. };
  18109. // Methods
  18110. BoundingSphere.prototype._update = function (world) {
  18111. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18112. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18113. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18114. };
  18115. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18116. for (var i = 0; i < 6; i++) {
  18117. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18118. return false;
  18119. }
  18120. return true;
  18121. };
  18122. BoundingSphere.prototype.intersectsPoint = function (point) {
  18123. var x = this.centerWorld.x - point.x;
  18124. var y = this.centerWorld.y - point.y;
  18125. var z = this.centerWorld.z - point.z;
  18126. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18127. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18128. return false;
  18129. return true;
  18130. };
  18131. // Statics
  18132. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18133. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18134. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18135. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18136. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18137. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18138. return false;
  18139. return true;
  18140. };
  18141. return BoundingSphere;
  18142. }());
  18143. BABYLON.BoundingSphere = BoundingSphere;
  18144. })(BABYLON || (BABYLON = {}));
  18145. //# sourceMappingURL=babylon.boundingSphere.js.map
  18146. var BABYLON;
  18147. (function (BABYLON) {
  18148. var BoundingBox = /** @class */ (function () {
  18149. /**
  18150. * Creates a new bounding box
  18151. * @param min defines the minimum vector (in local space)
  18152. * @param max defines the maximum vector (in local space)
  18153. */
  18154. function BoundingBox(min, max) {
  18155. this.vectorsWorld = new Array();
  18156. this.reConstruct(min, max);
  18157. }
  18158. // Methods
  18159. /**
  18160. * Recreates the entire bounding box from scratch
  18161. * @param min defines the new minimum vector (in local space)
  18162. * @param max defines the new maximum vector (in local space)
  18163. */
  18164. BoundingBox.prototype.reConstruct = function (min, max) {
  18165. this.minimum = min.clone();
  18166. this.maximum = max.clone();
  18167. // Bounding vectors
  18168. this.vectors = new Array();
  18169. this.vectors.push(this.minimum.clone());
  18170. this.vectors.push(this.maximum.clone());
  18171. this.vectors.push(this.minimum.clone());
  18172. this.vectors[2].x = this.maximum.x;
  18173. this.vectors.push(this.minimum.clone());
  18174. this.vectors[3].y = this.maximum.y;
  18175. this.vectors.push(this.minimum.clone());
  18176. this.vectors[4].z = this.maximum.z;
  18177. this.vectors.push(this.maximum.clone());
  18178. this.vectors[5].z = this.minimum.z;
  18179. this.vectors.push(this.maximum.clone());
  18180. this.vectors[6].x = this.minimum.x;
  18181. this.vectors.push(this.maximum.clone());
  18182. this.vectors[7].y = this.minimum.y;
  18183. // OBB
  18184. this.center = this.maximum.add(this.minimum).scale(0.5);
  18185. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18186. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18187. // World
  18188. for (var index = 0; index < this.vectors.length; index++) {
  18189. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18190. }
  18191. this.minimumWorld = BABYLON.Vector3.Zero();
  18192. this.maximumWorld = BABYLON.Vector3.Zero();
  18193. this.centerWorld = BABYLON.Vector3.Zero();
  18194. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18195. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18196. };
  18197. BoundingBox.prototype.getWorldMatrix = function () {
  18198. return this._worldMatrix;
  18199. };
  18200. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18201. this._worldMatrix.copyFrom(matrix);
  18202. return this;
  18203. };
  18204. BoundingBox.prototype._update = function (world) {
  18205. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18206. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18207. for (var index = 0; index < this.vectors.length; index++) {
  18208. var v = this.vectorsWorld[index];
  18209. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18210. if (v.x < this.minimumWorld.x)
  18211. this.minimumWorld.x = v.x;
  18212. if (v.y < this.minimumWorld.y)
  18213. this.minimumWorld.y = v.y;
  18214. if (v.z < this.minimumWorld.z)
  18215. this.minimumWorld.z = v.z;
  18216. if (v.x > this.maximumWorld.x)
  18217. this.maximumWorld.x = v.x;
  18218. if (v.y > this.maximumWorld.y)
  18219. this.maximumWorld.y = v.y;
  18220. if (v.z > this.maximumWorld.z)
  18221. this.maximumWorld.z = v.z;
  18222. }
  18223. // Extend
  18224. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18225. this.extendSizeWorld.scaleInPlace(0.5);
  18226. // OBB
  18227. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18228. this.centerWorld.scaleInPlace(0.5);
  18229. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18230. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18231. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18232. this._worldMatrix = world;
  18233. };
  18234. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18235. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18236. };
  18237. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18238. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18239. };
  18240. BoundingBox.prototype.intersectsPoint = function (point) {
  18241. var delta = -BABYLON.Epsilon;
  18242. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18243. return false;
  18244. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18245. return false;
  18246. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18247. return false;
  18248. return true;
  18249. };
  18250. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18251. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18252. };
  18253. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18254. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18255. return false;
  18256. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18257. return false;
  18258. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18259. return false;
  18260. return true;
  18261. };
  18262. // Statics
  18263. BoundingBox.Intersects = function (box0, box1) {
  18264. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18265. return false;
  18266. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18267. return false;
  18268. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18269. return false;
  18270. return true;
  18271. };
  18272. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18273. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18274. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18275. return (num <= (sphereRadius * sphereRadius));
  18276. };
  18277. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18278. for (var p = 0; p < 6; p++) {
  18279. for (var i = 0; i < 8; i++) {
  18280. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18281. return false;
  18282. }
  18283. }
  18284. }
  18285. return true;
  18286. };
  18287. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18288. for (var p = 0; p < 6; p++) {
  18289. var inCount = 8;
  18290. for (var i = 0; i < 8; i++) {
  18291. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18292. --inCount;
  18293. }
  18294. else {
  18295. break;
  18296. }
  18297. }
  18298. if (inCount === 0)
  18299. return false;
  18300. }
  18301. return true;
  18302. };
  18303. return BoundingBox;
  18304. }());
  18305. BABYLON.BoundingBox = BoundingBox;
  18306. })(BABYLON || (BABYLON = {}));
  18307. //# sourceMappingURL=babylon.boundingBox.js.map
  18308. var BABYLON;
  18309. (function (BABYLON) {
  18310. var computeBoxExtents = function (axis, box) {
  18311. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18312. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18313. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18314. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18315. var r = r0 + r1 + r2;
  18316. return {
  18317. min: p - r,
  18318. max: p + r
  18319. };
  18320. };
  18321. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18322. var axisOverlap = function (axis, box0, box1) {
  18323. var result0 = computeBoxExtents(axis, box0);
  18324. var result1 = computeBoxExtents(axis, box1);
  18325. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18326. };
  18327. var BoundingInfo = /** @class */ (function () {
  18328. function BoundingInfo(minimum, maximum) {
  18329. this.minimum = minimum;
  18330. this.maximum = maximum;
  18331. this._isLocked = false;
  18332. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18333. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18334. }
  18335. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18336. get: function () {
  18337. return this._isLocked;
  18338. },
  18339. set: function (value) {
  18340. this._isLocked = value;
  18341. },
  18342. enumerable: true,
  18343. configurable: true
  18344. });
  18345. // Methods
  18346. BoundingInfo.prototype.update = function (world) {
  18347. if (this._isLocked) {
  18348. return;
  18349. }
  18350. this.boundingBox._update(world);
  18351. this.boundingSphere._update(world);
  18352. };
  18353. /**
  18354. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18355. * @param center New center of the bounding info
  18356. * @param extend New extend of the bounding info
  18357. */
  18358. BoundingInfo.prototype.centerOn = function (center, extend) {
  18359. this.minimum = center.subtract(extend);
  18360. this.maximum = center.add(extend);
  18361. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18362. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18363. return this;
  18364. };
  18365. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18366. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18367. return false;
  18368. return this.boundingBox.isInFrustum(frustumPlanes);
  18369. };
  18370. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18371. /**
  18372. * Gets the world distance between the min and max points of the bounding box
  18373. */
  18374. get: function () {
  18375. var boundingBox = this.boundingBox;
  18376. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18377. return size.length();
  18378. },
  18379. enumerable: true,
  18380. configurable: true
  18381. });
  18382. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18383. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18384. };
  18385. BoundingInfo.prototype._checkCollision = function (collider) {
  18386. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18387. };
  18388. BoundingInfo.prototype.intersectsPoint = function (point) {
  18389. if (!this.boundingSphere.centerWorld) {
  18390. return false;
  18391. }
  18392. if (!this.boundingSphere.intersectsPoint(point)) {
  18393. return false;
  18394. }
  18395. if (!this.boundingBox.intersectsPoint(point)) {
  18396. return false;
  18397. }
  18398. return true;
  18399. };
  18400. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18401. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18402. return false;
  18403. }
  18404. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18405. return false;
  18406. }
  18407. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18408. return false;
  18409. }
  18410. if (!precise) {
  18411. return true;
  18412. }
  18413. var box0 = this.boundingBox;
  18414. var box1 = boundingInfo.boundingBox;
  18415. if (!axisOverlap(box0.directions[0], box0, box1))
  18416. return false;
  18417. if (!axisOverlap(box0.directions[1], box0, box1))
  18418. return false;
  18419. if (!axisOverlap(box0.directions[2], box0, box1))
  18420. return false;
  18421. if (!axisOverlap(box1.directions[0], box0, box1))
  18422. return false;
  18423. if (!axisOverlap(box1.directions[1], box0, box1))
  18424. return false;
  18425. if (!axisOverlap(box1.directions[2], box0, box1))
  18426. return false;
  18427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18428. return false;
  18429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18430. return false;
  18431. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18432. return false;
  18433. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18434. return false;
  18435. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18436. return false;
  18437. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18438. return false;
  18439. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18440. return false;
  18441. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18442. return false;
  18443. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18444. return false;
  18445. return true;
  18446. };
  18447. return BoundingInfo;
  18448. }());
  18449. BABYLON.BoundingInfo = BoundingInfo;
  18450. })(BABYLON || (BABYLON = {}));
  18451. //# sourceMappingURL=babylon.boundingInfo.js.map
  18452. var BABYLON;
  18453. (function (BABYLON) {
  18454. var TransformNode = /** @class */ (function (_super) {
  18455. __extends(TransformNode, _super);
  18456. function TransformNode(name, scene, isPure) {
  18457. if (scene === void 0) { scene = null; }
  18458. if (isPure === void 0) { isPure = true; }
  18459. var _this = _super.call(this, name, scene) || this;
  18460. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18461. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18462. _this._up = new BABYLON.Vector3(0, 1, 0);
  18463. _this._right = new BABYLON.Vector3(1, 0, 0);
  18464. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18465. // Properties
  18466. _this._rotation = BABYLON.Vector3.Zero();
  18467. _this._scaling = BABYLON.Vector3.One();
  18468. _this._isDirty = false;
  18469. /**
  18470. * Set the billboard mode. Default is 0.
  18471. *
  18472. * | Value | Type | Description |
  18473. * | --- | --- | --- |
  18474. * | 0 | BILLBOARDMODE_NONE | |
  18475. * | 1 | BILLBOARDMODE_X | |
  18476. * | 2 | BILLBOARDMODE_Y | |
  18477. * | 4 | BILLBOARDMODE_Z | |
  18478. * | 7 | BILLBOARDMODE_ALL | |
  18479. *
  18480. */
  18481. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18482. _this.scalingDeterminant = 1;
  18483. _this.infiniteDistance = false;
  18484. /**
  18485. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18486. * By default the system will update normals to compensate
  18487. */
  18488. _this.ignoreNonUniformScaling = false;
  18489. _this.position = BABYLON.Vector3.Zero();
  18490. _this._localWorld = BABYLON.Matrix.Zero();
  18491. _this._worldMatrix = BABYLON.Matrix.Zero();
  18492. _this._worldMatrixDeterminant = 0;
  18493. _this._absolutePosition = BABYLON.Vector3.Zero();
  18494. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18495. _this._postMultiplyPivotMatrix = false;
  18496. _this._isWorldMatrixFrozen = false;
  18497. /**
  18498. * An event triggered after the world matrix is updated
  18499. */
  18500. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18501. _this._nonUniformScaling = false;
  18502. if (isPure) {
  18503. _this.getScene().addTransformNode(_this);
  18504. }
  18505. return _this;
  18506. }
  18507. /**
  18508. * Gets a string idenfifying the name of the class
  18509. * @returns "TransformNode" string
  18510. */
  18511. TransformNode.prototype.getClassName = function () {
  18512. return "TransformNode";
  18513. };
  18514. Object.defineProperty(TransformNode.prototype, "rotation", {
  18515. /**
  18516. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18517. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18518. * Default : (0.0, 0.0, 0.0)
  18519. */
  18520. get: function () {
  18521. return this._rotation;
  18522. },
  18523. set: function (newRotation) {
  18524. this._rotation = newRotation;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. Object.defineProperty(TransformNode.prototype, "scaling", {
  18530. /**
  18531. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18532. * Default : (1.0, 1.0, 1.0)
  18533. */
  18534. get: function () {
  18535. return this._scaling;
  18536. },
  18537. /**
  18538. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18539. * Default : (1.0, 1.0, 1.0)
  18540. */
  18541. set: function (newScaling) {
  18542. this._scaling = newScaling;
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18548. /**
  18549. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18550. * It's null by default.
  18551. * 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)
  18552. */
  18553. get: function () {
  18554. return this._rotationQuaternion;
  18555. },
  18556. set: function (quaternion) {
  18557. this._rotationQuaternion = quaternion;
  18558. //reset the rotation vector.
  18559. if (quaternion && this.rotation.length()) {
  18560. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18561. }
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Object.defineProperty(TransformNode.prototype, "forward", {
  18567. /**
  18568. * The forward direction of that transform in world space.
  18569. */
  18570. get: function () {
  18571. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(TransformNode.prototype, "up", {
  18577. /**
  18578. * The up direction of that transform in world space.
  18579. */
  18580. get: function () {
  18581. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(TransformNode.prototype, "right", {
  18587. /**
  18588. * The right direction of that transform in world space.
  18589. */
  18590. get: function () {
  18591. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. /**
  18597. * Returns the latest update of the World matrix
  18598. * Returns a Matrix.
  18599. */
  18600. TransformNode.prototype.getWorldMatrix = function () {
  18601. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18602. this.computeWorldMatrix();
  18603. }
  18604. return this._worldMatrix;
  18605. };
  18606. /** @hidden */
  18607. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18608. return this._worldMatrixDeterminant;
  18609. };
  18610. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18611. /**
  18612. * Returns directly the latest state of the mesh World matrix.
  18613. * A Matrix is returned.
  18614. */
  18615. get: function () {
  18616. return this._worldMatrix;
  18617. },
  18618. enumerable: true,
  18619. configurable: true
  18620. });
  18621. /**
  18622. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18623. * Returns the TransformNode.
  18624. */
  18625. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18626. this._poseMatrix.copyFrom(matrix);
  18627. return this;
  18628. };
  18629. /**
  18630. * Returns the mesh Pose matrix.
  18631. * Returned object : Matrix
  18632. */
  18633. TransformNode.prototype.getPoseMatrix = function () {
  18634. return this._poseMatrix;
  18635. };
  18636. TransformNode.prototype._isSynchronized = function () {
  18637. if (this._isDirty) {
  18638. return false;
  18639. }
  18640. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18641. return false;
  18642. if (this._cache.pivotMatrixUpdated) {
  18643. return false;
  18644. }
  18645. if (this.infiniteDistance) {
  18646. return false;
  18647. }
  18648. if (!this._cache.position.equals(this.position))
  18649. return false;
  18650. if (this.rotationQuaternion) {
  18651. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18652. return false;
  18653. }
  18654. if (!this._cache.rotation.equals(this.rotation))
  18655. return false;
  18656. if (!this._cache.scaling.equals(this.scaling))
  18657. return false;
  18658. return true;
  18659. };
  18660. TransformNode.prototype._initCache = function () {
  18661. _super.prototype._initCache.call(this);
  18662. this._cache.localMatrixUpdated = false;
  18663. this._cache.position = BABYLON.Vector3.Zero();
  18664. this._cache.scaling = BABYLON.Vector3.Zero();
  18665. this._cache.rotation = BABYLON.Vector3.Zero();
  18666. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18667. this._cache.billboardMode = -1;
  18668. };
  18669. TransformNode.prototype.markAsDirty = function (property) {
  18670. if (property === "rotation") {
  18671. this.rotationQuaternion = null;
  18672. }
  18673. this._currentRenderId = Number.MAX_VALUE;
  18674. this._isDirty = true;
  18675. return this;
  18676. };
  18677. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18678. /**
  18679. * Returns the current mesh absolute position.
  18680. * Retuns a Vector3.
  18681. */
  18682. get: function () {
  18683. return this._absolutePosition;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. /**
  18689. * Sets a new matrix to apply before all other transformation
  18690. * @param matrix defines the transform matrix
  18691. * @returns the current TransformNode
  18692. */
  18693. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18694. return this.setPivotMatrix(matrix, false);
  18695. };
  18696. /**
  18697. * Sets a new pivot matrix to the current node
  18698. * @param matrix defines the new pivot matrix to use
  18699. * @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
  18700. * @returns the current TransformNode
  18701. */
  18702. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18703. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18704. this._pivotMatrix = matrix.clone();
  18705. this._cache.pivotMatrixUpdated = true;
  18706. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18707. if (this._postMultiplyPivotMatrix) {
  18708. if (!this._pivotMatrixInverse) {
  18709. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18710. }
  18711. else {
  18712. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18713. }
  18714. }
  18715. return this;
  18716. };
  18717. /**
  18718. * Returns the mesh pivot matrix.
  18719. * Default : Identity.
  18720. * A Matrix is returned.
  18721. */
  18722. TransformNode.prototype.getPivotMatrix = function () {
  18723. return this._pivotMatrix;
  18724. };
  18725. /**
  18726. * Prevents the World matrix to be computed any longer.
  18727. * Returns the TransformNode.
  18728. */
  18729. TransformNode.prototype.freezeWorldMatrix = function () {
  18730. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18731. this.computeWorldMatrix(true);
  18732. this._isWorldMatrixFrozen = true;
  18733. return this;
  18734. };
  18735. /**
  18736. * Allows back the World matrix computation.
  18737. * Returns the TransformNode.
  18738. */
  18739. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18740. this._isWorldMatrixFrozen = false;
  18741. this.computeWorldMatrix(true);
  18742. return this;
  18743. };
  18744. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18745. /**
  18746. * True if the World matrix has been frozen.
  18747. * Returns a boolean.
  18748. */
  18749. get: function () {
  18750. return this._isWorldMatrixFrozen;
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. /**
  18756. * Retuns the mesh absolute position in the World.
  18757. * Returns a Vector3.
  18758. */
  18759. TransformNode.prototype.getAbsolutePosition = function () {
  18760. this.computeWorldMatrix();
  18761. return this._absolutePosition;
  18762. };
  18763. /**
  18764. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18765. * Returns the TransformNode.
  18766. */
  18767. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18768. if (!absolutePosition) {
  18769. return this;
  18770. }
  18771. var absolutePositionX;
  18772. var absolutePositionY;
  18773. var absolutePositionZ;
  18774. if (absolutePosition.x === undefined) {
  18775. if (arguments.length < 3) {
  18776. return this;
  18777. }
  18778. absolutePositionX = arguments[0];
  18779. absolutePositionY = arguments[1];
  18780. absolutePositionZ = arguments[2];
  18781. }
  18782. else {
  18783. absolutePositionX = absolutePosition.x;
  18784. absolutePositionY = absolutePosition.y;
  18785. absolutePositionZ = absolutePosition.z;
  18786. }
  18787. if (this.parent) {
  18788. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18789. invertParentWorldMatrix.invert();
  18790. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18791. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18792. }
  18793. else {
  18794. this.position.x = absolutePositionX;
  18795. this.position.y = absolutePositionY;
  18796. this.position.z = absolutePositionZ;
  18797. }
  18798. return this;
  18799. };
  18800. /**
  18801. * Sets the mesh position in its local space.
  18802. * Returns the TransformNode.
  18803. */
  18804. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18805. this.computeWorldMatrix();
  18806. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18807. return this;
  18808. };
  18809. /**
  18810. * Returns the mesh position in the local space from the current World matrix values.
  18811. * Returns a new Vector3.
  18812. */
  18813. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18814. this.computeWorldMatrix();
  18815. var invLocalWorldMatrix = this._localWorld.clone();
  18816. invLocalWorldMatrix.invert();
  18817. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18818. };
  18819. /**
  18820. * Translates the mesh along the passed Vector3 in its local space.
  18821. * Returns the TransformNode.
  18822. */
  18823. TransformNode.prototype.locallyTranslate = function (vector3) {
  18824. this.computeWorldMatrix(true);
  18825. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18826. return this;
  18827. };
  18828. /**
  18829. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18830. * @param targetPoint the position (must be in same space as current mesh) to look at
  18831. * @param yawCor optional yaw (y-axis) correction in radians
  18832. * @param pitchCor optional pitch (x-axis) correction in radians
  18833. * @param rollCor optional roll (z-axis) correction in radians
  18834. * @param space the choosen space of the target
  18835. * @returns the TransformNode.
  18836. */
  18837. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18838. if (yawCor === void 0) { yawCor = 0; }
  18839. if (pitchCor === void 0) { pitchCor = 0; }
  18840. if (rollCor === void 0) { rollCor = 0; }
  18841. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18842. var dv = TransformNode._lookAtVectorCache;
  18843. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18844. targetPoint.subtractToRef(pos, dv);
  18845. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18846. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18847. var pitch = Math.atan2(dv.y, len);
  18848. if (this.rotationQuaternion) {
  18849. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18850. }
  18851. else {
  18852. this.rotation.x = pitch + pitchCor;
  18853. this.rotation.y = yaw + yawCor;
  18854. this.rotation.z = rollCor;
  18855. }
  18856. return this;
  18857. };
  18858. /**
  18859. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18860. * This Vector3 is expressed in the World space.
  18861. */
  18862. TransformNode.prototype.getDirection = function (localAxis) {
  18863. var result = BABYLON.Vector3.Zero();
  18864. this.getDirectionToRef(localAxis, result);
  18865. return result;
  18866. };
  18867. /**
  18868. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18869. * localAxis is expressed in the mesh local space.
  18870. * result is computed in the Wordl space from the mesh World matrix.
  18871. * Returns the TransformNode.
  18872. */
  18873. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18874. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18875. return this;
  18876. };
  18877. /**
  18878. * Sets a new pivot point to the current node
  18879. * @param point defines the new pivot point to use
  18880. * @param space defines if the point is in world or local space (local by default)
  18881. * @returns the current TransformNode
  18882. */
  18883. TransformNode.prototype.setPivotPoint = function (point, space) {
  18884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18885. if (this.getScene().getRenderId() == 0) {
  18886. this.computeWorldMatrix(true);
  18887. }
  18888. var wm = this.getWorldMatrix();
  18889. if (space == BABYLON.Space.WORLD) {
  18890. var tmat = BABYLON.Tmp.Matrix[0];
  18891. wm.invertToRef(tmat);
  18892. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18893. }
  18894. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18895. };
  18896. /**
  18897. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18898. */
  18899. TransformNode.prototype.getPivotPoint = function () {
  18900. var point = BABYLON.Vector3.Zero();
  18901. this.getPivotPointToRef(point);
  18902. return point;
  18903. };
  18904. /**
  18905. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18906. * Returns the TransformNode.
  18907. */
  18908. TransformNode.prototype.getPivotPointToRef = function (result) {
  18909. result.x = -this._pivotMatrix.m[12];
  18910. result.y = -this._pivotMatrix.m[13];
  18911. result.z = -this._pivotMatrix.m[14];
  18912. return this;
  18913. };
  18914. /**
  18915. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18916. */
  18917. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18918. var point = BABYLON.Vector3.Zero();
  18919. this.getAbsolutePivotPointToRef(point);
  18920. return point;
  18921. };
  18922. /**
  18923. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18924. * Returns the TransformNode.
  18925. */
  18926. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18927. result.x = this._pivotMatrix.m[12];
  18928. result.y = this._pivotMatrix.m[13];
  18929. result.z = this._pivotMatrix.m[14];
  18930. this.getPivotPointToRef(result);
  18931. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18932. return this;
  18933. };
  18934. /**
  18935. * Defines the passed node as the parent of the current node.
  18936. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18937. * Returns the TransformNode.
  18938. */
  18939. TransformNode.prototype.setParent = function (node) {
  18940. if (node === null) {
  18941. var rotation = BABYLON.Tmp.Quaternion[0];
  18942. var position = BABYLON.Tmp.Vector3[0];
  18943. var scale = BABYLON.Tmp.Vector3[1];
  18944. if (this.parent && this.parent.computeWorldMatrix) {
  18945. this.parent.computeWorldMatrix(true);
  18946. }
  18947. this.computeWorldMatrix(true);
  18948. this.getWorldMatrix().decompose(scale, rotation, position);
  18949. if (this.rotationQuaternion) {
  18950. this.rotationQuaternion.copyFrom(rotation);
  18951. }
  18952. else {
  18953. rotation.toEulerAnglesToRef(this.rotation);
  18954. }
  18955. this.scaling.x = scale.x;
  18956. this.scaling.y = scale.y;
  18957. this.scaling.z = scale.z;
  18958. this.position.x = position.x;
  18959. this.position.y = position.y;
  18960. this.position.z = position.z;
  18961. }
  18962. else {
  18963. var rotation = BABYLON.Tmp.Quaternion[0];
  18964. var position = BABYLON.Tmp.Vector3[0];
  18965. var scale = BABYLON.Tmp.Vector3[1];
  18966. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18967. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18968. this.computeWorldMatrix(true);
  18969. node.computeWorldMatrix(true);
  18970. node.getWorldMatrix().invertToRef(invParentMatrix);
  18971. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18972. diffMatrix.decompose(scale, rotation, position);
  18973. if (this.rotationQuaternion) {
  18974. this.rotationQuaternion.copyFrom(rotation);
  18975. }
  18976. else {
  18977. rotation.toEulerAnglesToRef(this.rotation);
  18978. }
  18979. this.position.x = position.x;
  18980. this.position.y = position.y;
  18981. this.position.z = position.z;
  18982. this.scaling.x = scale.x;
  18983. this.scaling.y = scale.y;
  18984. this.scaling.z = scale.z;
  18985. }
  18986. this.parent = node;
  18987. return this;
  18988. };
  18989. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18990. get: function () {
  18991. return this._nonUniformScaling;
  18992. },
  18993. enumerable: true,
  18994. configurable: true
  18995. });
  18996. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18997. if (this._nonUniformScaling === value) {
  18998. return false;
  18999. }
  19000. this._nonUniformScaling = value;
  19001. return true;
  19002. };
  19003. /**
  19004. * Attach the current TransformNode to another TransformNode associated with a bone
  19005. * @param bone Bone affecting the TransformNode
  19006. * @param affectedTransformNode TransformNode associated with the bone
  19007. */
  19008. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19009. this._transformToBoneReferal = affectedTransformNode;
  19010. this.parent = bone;
  19011. if (bone.getWorldMatrix().determinant() < 0) {
  19012. this.scalingDeterminant *= -1;
  19013. }
  19014. return this;
  19015. };
  19016. TransformNode.prototype.detachFromBone = function () {
  19017. if (!this.parent) {
  19018. return this;
  19019. }
  19020. if (this.parent.getWorldMatrix().determinant() < 0) {
  19021. this.scalingDeterminant *= -1;
  19022. }
  19023. this._transformToBoneReferal = null;
  19024. this.parent = null;
  19025. return this;
  19026. };
  19027. /**
  19028. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19029. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19030. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19031. * The passed axis is also normalized.
  19032. * Returns the TransformNode.
  19033. */
  19034. TransformNode.prototype.rotate = function (axis, amount, space) {
  19035. axis.normalize();
  19036. if (!this.rotationQuaternion) {
  19037. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19038. this.rotation = BABYLON.Vector3.Zero();
  19039. }
  19040. var rotationQuaternion;
  19041. if (!space || space === BABYLON.Space.LOCAL) {
  19042. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19043. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19044. }
  19045. else {
  19046. if (this.parent) {
  19047. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19048. invertParentWorldMatrix.invert();
  19049. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19050. }
  19051. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19052. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19053. }
  19054. return this;
  19055. };
  19056. /**
  19057. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19058. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19059. * The passed axis is also normalized.
  19060. * Returns the TransformNode.
  19061. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19062. */
  19063. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19064. axis.normalize();
  19065. if (!this.rotationQuaternion) {
  19066. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19067. this.rotation.copyFromFloats(0, 0, 0);
  19068. }
  19069. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19070. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19071. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19072. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19073. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19074. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19075. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19076. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19077. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19078. return this;
  19079. };
  19080. /**
  19081. * Translates the mesh along the axis vector for the passed distance in the given space.
  19082. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19083. * Returns the TransformNode.
  19084. */
  19085. TransformNode.prototype.translate = function (axis, distance, space) {
  19086. var displacementVector = axis.scale(distance);
  19087. if (!space || space === BABYLON.Space.LOCAL) {
  19088. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19089. this.setPositionWithLocalVector(tempV3);
  19090. }
  19091. else {
  19092. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19093. }
  19094. return this;
  19095. };
  19096. /**
  19097. * Adds a rotation step to the mesh current rotation.
  19098. * x, y, z are Euler angles expressed in radians.
  19099. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19100. * This means this rotation is made in the mesh local space only.
  19101. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19102. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19103. * ```javascript
  19104. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19105. * ```
  19106. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19107. * 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.
  19108. * Returns the TransformNode.
  19109. */
  19110. TransformNode.prototype.addRotation = function (x, y, z) {
  19111. var rotationQuaternion;
  19112. if (this.rotationQuaternion) {
  19113. rotationQuaternion = this.rotationQuaternion;
  19114. }
  19115. else {
  19116. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19117. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19118. }
  19119. var accumulation = BABYLON.Tmp.Quaternion[0];
  19120. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19121. rotationQuaternion.multiplyInPlace(accumulation);
  19122. if (!this.rotationQuaternion) {
  19123. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19124. }
  19125. return this;
  19126. };
  19127. /**
  19128. * Computes the mesh World matrix and returns it.
  19129. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19130. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19131. * If the parameter `force`is set to `true`, the actual computation is done.
  19132. * Returns the mesh World Matrix.
  19133. */
  19134. TransformNode.prototype.computeWorldMatrix = function (force) {
  19135. if (this._isWorldMatrixFrozen) {
  19136. return this._worldMatrix;
  19137. }
  19138. if (!force && this.isSynchronized(true)) {
  19139. this._currentRenderId = this.getScene().getRenderId();
  19140. return this._worldMatrix;
  19141. }
  19142. this._cache.position.copyFrom(this.position);
  19143. this._cache.scaling.copyFrom(this.scaling);
  19144. this._cache.pivotMatrixUpdated = false;
  19145. this._cache.billboardMode = this.billboardMode;
  19146. this._currentRenderId = this.getScene().getRenderId();
  19147. this._childRenderId = this.getScene().getRenderId();
  19148. this._isDirty = false;
  19149. // Scaling
  19150. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19151. // Rotation
  19152. //rotate, if quaternion is set and rotation was used
  19153. if (this.rotationQuaternion) {
  19154. var len = this.rotation.length();
  19155. if (len) {
  19156. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19157. this.rotation.copyFromFloats(0, 0, 0);
  19158. }
  19159. }
  19160. if (this.rotationQuaternion) {
  19161. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19162. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19163. }
  19164. else {
  19165. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19166. this._cache.rotation.copyFrom(this.rotation);
  19167. }
  19168. // Translation
  19169. var camera = this.getScene().activeCamera;
  19170. if (this.infiniteDistance && !this.parent && camera) {
  19171. var cameraWorldMatrix = camera.getWorldMatrix();
  19172. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19173. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19174. }
  19175. else {
  19176. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19177. }
  19178. // Composing transformations
  19179. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19180. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19181. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19182. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19183. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19184. // Need to decompose each rotation here
  19185. var currentPosition = BABYLON.Tmp.Vector3[3];
  19186. if (this.parent && this.parent.getWorldMatrix) {
  19187. if (this._transformToBoneReferal) {
  19188. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19189. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19190. }
  19191. else {
  19192. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19193. }
  19194. }
  19195. else {
  19196. currentPosition.copyFrom(this.position);
  19197. }
  19198. currentPosition.subtractInPlace(camera.globalPosition);
  19199. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19200. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19201. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19202. }
  19203. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19204. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19205. }
  19206. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19207. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19208. }
  19209. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19210. }
  19211. else {
  19212. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19213. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19214. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19215. }
  19216. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19217. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19218. }
  19219. // Local world
  19220. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19221. // Parent
  19222. if (this.parent && this.parent.getWorldMatrix) {
  19223. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19224. if (this._transformToBoneReferal) {
  19225. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19226. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19227. }
  19228. else {
  19229. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19230. }
  19231. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19232. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19233. this._worldMatrix.copyFrom(this._localWorld);
  19234. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19235. }
  19236. else {
  19237. if (this._transformToBoneReferal) {
  19238. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19239. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19240. }
  19241. else {
  19242. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19243. }
  19244. }
  19245. this._markSyncedWithParent();
  19246. }
  19247. else {
  19248. this._worldMatrix.copyFrom(this._localWorld);
  19249. }
  19250. // Post multiply inverse of pivotMatrix
  19251. if (this._postMultiplyPivotMatrix) {
  19252. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19253. }
  19254. // Normal matrix
  19255. if (!this.ignoreNonUniformScaling) {
  19256. if (this.scaling.isNonUniform) {
  19257. this._updateNonUniformScalingState(true);
  19258. }
  19259. else if (this.parent && this.parent._nonUniformScaling) {
  19260. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19261. }
  19262. else {
  19263. this._updateNonUniformScalingState(false);
  19264. }
  19265. }
  19266. else {
  19267. this._updateNonUniformScalingState(false);
  19268. }
  19269. this._afterComputeWorldMatrix();
  19270. // Absolute position
  19271. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19272. // Callbacks
  19273. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19274. if (!this._poseMatrix) {
  19275. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19276. }
  19277. // Cache the determinant
  19278. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19279. return this._worldMatrix;
  19280. };
  19281. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19282. };
  19283. /**
  19284. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19285. * @param func: callback function to add
  19286. *
  19287. * Returns the TransformNode.
  19288. */
  19289. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19290. this.onAfterWorldMatrixUpdateObservable.add(func);
  19291. return this;
  19292. };
  19293. /**
  19294. * Removes a registered callback function.
  19295. * Returns the TransformNode.
  19296. */
  19297. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19298. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19299. return this;
  19300. };
  19301. /**
  19302. * Clone the current transform node
  19303. * Returns the new transform node
  19304. * @param name Name of the new clone
  19305. * @param newParent New parent for the clone
  19306. * @param doNotCloneChildren Do not clone children hierarchy
  19307. */
  19308. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19309. var _this = this;
  19310. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19311. result.name = name;
  19312. result.id = name;
  19313. if (newParent) {
  19314. result.parent = newParent;
  19315. }
  19316. if (!doNotCloneChildren) {
  19317. // Children
  19318. var directDescendants = this.getDescendants(true);
  19319. for (var index = 0; index < directDescendants.length; index++) {
  19320. var child = directDescendants[index];
  19321. if (child.clone) {
  19322. child.clone(name + "." + child.name, result);
  19323. }
  19324. }
  19325. }
  19326. return result;
  19327. };
  19328. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19329. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19330. serializationObject.type = this.getClassName();
  19331. // Parent
  19332. if (this.parent) {
  19333. serializationObject.parentId = this.parent.id;
  19334. }
  19335. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19336. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19337. }
  19338. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19339. serializationObject.isEnabled = this.isEnabled();
  19340. // Parent
  19341. if (this.parent) {
  19342. serializationObject.parentId = this.parent.id;
  19343. }
  19344. return serializationObject;
  19345. };
  19346. // Statics
  19347. /**
  19348. * Returns a new TransformNode object parsed from the source provided.
  19349. * The parameter `parsedMesh` is the source.
  19350. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19351. */
  19352. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19353. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19354. if (BABYLON.Tags) {
  19355. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19356. }
  19357. if (parsedTransformNode.localMatrix) {
  19358. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19359. }
  19360. else if (parsedTransformNode.pivotMatrix) {
  19361. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19362. }
  19363. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19364. // Parent
  19365. if (parsedTransformNode.parentId) {
  19366. transformNode._waitingParentId = parsedTransformNode.parentId;
  19367. }
  19368. return transformNode;
  19369. };
  19370. /**
  19371. * Releases resources associated with this transform node.
  19372. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19373. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19374. */
  19375. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19376. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19377. // Animations
  19378. this.getScene().stopAnimation(this);
  19379. // Remove from scene
  19380. this.getScene().removeTransformNode(this);
  19381. this.onAfterWorldMatrixUpdateObservable.clear();
  19382. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19383. };
  19384. // Statics
  19385. TransformNode.BILLBOARDMODE_NONE = 0;
  19386. TransformNode.BILLBOARDMODE_X = 1;
  19387. TransformNode.BILLBOARDMODE_Y = 2;
  19388. TransformNode.BILLBOARDMODE_Z = 4;
  19389. TransformNode.BILLBOARDMODE_ALL = 7;
  19390. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19391. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19392. __decorate([
  19393. BABYLON.serializeAsVector3()
  19394. ], TransformNode.prototype, "_rotation", void 0);
  19395. __decorate([
  19396. BABYLON.serializeAsQuaternion()
  19397. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19398. __decorate([
  19399. BABYLON.serializeAsVector3()
  19400. ], TransformNode.prototype, "_scaling", void 0);
  19401. __decorate([
  19402. BABYLON.serialize()
  19403. ], TransformNode.prototype, "billboardMode", void 0);
  19404. __decorate([
  19405. BABYLON.serialize()
  19406. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19407. __decorate([
  19408. BABYLON.serialize()
  19409. ], TransformNode.prototype, "infiniteDistance", void 0);
  19410. __decorate([
  19411. BABYLON.serialize()
  19412. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19413. __decorate([
  19414. BABYLON.serializeAsVector3()
  19415. ], TransformNode.prototype, "position", void 0);
  19416. return TransformNode;
  19417. }(BABYLON.Node));
  19418. BABYLON.TransformNode = TransformNode;
  19419. })(BABYLON || (BABYLON = {}));
  19420. //# sourceMappingURL=babylon.transformNode.js.map
  19421. var BABYLON;
  19422. (function (BABYLON) {
  19423. /**
  19424. * Class used to store all common mesh properties
  19425. */
  19426. var AbstractMesh = /** @class */ (function (_super) {
  19427. __extends(AbstractMesh, _super);
  19428. // Constructor
  19429. /**
  19430. * Creates a new AbstractMesh
  19431. * @param name defines the name of the mesh
  19432. * @param scene defines the hosting scene
  19433. */
  19434. function AbstractMesh(name, scene) {
  19435. if (scene === void 0) { scene = null; }
  19436. var _this = _super.call(this, name, scene, false) || this;
  19437. _this._facetNb = 0; // facet number
  19438. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19439. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19440. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19441. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19442. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19443. _this._subDiv = {
  19444. max: 1,
  19445. X: 1,
  19446. Y: 1,
  19447. Z: 1
  19448. };
  19449. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19450. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19451. // Events
  19452. /**
  19453. * An event triggered when this mesh collides with another one
  19454. */
  19455. _this.onCollideObservable = new BABYLON.Observable();
  19456. /**
  19457. * An event triggered when the collision's position changes
  19458. */
  19459. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19460. /**
  19461. * An event triggered when material is changed
  19462. */
  19463. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19464. // Properties
  19465. /**
  19466. * Gets or sets the orientation for POV movement & rotation
  19467. */
  19468. _this.definedFacingForward = true;
  19469. /**
  19470. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19471. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19472. * * 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.
  19473. * @see http://doc.babylonjs.com/features/occlusionquery
  19474. */
  19475. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19476. /**
  19477. * 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:
  19478. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19479. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19480. * * 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.
  19481. * @see http://doc.babylonjs.com/features/occlusionquery
  19482. */
  19483. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19484. /**
  19485. * 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.
  19486. * The default value is -1 which means don't break the query and wait till the result
  19487. * @see http://doc.babylonjs.com/features/occlusionquery
  19488. */
  19489. _this.occlusionRetryCount = -1;
  19490. _this._occlusionInternalRetryCounter = 0;
  19491. _this._isOccluded = false;
  19492. _this._isOcclusionQueryInProgress = false;
  19493. _this._visibility = 1.0;
  19494. /** Gets or sets the alpha index used to sort transparent meshes
  19495. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19496. */
  19497. _this.alphaIndex = Number.MAX_VALUE;
  19498. /**
  19499. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19500. */
  19501. _this.isVisible = true;
  19502. /**
  19503. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19504. */
  19505. _this.isPickable = true;
  19506. /**
  19507. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19508. */
  19509. _this.showBoundingBox = false;
  19510. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19511. _this.showSubMeshesBoundingBox = false;
  19512. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19513. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19514. */
  19515. _this.isBlocker = false;
  19516. /**
  19517. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19518. */
  19519. _this.enablePointerMoveEvents = false;
  19520. /**
  19521. * Specifies the rendering group id for this mesh (0 by default)
  19522. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19523. */
  19524. _this.renderingGroupId = 0;
  19525. _this._receiveShadows = false;
  19526. /**
  19527. * Gets or sets a boolean indicating if the outline must be rendered as well
  19528. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19529. */
  19530. _this.renderOutline = false;
  19531. /** Defines color to use when rendering outline */
  19532. _this.outlineColor = BABYLON.Color3.Red();
  19533. /** Define width to use when rendering outline */
  19534. _this.outlineWidth = 0.02;
  19535. /**
  19536. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19537. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19538. */
  19539. _this.renderOverlay = false;
  19540. /** Defines color to use when rendering overlay */
  19541. _this.overlayColor = BABYLON.Color3.Red();
  19542. /** Defines alpha to use when rendering overlay */
  19543. _this.overlayAlpha = 0.5;
  19544. _this._hasVertexAlpha = false;
  19545. _this._useVertexColors = true;
  19546. _this._computeBonesUsingShaders = true;
  19547. _this._numBoneInfluencers = 4;
  19548. _this._applyFog = true;
  19549. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19550. _this.useOctreeForRenderingSelection = true;
  19551. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19552. _this.useOctreeForPicking = true;
  19553. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19554. _this.useOctreeForCollisions = true;
  19555. _this._layerMask = 0x0FFFFFFF;
  19556. /**
  19557. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19558. */
  19559. _this.alwaysSelectAsActiveMesh = false;
  19560. /**
  19561. * Gets or sets the current action manager
  19562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19563. */
  19564. _this.actionManager = null;
  19565. /**
  19566. * Gets or sets impostor used for physic simulation
  19567. * @see http://doc.babylonjs.com/features/physics_engine
  19568. */
  19569. _this.physicsImpostor = null;
  19570. // Collisions
  19571. _this._checkCollisions = false;
  19572. _this._collisionMask = -1;
  19573. _this._collisionGroup = -1;
  19574. /**
  19575. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19576. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19577. */
  19578. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19579. /**
  19580. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19581. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19582. */
  19583. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19584. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19585. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19586. // Edges
  19587. /**
  19588. * Defines edge width used when edgesRenderer is enabled
  19589. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19590. */
  19591. _this.edgesWidth = 1;
  19592. /**
  19593. * Defines edge color used when edgesRenderer is enabled
  19594. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19595. */
  19596. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19597. // Cache
  19598. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19599. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19600. /** @hidden */
  19601. _this._renderId = 0;
  19602. /** @hidden */
  19603. _this._intersectionsInProgress = new Array();
  19604. /** @hidden */
  19605. _this._unIndexed = false;
  19606. /** @hidden */
  19607. _this._lightSources = new Array();
  19608. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19609. if (collidedMesh === void 0) { collidedMesh = null; }
  19610. //TODO move this to the collision coordinator!
  19611. if (_this.getScene().workerCollisions)
  19612. newPosition.multiplyInPlace(_this._collider._radius);
  19613. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19614. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19615. _this.position.addInPlace(_this._diffPositionForCollisions);
  19616. }
  19617. if (collidedMesh) {
  19618. _this.onCollideObservable.notifyObservers(collidedMesh);
  19619. }
  19620. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19621. };
  19622. _this.getScene().addMesh(_this);
  19623. _this._resyncLightSources();
  19624. return _this;
  19625. }
  19626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19627. /**
  19628. * No billboard
  19629. */
  19630. get: function () {
  19631. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19637. /** Billboard on X axis */
  19638. get: function () {
  19639. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19640. },
  19641. enumerable: true,
  19642. configurable: true
  19643. });
  19644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19645. /** Billboard on Y axis */
  19646. get: function () {
  19647. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19653. /** Billboard on Z axis */
  19654. get: function () {
  19655. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19661. /** Billboard on all axes */
  19662. get: function () {
  19663. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19669. /**
  19670. * Gets the number of facets in the mesh
  19671. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19672. */
  19673. get: function () {
  19674. return this._facetNb;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19680. /**
  19681. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19682. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19683. */
  19684. get: function () {
  19685. return this._partitioningSubdivisions;
  19686. },
  19687. set: function (nb) {
  19688. this._partitioningSubdivisions = nb;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19694. /**
  19695. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19696. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19697. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19698. */
  19699. get: function () {
  19700. return this._partitioningBBoxRatio;
  19701. },
  19702. set: function (ratio) {
  19703. this._partitioningBBoxRatio = ratio;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19709. /**
  19710. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19711. * Works only for updatable meshes.
  19712. * Doesn't work with multi-materials
  19713. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19714. */
  19715. get: function () {
  19716. return this._facetDepthSort;
  19717. },
  19718. set: function (sort) {
  19719. this._facetDepthSort = sort;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19725. /**
  19726. * The location (Vector3) where the facet depth sort must be computed from.
  19727. * By default, the active camera position.
  19728. * Used only when facet depth sort is enabled
  19729. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19730. */
  19731. get: function () {
  19732. return this._facetDepthSortFrom;
  19733. },
  19734. set: function (location) {
  19735. this._facetDepthSortFrom = location;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19741. /**
  19742. * gets a boolean indicating if facetData is enabled
  19743. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19744. */
  19745. get: function () {
  19746. return this._facetDataEnabled;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. /** @hidden */
  19752. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19753. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19754. return false;
  19755. }
  19756. this._markSubMeshesAsMiscDirty();
  19757. return true;
  19758. };
  19759. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19760. /** Set a function to call when this mesh collides with another one */
  19761. set: function (callback) {
  19762. if (this._onCollideObserver) {
  19763. this.onCollideObservable.remove(this._onCollideObserver);
  19764. }
  19765. this._onCollideObserver = this.onCollideObservable.add(callback);
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19771. /** Set a function to call when the collision's position changes */
  19772. set: function (callback) {
  19773. if (this._onCollisionPositionChangeObserver) {
  19774. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19775. }
  19776. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19782. /**
  19783. * 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
  19784. * @see http://doc.babylonjs.com/features/occlusionquery
  19785. */
  19786. get: function () {
  19787. return this._isOccluded;
  19788. },
  19789. set: function (value) {
  19790. this._isOccluded = value;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19796. /**
  19797. * Flag to check the progress status of the query
  19798. * @see http://doc.babylonjs.com/features/occlusionquery
  19799. */
  19800. get: function () {
  19801. return this._isOcclusionQueryInProgress;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19807. /**
  19808. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19809. */
  19810. get: function () {
  19811. return this._visibility;
  19812. },
  19813. /**
  19814. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19815. */
  19816. set: function (value) {
  19817. if (this._visibility === value) {
  19818. return;
  19819. }
  19820. this._visibility = value;
  19821. this._markSubMeshesAsMiscDirty();
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(AbstractMesh.prototype, "material", {
  19827. /** Gets or sets current material */
  19828. get: function () {
  19829. return this._material;
  19830. },
  19831. set: function (value) {
  19832. if (this._material === value) {
  19833. return;
  19834. }
  19835. this._material = value;
  19836. if (this.onMaterialChangedObservable.hasObservers) {
  19837. this.onMaterialChangedObservable.notifyObservers(this);
  19838. }
  19839. if (!this.subMeshes) {
  19840. return;
  19841. }
  19842. this._unBindEffect();
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19848. /**
  19849. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19850. * @see http://doc.babylonjs.com/babylon101/shadows
  19851. */
  19852. get: function () {
  19853. return this._receiveShadows;
  19854. },
  19855. set: function (value) {
  19856. if (this._receiveShadows === value) {
  19857. return;
  19858. }
  19859. this._receiveShadows = value;
  19860. this._markSubMeshesAsLightDirty();
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19866. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19867. get: function () {
  19868. return this._hasVertexAlpha;
  19869. },
  19870. set: function (value) {
  19871. if (this._hasVertexAlpha === value) {
  19872. return;
  19873. }
  19874. this._hasVertexAlpha = value;
  19875. this._markSubMeshesAsAttributesDirty();
  19876. this._markSubMeshesAsMiscDirty();
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19882. /** 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) */
  19883. get: function () {
  19884. return this._useVertexColors;
  19885. },
  19886. set: function (value) {
  19887. if (this._useVertexColors === value) {
  19888. return;
  19889. }
  19890. this._useVertexColors = value;
  19891. this._markSubMeshesAsAttributesDirty();
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19897. /**
  19898. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19899. */
  19900. get: function () {
  19901. return this._computeBonesUsingShaders;
  19902. },
  19903. set: function (value) {
  19904. if (this._computeBonesUsingShaders === value) {
  19905. return;
  19906. }
  19907. this._computeBonesUsingShaders = value;
  19908. this._markSubMeshesAsAttributesDirty();
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19914. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19915. get: function () {
  19916. return this._numBoneInfluencers;
  19917. },
  19918. set: function (value) {
  19919. if (this._numBoneInfluencers === value) {
  19920. return;
  19921. }
  19922. this._numBoneInfluencers = value;
  19923. this._markSubMeshesAsAttributesDirty();
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19929. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19930. get: function () {
  19931. return this._applyFog;
  19932. },
  19933. set: function (value) {
  19934. if (this._applyFog === value) {
  19935. return;
  19936. }
  19937. this._applyFog = value;
  19938. this._markSubMeshesAsMiscDirty();
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19944. /**
  19945. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19946. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19947. */
  19948. get: function () {
  19949. return this._layerMask;
  19950. },
  19951. set: function (value) {
  19952. if (value === this._layerMask) {
  19953. return;
  19954. }
  19955. this._layerMask = value;
  19956. this._resyncLightSources();
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19962. /**
  19963. * Gets or sets a collision mask used to mask collisions (default is -1).
  19964. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19965. */
  19966. get: function () {
  19967. return this._collisionMask;
  19968. },
  19969. set: function (mask) {
  19970. this._collisionMask = !isNaN(mask) ? mask : -1;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19976. /**
  19977. * Gets or sets the current collision group mask (-1 by default).
  19978. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19979. */
  19980. get: function () {
  19981. return this._collisionGroup;
  19982. },
  19983. set: function (mask) {
  19984. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19990. /** @hidden */
  19991. get: function () {
  19992. return null;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19998. get: function () {
  19999. return this._skeleton;
  20000. },
  20001. /**
  20002. * Gets or sets a skeleton to apply skining transformations
  20003. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20004. */
  20005. set: function (value) {
  20006. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20007. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20008. }
  20009. if (value && value.needInitialSkinMatrix) {
  20010. value._registerMeshWithPoseMatrix(this);
  20011. }
  20012. this._skeleton = value;
  20013. if (!this._skeleton) {
  20014. this._bonesTransformMatrices = null;
  20015. }
  20016. this._markSubMeshesAsAttributesDirty();
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Returns the string "AbstractMesh"
  20023. * @returns "AbstractMesh"
  20024. */
  20025. AbstractMesh.prototype.getClassName = function () {
  20026. return "AbstractMesh";
  20027. };
  20028. /**
  20029. * Gets a string representation of the current mesh
  20030. * @param fullDetails defines a boolean indicating if full details must be included
  20031. * @returns a string representation of the current mesh
  20032. */
  20033. AbstractMesh.prototype.toString = function (fullDetails) {
  20034. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20035. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20036. if (this._skeleton) {
  20037. ret += ", skeleton: " + this._skeleton.name;
  20038. }
  20039. if (fullDetails) {
  20040. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20041. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20042. }
  20043. return ret;
  20044. };
  20045. /** @hidden */
  20046. AbstractMesh.prototype._rebuild = function () {
  20047. if (this._occlusionQuery) {
  20048. this._occlusionQuery = null;
  20049. }
  20050. if (this._edgesRenderer) {
  20051. this._edgesRenderer._rebuild();
  20052. }
  20053. if (!this.subMeshes) {
  20054. return;
  20055. }
  20056. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20057. var subMesh = _a[_i];
  20058. subMesh._rebuild();
  20059. }
  20060. };
  20061. /** @hidden */
  20062. AbstractMesh.prototype._resyncLightSources = function () {
  20063. this._lightSources.length = 0;
  20064. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20065. var light = _a[_i];
  20066. if (!light.isEnabled()) {
  20067. continue;
  20068. }
  20069. if (light.canAffectMesh(this)) {
  20070. this._lightSources.push(light);
  20071. }
  20072. }
  20073. this._markSubMeshesAsLightDirty();
  20074. };
  20075. /** @hidden */
  20076. AbstractMesh.prototype._resyncLighSource = function (light) {
  20077. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20078. var index = this._lightSources.indexOf(light);
  20079. if (index === -1) {
  20080. if (!isIn) {
  20081. return;
  20082. }
  20083. this._lightSources.push(light);
  20084. }
  20085. else {
  20086. if (isIn) {
  20087. return;
  20088. }
  20089. this._lightSources.splice(index, 1);
  20090. }
  20091. this._markSubMeshesAsLightDirty();
  20092. };
  20093. /** @hidden */
  20094. AbstractMesh.prototype._unBindEffect = function () {
  20095. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20096. var subMesh = _a[_i];
  20097. subMesh.setEffect(null);
  20098. }
  20099. };
  20100. /** @hidden */
  20101. AbstractMesh.prototype._removeLightSource = function (light) {
  20102. var index = this._lightSources.indexOf(light);
  20103. if (index === -1) {
  20104. return;
  20105. }
  20106. this._lightSources.splice(index, 1);
  20107. this._markSubMeshesAsLightDirty();
  20108. };
  20109. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20110. if (!this.subMeshes) {
  20111. return;
  20112. }
  20113. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20114. var subMesh = _a[_i];
  20115. if (subMesh._materialDefines) {
  20116. func(subMesh._materialDefines);
  20117. }
  20118. }
  20119. };
  20120. /** @hidden */
  20121. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20122. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20123. };
  20124. /** @hidden */
  20125. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20126. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20127. };
  20128. /** @hidden */
  20129. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20130. if (!this.subMeshes) {
  20131. return;
  20132. }
  20133. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20134. var subMesh = _a[_i];
  20135. var material = subMesh.getMaterial();
  20136. if (material) {
  20137. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20138. }
  20139. }
  20140. };
  20141. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20142. /**
  20143. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20144. */
  20145. get: function () {
  20146. return this._scaling;
  20147. },
  20148. set: function (newScaling) {
  20149. this._scaling = newScaling;
  20150. if (this.physicsImpostor) {
  20151. this.physicsImpostor.forceUpdate();
  20152. }
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. // Methods
  20158. /**
  20159. * Disables the mesh edge rendering mode
  20160. * @returns the currentAbstractMesh
  20161. */
  20162. AbstractMesh.prototype.disableEdgesRendering = function () {
  20163. if (this._edgesRenderer) {
  20164. this._edgesRenderer.dispose();
  20165. this._edgesRenderer = null;
  20166. }
  20167. return this;
  20168. };
  20169. /**
  20170. * Enables the edge rendering mode on the mesh.
  20171. * This mode makes the mesh edges visible
  20172. * @param epsilon defines the maximal distance between two angles to detect a face
  20173. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20174. * @returns the currentAbstractMesh
  20175. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20176. */
  20177. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20178. if (epsilon === void 0) { epsilon = 0.95; }
  20179. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20180. this.disableEdgesRendering();
  20181. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20182. return this;
  20183. };
  20184. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20185. /**
  20186. * Gets the edgesRenderer associated with the mesh
  20187. */
  20188. get: function () {
  20189. return this._edgesRenderer;
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20195. /**
  20196. * Returns true if the mesh is blocked. Implemented by child classes
  20197. */
  20198. get: function () {
  20199. return false;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. /**
  20205. * Returns the mesh itself by default. Implemented by child classes
  20206. * @param camera defines the camera to use to pick the right LOD level
  20207. * @returns the currentAbstractMesh
  20208. */
  20209. AbstractMesh.prototype.getLOD = function (camera) {
  20210. return this;
  20211. };
  20212. /**
  20213. * Returns 0 by default. Implemented by child classes
  20214. * @returns an integer
  20215. */
  20216. AbstractMesh.prototype.getTotalVertices = function () {
  20217. return 0;
  20218. };
  20219. /**
  20220. * Returns null by default. Implemented by child classes
  20221. * @returns null
  20222. */
  20223. AbstractMesh.prototype.getIndices = function () {
  20224. return null;
  20225. };
  20226. /**
  20227. * Returns the array of the requested vertex data kind. Implemented by child classes
  20228. * @param kind defines the vertex data kind to use
  20229. * @returns null
  20230. */
  20231. AbstractMesh.prototype.getVerticesData = function (kind) {
  20232. return null;
  20233. };
  20234. /**
  20235. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20236. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20237. * Note that a new underlying VertexBuffer object is created each call.
  20238. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20239. * @param kind defines vertex data kind:
  20240. * * BABYLON.VertexBuffer.PositionKind
  20241. * * BABYLON.VertexBuffer.UVKind
  20242. * * BABYLON.VertexBuffer.UV2Kind
  20243. * * BABYLON.VertexBuffer.UV3Kind
  20244. * * BABYLON.VertexBuffer.UV4Kind
  20245. * * BABYLON.VertexBuffer.UV5Kind
  20246. * * BABYLON.VertexBuffer.UV6Kind
  20247. * * BABYLON.VertexBuffer.ColorKind
  20248. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20249. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20250. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20251. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20252. * @param data defines the data source
  20253. * @param updatable defines if the data must be flagged as updatable (or static)
  20254. * @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
  20255. * @returns the current mesh
  20256. */
  20257. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20258. return this;
  20259. };
  20260. /**
  20261. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20262. * If the mesh has no geometry, it is simply returned as it is.
  20263. * @param kind defines vertex data kind:
  20264. * * BABYLON.VertexBuffer.PositionKind
  20265. * * BABYLON.VertexBuffer.UVKind
  20266. * * BABYLON.VertexBuffer.UV2Kind
  20267. * * BABYLON.VertexBuffer.UV3Kind
  20268. * * BABYLON.VertexBuffer.UV4Kind
  20269. * * BABYLON.VertexBuffer.UV5Kind
  20270. * * BABYLON.VertexBuffer.UV6Kind
  20271. * * BABYLON.VertexBuffer.ColorKind
  20272. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20273. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20274. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20275. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20276. * @param data defines the data source
  20277. * @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
  20278. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20279. * @returns the current mesh
  20280. */
  20281. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20282. return this;
  20283. };
  20284. /**
  20285. * Sets the mesh indices,
  20286. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20287. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20288. * @param totalVertices Defines the total number of vertices
  20289. * @returns the current mesh
  20290. */
  20291. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20292. return this;
  20293. };
  20294. /**
  20295. * Gets a boolean indicating if specific vertex data is present
  20296. * @param kind defines the vertex data kind to use
  20297. * @returns true is data kind is present
  20298. */
  20299. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20300. return false;
  20301. };
  20302. /**
  20303. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20304. * @returns a BoundingInfo
  20305. */
  20306. AbstractMesh.prototype.getBoundingInfo = function () {
  20307. if (this._masterMesh) {
  20308. return this._masterMesh.getBoundingInfo();
  20309. }
  20310. if (!this._boundingInfo) {
  20311. // this._boundingInfo is being created here
  20312. this._updateBoundingInfo();
  20313. }
  20314. // cannot be null.
  20315. return this._boundingInfo;
  20316. };
  20317. /**
  20318. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20319. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20320. * @returns the current mesh
  20321. */
  20322. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20323. if (includeDescendants === void 0) { includeDescendants = true; }
  20324. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20325. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20326. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20327. if (maxDimension === 0) {
  20328. return this;
  20329. }
  20330. var scale = 1 / maxDimension;
  20331. this.scaling.scaleInPlace(scale);
  20332. return this;
  20333. };
  20334. /**
  20335. * Overwrite the current bounding info
  20336. * @param boundingInfo defines the new bounding info
  20337. * @returns the current mesh
  20338. */
  20339. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20340. this._boundingInfo = boundingInfo;
  20341. return this;
  20342. };
  20343. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20344. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20345. get: function () {
  20346. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20347. },
  20348. enumerable: true,
  20349. configurable: true
  20350. });
  20351. /** @hidden */
  20352. AbstractMesh.prototype._preActivate = function () {
  20353. };
  20354. /** @hidden */
  20355. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20356. };
  20357. /** @hidden */
  20358. AbstractMesh.prototype._activate = function (renderId) {
  20359. this._renderId = renderId;
  20360. };
  20361. /**
  20362. * Gets the current world matrix
  20363. * @returns a Matrix
  20364. */
  20365. AbstractMesh.prototype.getWorldMatrix = function () {
  20366. if (this._masterMesh) {
  20367. return this._masterMesh.getWorldMatrix();
  20368. }
  20369. return _super.prototype.getWorldMatrix.call(this);
  20370. };
  20371. /** @hidden */
  20372. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20373. if (this._masterMesh) {
  20374. return this._masterMesh._getWorldMatrixDeterminant();
  20375. }
  20376. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20377. };
  20378. // ================================== Point of View Movement =================================
  20379. /**
  20380. * Perform relative position change from the point of view of behind the front of the mesh.
  20381. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20382. * Supports definition of mesh facing forward or backward
  20383. * @param amountRight defines the distance on the right axis
  20384. * @param amountUp defines the distance on the up axis
  20385. * @param amountForward defines the distance on the forward axis
  20386. * @returns the current mesh
  20387. */
  20388. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20389. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20390. return this;
  20391. };
  20392. /**
  20393. * Calculate relative position change from the point of view of behind the front of the mesh.
  20394. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20395. * Supports definition of mesh facing forward or backward
  20396. * @param amountRight defines the distance on the right axis
  20397. * @param amountUp defines the distance on the up axis
  20398. * @param amountForward defines the distance on the forward axis
  20399. * @returns the new displacement vector
  20400. */
  20401. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20402. var rotMatrix = new BABYLON.Matrix();
  20403. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20404. rotQuaternion.toRotationMatrix(rotMatrix);
  20405. var translationDelta = BABYLON.Vector3.Zero();
  20406. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20408. return translationDelta;
  20409. };
  20410. // ================================== Point of View Rotation =================================
  20411. /**
  20412. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20413. * Supports definition of mesh facing forward or backward
  20414. * @param flipBack defines the flip
  20415. * @param twirlClockwise defines the twirl
  20416. * @param tiltRight defines the tilt
  20417. * @returns the current mesh
  20418. */
  20419. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20420. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20421. return this;
  20422. };
  20423. /**
  20424. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20425. * Supports definition of mesh facing forward or backward.
  20426. * @param flipBack defines the flip
  20427. * @param twirlClockwise defines the twirl
  20428. * @param tiltRight defines the tilt
  20429. * @returns the new rotation vector
  20430. */
  20431. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20432. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20433. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20434. };
  20435. /**
  20436. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20437. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20438. * @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
  20439. * @returns the new bounding vectors
  20440. */
  20441. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20442. if (includeDescendants === void 0) { includeDescendants = true; }
  20443. if (predicate === void 0) { predicate = null; }
  20444. // Ensures that all world matrix will be recomputed.
  20445. this.getScene().incrementRenderId();
  20446. this.computeWorldMatrix(true);
  20447. var min;
  20448. var max;
  20449. var boundingInfo = this.getBoundingInfo();
  20450. if (!this.subMeshes) {
  20451. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20452. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20453. }
  20454. else {
  20455. min = boundingInfo.boundingBox.minimumWorld;
  20456. max = boundingInfo.boundingBox.maximumWorld;
  20457. }
  20458. if (includeDescendants) {
  20459. var descendants = this.getDescendants(false);
  20460. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20461. var descendant = descendants_1[_i];
  20462. var childMesh = descendant;
  20463. childMesh.computeWorldMatrix(true);
  20464. // Filters meshes based on custom predicate function.
  20465. if (predicate && !predicate(childMesh)) {
  20466. continue;
  20467. }
  20468. //make sure we have the needed params to get mix and max
  20469. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20470. continue;
  20471. }
  20472. var childBoundingInfo = childMesh.getBoundingInfo();
  20473. var boundingBox = childBoundingInfo.boundingBox;
  20474. var minBox = boundingBox.minimumWorld;
  20475. var maxBox = boundingBox.maximumWorld;
  20476. BABYLON.Tools.CheckExtends(minBox, min, max);
  20477. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20478. }
  20479. }
  20480. return {
  20481. min: min,
  20482. max: max
  20483. };
  20484. };
  20485. /** @hidden */
  20486. AbstractMesh.prototype._updateBoundingInfo = function () {
  20487. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20488. this._boundingInfo.update(this.worldMatrixFromCache);
  20489. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20490. return this;
  20491. };
  20492. /** @hidden */
  20493. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20494. if (!this.subMeshes) {
  20495. return this;
  20496. }
  20497. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20498. var subMesh = this.subMeshes[subIndex];
  20499. if (!subMesh.IsGlobal) {
  20500. subMesh.updateBoundingInfo(matrix);
  20501. }
  20502. }
  20503. return this;
  20504. };
  20505. /** @hidden */
  20506. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20507. // Bounding info
  20508. this._updateBoundingInfo();
  20509. };
  20510. /**
  20511. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20512. * A mesh is in the frustum if its bounding box intersects the frustum
  20513. * @param frustumPlanes defines the frustum to test
  20514. * @returns true if the mesh is in the frustum planes
  20515. */
  20516. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20517. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20518. };
  20519. /**
  20520. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20521. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20522. * @param frustumPlanes defines the frustum to test
  20523. * @returns true if the mesh is completely in the frustum planes
  20524. */
  20525. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20526. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20527. };
  20528. /**
  20529. * True if the mesh intersects another mesh or a SolidParticle object
  20530. * @param mesh defines a target mesh or SolidParticle to test
  20531. * @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)
  20532. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20533. * @returns true if there is an intersection
  20534. */
  20535. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20536. if (precise === void 0) { precise = false; }
  20537. if (!this._boundingInfo || !mesh._boundingInfo) {
  20538. return false;
  20539. }
  20540. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20541. return true;
  20542. }
  20543. if (includeDescendants) {
  20544. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20545. var child = _a[_i];
  20546. if (child.intersectsMesh(mesh, precise, true)) {
  20547. return true;
  20548. }
  20549. }
  20550. }
  20551. return false;
  20552. };
  20553. /**
  20554. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20555. * @param point defines the point to test
  20556. * @returns true if there is an intersection
  20557. */
  20558. AbstractMesh.prototype.intersectsPoint = function (point) {
  20559. if (!this._boundingInfo) {
  20560. return false;
  20561. }
  20562. return this._boundingInfo.intersectsPoint(point);
  20563. };
  20564. /**
  20565. * Gets the current physics impostor
  20566. * @see http://doc.babylonjs.com/features/physics_engine
  20567. * @returns a physics impostor or null
  20568. */
  20569. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20570. return this.physicsImpostor;
  20571. };
  20572. /**
  20573. * Gets the position of the current mesh in camera space
  20574. * @param camera defines the camera to use
  20575. * @returns a position
  20576. */
  20577. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20578. if (camera === void 0) { camera = null; }
  20579. if (!camera) {
  20580. camera = this.getScene().activeCamera;
  20581. }
  20582. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20583. };
  20584. /**
  20585. * Returns the distance from the mesh to the active camera
  20586. * @param camera defines the camera to use
  20587. * @returns the distance
  20588. */
  20589. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20590. if (camera === void 0) { camera = null; }
  20591. if (!camera) {
  20592. camera = this.getScene().activeCamera;
  20593. }
  20594. return this.absolutePosition.subtract(camera.position).length();
  20595. };
  20596. /**
  20597. * Apply a physic impulse to the mesh
  20598. * @param force defines the force to apply
  20599. * @param contactPoint defines where to apply the force
  20600. * @returns the current mesh
  20601. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20602. */
  20603. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20604. if (!this.physicsImpostor) {
  20605. return this;
  20606. }
  20607. this.physicsImpostor.applyImpulse(force, contactPoint);
  20608. return this;
  20609. };
  20610. /**
  20611. * Creates a physic joint between two meshes
  20612. * @param otherMesh defines the other mesh to use
  20613. * @param pivot1 defines the pivot to use on this mesh
  20614. * @param pivot2 defines the pivot to use on the other mesh
  20615. * @param options defines additional options (can be plugin dependent)
  20616. * @returns the current mesh
  20617. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20618. */
  20619. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20620. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20621. return this;
  20622. }
  20623. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20624. mainPivot: pivot1,
  20625. connectedPivot: pivot2,
  20626. nativeParams: options
  20627. });
  20628. return this;
  20629. };
  20630. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20631. // Collisions
  20632. /**
  20633. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20634. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20635. */
  20636. get: function () {
  20637. return this._checkCollisions;
  20638. },
  20639. set: function (collisionEnabled) {
  20640. this._checkCollisions = collisionEnabled;
  20641. if (this.getScene().workerCollisions) {
  20642. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20643. }
  20644. },
  20645. enumerable: true,
  20646. configurable: true
  20647. });
  20648. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20649. /**
  20650. * Gets Collider object used to compute collisions (not physics)
  20651. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20652. */
  20653. get: function () {
  20654. return this._collider;
  20655. },
  20656. enumerable: true,
  20657. configurable: true
  20658. });
  20659. /**
  20660. * Move the mesh using collision engine
  20661. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20662. * @param displacement defines the requested displacement vector
  20663. * @returns the current mesh
  20664. */
  20665. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20666. var globalPosition = this.getAbsolutePosition();
  20667. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20668. if (!this._collider) {
  20669. this._collider = new BABYLON.Collider();
  20670. }
  20671. this._collider._radius = this.ellipsoid;
  20672. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20673. return this;
  20674. };
  20675. // Submeshes octree
  20676. /**
  20677. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20678. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20679. * @param maxCapacity defines the maximum size of each block (64 by default)
  20680. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20681. * @returns the new octree
  20682. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20683. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20684. */
  20685. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20686. if (maxCapacity === void 0) { maxCapacity = 64; }
  20687. if (maxDepth === void 0) { maxDepth = 2; }
  20688. if (!this._submeshesOctree) {
  20689. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20690. }
  20691. this.computeWorldMatrix(true);
  20692. var boundingInfo = this.getBoundingInfo();
  20693. // Update octree
  20694. var bbox = boundingInfo.boundingBox;
  20695. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20696. return this._submeshesOctree;
  20697. };
  20698. // Collisions
  20699. /** @hidden */
  20700. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20701. this._generatePointsArray();
  20702. if (!this._positions) {
  20703. return this;
  20704. }
  20705. // Transformation
  20706. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20707. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20708. subMesh._lastColliderWorldVertices = [];
  20709. subMesh._trianglePlanes = [];
  20710. var start = subMesh.verticesStart;
  20711. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20712. for (var i = start; i < end; i++) {
  20713. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20714. }
  20715. }
  20716. // Collide
  20717. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20718. if (collider.collisionFound) {
  20719. collider.collidedMesh = this;
  20720. }
  20721. return this;
  20722. };
  20723. /** @hidden */
  20724. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20725. var subMeshes;
  20726. var len;
  20727. // Octrees
  20728. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20729. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20730. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20731. len = intersections.length;
  20732. subMeshes = intersections.data;
  20733. }
  20734. else {
  20735. subMeshes = this.subMeshes;
  20736. len = subMeshes.length;
  20737. }
  20738. for (var index = 0; index < len; index++) {
  20739. var subMesh = subMeshes[index];
  20740. // Bounding test
  20741. if (len > 1 && !subMesh._checkCollision(collider))
  20742. continue;
  20743. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20744. }
  20745. return this;
  20746. };
  20747. /** @hidden */
  20748. AbstractMesh.prototype._checkCollision = function (collider) {
  20749. // Bounding box test
  20750. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20751. return this;
  20752. // Transformation matrix
  20753. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20754. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20755. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20756. return this;
  20757. };
  20758. // Picking
  20759. /** @hidden */
  20760. AbstractMesh.prototype._generatePointsArray = function () {
  20761. return false;
  20762. };
  20763. /**
  20764. * Checks if the passed Ray intersects with the mesh
  20765. * @param ray defines the ray to use
  20766. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20767. * @returns the picking info
  20768. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20769. */
  20770. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20771. var pickingInfo = new BABYLON.PickingInfo();
  20772. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20773. return pickingInfo;
  20774. }
  20775. if (!this._generatePointsArray()) {
  20776. return pickingInfo;
  20777. }
  20778. var intersectInfo = null;
  20779. // Octrees
  20780. var subMeshes;
  20781. var len;
  20782. if (this._submeshesOctree && this.useOctreeForPicking) {
  20783. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20784. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20785. len = intersections.length;
  20786. subMeshes = intersections.data;
  20787. }
  20788. else {
  20789. subMeshes = this.subMeshes;
  20790. len = subMeshes.length;
  20791. }
  20792. for (var index = 0; index < len; index++) {
  20793. var subMesh = subMeshes[index];
  20794. // Bounding test
  20795. if (len > 1 && !subMesh.canIntersects(ray))
  20796. continue;
  20797. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20798. if (currentIntersectInfo) {
  20799. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20800. intersectInfo = currentIntersectInfo;
  20801. intersectInfo.subMeshId = index;
  20802. if (fastCheck) {
  20803. break;
  20804. }
  20805. }
  20806. }
  20807. }
  20808. if (intersectInfo) {
  20809. // Get picked point
  20810. var world = this.getWorldMatrix();
  20811. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20812. var direction = ray.direction.clone();
  20813. direction = direction.scale(intersectInfo.distance);
  20814. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20815. var pickedPoint = worldOrigin.add(worldDirection);
  20816. // Return result
  20817. pickingInfo.hit = true;
  20818. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20819. pickingInfo.pickedPoint = pickedPoint;
  20820. pickingInfo.pickedMesh = this;
  20821. pickingInfo.bu = intersectInfo.bu || 0;
  20822. pickingInfo.bv = intersectInfo.bv || 0;
  20823. pickingInfo.faceId = intersectInfo.faceId;
  20824. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20825. return pickingInfo;
  20826. }
  20827. return pickingInfo;
  20828. };
  20829. /**
  20830. * Clones the current mesh
  20831. * @param name defines the mesh name
  20832. * @param newParent defines the new mesh parent
  20833. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20834. * @returns the new mesh
  20835. */
  20836. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20837. return null;
  20838. };
  20839. /**
  20840. * Disposes all the submeshes of the current meshnp
  20841. * @returns the current mesh
  20842. */
  20843. AbstractMesh.prototype.releaseSubMeshes = function () {
  20844. if (this.subMeshes) {
  20845. while (this.subMeshes.length) {
  20846. this.subMeshes[0].dispose();
  20847. }
  20848. }
  20849. else {
  20850. this.subMeshes = new Array();
  20851. }
  20852. return this;
  20853. };
  20854. /**
  20855. * Releases resources associated with this abstract mesh.
  20856. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20857. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20858. */
  20859. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20860. var _this = this;
  20861. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20862. var index;
  20863. // Smart Array Retainers.
  20864. this.getScene().freeActiveMeshes();
  20865. this.getScene().freeRenderingGroups();
  20866. // Action manager
  20867. if (this.actionManager !== undefined && this.actionManager !== null) {
  20868. this.actionManager.dispose();
  20869. this.actionManager = null;
  20870. }
  20871. // Skeleton
  20872. this._skeleton = null;
  20873. // Physics
  20874. if (this.physicsImpostor) {
  20875. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20876. }
  20877. // Intersections in progress
  20878. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20879. var other = this._intersectionsInProgress[index];
  20880. var pos = other._intersectionsInProgress.indexOf(this);
  20881. other._intersectionsInProgress.splice(pos, 1);
  20882. }
  20883. this._intersectionsInProgress = [];
  20884. // Lights
  20885. var lights = this.getScene().lights;
  20886. lights.forEach(function (light) {
  20887. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20888. if (meshIndex !== -1) {
  20889. light.includedOnlyMeshes.splice(meshIndex, 1);
  20890. }
  20891. meshIndex = light.excludedMeshes.indexOf(_this);
  20892. if (meshIndex !== -1) {
  20893. light.excludedMeshes.splice(meshIndex, 1);
  20894. }
  20895. // Shadow generators
  20896. var generator = light.getShadowGenerator();
  20897. if (generator) {
  20898. var shadowMap = generator.getShadowMap();
  20899. if (shadowMap && shadowMap.renderList) {
  20900. meshIndex = shadowMap.renderList.indexOf(_this);
  20901. if (meshIndex !== -1) {
  20902. shadowMap.renderList.splice(meshIndex, 1);
  20903. }
  20904. }
  20905. }
  20906. });
  20907. // Edges
  20908. if (this._edgesRenderer) {
  20909. this._edgesRenderer.dispose();
  20910. this._edgesRenderer = null;
  20911. }
  20912. // SubMeshes
  20913. if (this.getClassName() !== "InstancedMesh") {
  20914. this.releaseSubMeshes();
  20915. }
  20916. // Octree
  20917. var sceneOctree = this.getScene().selectionOctree;
  20918. if (sceneOctree !== undefined && sceneOctree !== null) {
  20919. var index = sceneOctree.dynamicContent.indexOf(this);
  20920. if (index !== -1) {
  20921. sceneOctree.dynamicContent.splice(index, 1);
  20922. }
  20923. }
  20924. // Query
  20925. var engine = this.getScene().getEngine();
  20926. if (this._occlusionQuery) {
  20927. this._isOcclusionQueryInProgress = false;
  20928. engine.deleteQuery(this._occlusionQuery);
  20929. this._occlusionQuery = null;
  20930. }
  20931. // Engine
  20932. engine.wipeCaches();
  20933. // Remove from scene
  20934. this.getScene().removeMesh(this);
  20935. if (disposeMaterialAndTextures) {
  20936. if (this.material) {
  20937. this.material.dispose(false, true);
  20938. }
  20939. }
  20940. if (!doNotRecurse) {
  20941. // Particles
  20942. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20943. if (this.getScene().particleSystems[index].emitter === this) {
  20944. this.getScene().particleSystems[index].dispose();
  20945. index--;
  20946. }
  20947. }
  20948. }
  20949. // facet data
  20950. if (this._facetDataEnabled) {
  20951. this.disableFacetData();
  20952. }
  20953. this.onAfterWorldMatrixUpdateObservable.clear();
  20954. this.onCollideObservable.clear();
  20955. this.onCollisionPositionChangeObservable.clear();
  20956. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20957. };
  20958. /**
  20959. * Adds the passed mesh as a child to the current mesh
  20960. * @param mesh defines the child mesh
  20961. * @returns the current mesh
  20962. */
  20963. AbstractMesh.prototype.addChild = function (mesh) {
  20964. mesh.setParent(this);
  20965. return this;
  20966. };
  20967. /**
  20968. * Removes the passed mesh from the current mesh children list
  20969. * @param mesh defines the child mesh
  20970. * @returns the current mesh
  20971. */
  20972. AbstractMesh.prototype.removeChild = function (mesh) {
  20973. mesh.setParent(null);
  20974. return this;
  20975. };
  20976. // Facet data
  20977. /** @hidden */
  20978. AbstractMesh.prototype._initFacetData = function () {
  20979. if (!this._facetNormals) {
  20980. this._facetNormals = new Array();
  20981. }
  20982. if (!this._facetPositions) {
  20983. this._facetPositions = new Array();
  20984. }
  20985. if (!this._facetPartitioning) {
  20986. this._facetPartitioning = new Array();
  20987. }
  20988. this._facetNb = (this.getIndices().length / 3) | 0;
  20989. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20990. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20991. for (var f = 0; f < this._facetNb; f++) {
  20992. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20993. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20994. }
  20995. this._facetDataEnabled = true;
  20996. return this;
  20997. };
  20998. /**
  20999. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21000. * This method can be called within the render loop.
  21001. * 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
  21002. * @returns the current mesh
  21003. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21004. */
  21005. AbstractMesh.prototype.updateFacetData = function () {
  21006. if (!this._facetDataEnabled) {
  21007. this._initFacetData();
  21008. }
  21009. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21010. var indices = this.getIndices();
  21011. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21012. var bInfo = this.getBoundingInfo();
  21013. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21014. // init arrays, matrix and sort function on first call
  21015. this._facetDepthSortEnabled = true;
  21016. if (indices instanceof Uint16Array) {
  21017. this._depthSortedIndices = new Uint16Array(indices);
  21018. }
  21019. else if (indices instanceof Uint32Array) {
  21020. this._depthSortedIndices = new Uint32Array(indices);
  21021. }
  21022. else {
  21023. var needs32bits = false;
  21024. for (var i = 0; i < indices.length; i++) {
  21025. if (indices[i] > 65535) {
  21026. needs32bits = true;
  21027. break;
  21028. }
  21029. }
  21030. if (needs32bits) {
  21031. this._depthSortedIndices = new Uint32Array(indices);
  21032. }
  21033. else {
  21034. this._depthSortedIndices = new Uint16Array(indices);
  21035. }
  21036. }
  21037. this._facetDepthSortFunction = function (f1, f2) {
  21038. return (f2.sqDistance - f1.sqDistance);
  21039. };
  21040. if (!this._facetDepthSortFrom) {
  21041. var camera = this.getScene().activeCamera;
  21042. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21043. }
  21044. this._depthSortedFacets = [];
  21045. for (var f = 0; f < this._facetNb; f++) {
  21046. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21047. this._depthSortedFacets.push(depthSortedFacet);
  21048. }
  21049. this._invertedMatrix = BABYLON.Matrix.Identity();
  21050. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21051. }
  21052. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21053. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21054. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21055. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21056. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21057. this._subDiv.max = this._partitioningSubdivisions;
  21058. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21059. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21060. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21061. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21062. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21063. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21064. // set the parameters for ComputeNormals()
  21065. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21066. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21067. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21068. this._facetParameters.bInfo = bInfo;
  21069. this._facetParameters.bbSize = this._bbSize;
  21070. this._facetParameters.subDiv = this._subDiv;
  21071. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21072. this._facetParameters.depthSort = this._facetDepthSort;
  21073. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21074. this.computeWorldMatrix(true);
  21075. this._worldMatrix.invertToRef(this._invertedMatrix);
  21076. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21077. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21078. }
  21079. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21080. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21081. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21082. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21083. var l = (this._depthSortedIndices.length / 3) | 0;
  21084. for (var f = 0; f < l; f++) {
  21085. var sind = this._depthSortedFacets[f].ind;
  21086. this._depthSortedIndices[f * 3] = indices[sind];
  21087. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21088. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21089. }
  21090. this.updateIndices(this._depthSortedIndices);
  21091. }
  21092. return this;
  21093. };
  21094. /**
  21095. * Returns the facetLocalNormals array.
  21096. * The normals are expressed in the mesh local spac
  21097. * @returns an array of Vector3
  21098. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21099. */
  21100. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21101. if (!this._facetNormals) {
  21102. this.updateFacetData();
  21103. }
  21104. return this._facetNormals;
  21105. };
  21106. /**
  21107. * Returns the facetLocalPositions array.
  21108. * The facet positions are expressed in the mesh local space
  21109. * @returns an array of Vector3
  21110. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21111. */
  21112. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21113. if (!this._facetPositions) {
  21114. this.updateFacetData();
  21115. }
  21116. return this._facetPositions;
  21117. };
  21118. /**
  21119. * Returns the facetLocalPartioning array
  21120. * @returns an array of array of numbers
  21121. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21122. */
  21123. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21124. if (!this._facetPartitioning) {
  21125. this.updateFacetData();
  21126. }
  21127. return this._facetPartitioning;
  21128. };
  21129. /**
  21130. * Returns the i-th facet position in the world system.
  21131. * This method allocates a new Vector3 per call
  21132. * @param i defines the facet index
  21133. * @returns a new Vector3
  21134. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21135. */
  21136. AbstractMesh.prototype.getFacetPosition = function (i) {
  21137. var pos = BABYLON.Vector3.Zero();
  21138. this.getFacetPositionToRef(i, pos);
  21139. return pos;
  21140. };
  21141. /**
  21142. * Sets the reference Vector3 with the i-th facet position in the world system
  21143. * @param i defines the facet index
  21144. * @param ref defines the target vector
  21145. * @returns the current mesh
  21146. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21147. */
  21148. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21149. var localPos = (this.getFacetLocalPositions())[i];
  21150. var world = this.getWorldMatrix();
  21151. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21152. return this;
  21153. };
  21154. /**
  21155. * Returns the i-th facet normal in the world system.
  21156. * This method allocates a new Vector3 per call
  21157. * @param i defines the facet index
  21158. * @returns a new Vector3
  21159. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21160. */
  21161. AbstractMesh.prototype.getFacetNormal = function (i) {
  21162. var norm = BABYLON.Vector3.Zero();
  21163. this.getFacetNormalToRef(i, norm);
  21164. return norm;
  21165. };
  21166. /**
  21167. * Sets the reference Vector3 with the i-th facet normal in the world system
  21168. * @param i defines the facet index
  21169. * @param ref defines the target vector
  21170. * @returns the current mesh
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21174. var localNorm = (this.getFacetLocalNormals())[i];
  21175. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21176. return this;
  21177. };
  21178. /**
  21179. * 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)
  21180. * @param x defines x coordinate
  21181. * @param y defines y coordinate
  21182. * @param z defines z coordinate
  21183. * @returns the array of facet indexes
  21184. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21185. */
  21186. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21187. var bInfo = this.getBoundingInfo();
  21188. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21189. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21190. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21191. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21192. return null;
  21193. }
  21194. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21195. };
  21196. /**
  21197. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21198. * @param projected sets as the (x,y,z) world projection on the facet
  21199. * @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
  21200. * @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
  21201. * @param x defines x coordinate
  21202. * @param y defines y coordinate
  21203. * @param z defines z coordinate
  21204. * @returns the face index if found (or null instead)
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21208. if (checkFace === void 0) { checkFace = false; }
  21209. if (facing === void 0) { facing = true; }
  21210. var world = this.getWorldMatrix();
  21211. var invMat = BABYLON.Tmp.Matrix[5];
  21212. world.invertToRef(invMat);
  21213. var invVect = BABYLON.Tmp.Vector3[8];
  21214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21215. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21216. if (projected) {
  21217. // tranform the local computed projected vector to world coordinates
  21218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21219. }
  21220. return closest;
  21221. };
  21222. /**
  21223. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21224. * @param projected sets as the (x,y,z) local projection on the facet
  21225. * @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
  21226. * @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
  21227. * @param x defines x coordinate
  21228. * @param y defines y coordinate
  21229. * @param z defines z coordinate
  21230. * @returns the face index if found (or null instead)
  21231. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21232. */
  21233. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21234. if (checkFace === void 0) { checkFace = false; }
  21235. if (facing === void 0) { facing = true; }
  21236. var closest = null;
  21237. var tmpx = 0.0;
  21238. var tmpy = 0.0;
  21239. var tmpz = 0.0;
  21240. var d = 0.0; // tmp dot facet normal * facet position
  21241. var t0 = 0.0;
  21242. var projx = 0.0;
  21243. var projy = 0.0;
  21244. var projz = 0.0;
  21245. // Get all the facets in the same partitioning block than (x, y, z)
  21246. var facetPositions = this.getFacetLocalPositions();
  21247. var facetNormals = this.getFacetLocalNormals();
  21248. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21249. if (!facetsInBlock) {
  21250. return null;
  21251. }
  21252. // Get the closest facet to (x, y, z)
  21253. var shortest = Number.MAX_VALUE; // init distance vars
  21254. var tmpDistance = shortest;
  21255. var fib; // current facet in the block
  21256. var norm; // current facet normal
  21257. var p0; // current facet barycenter position
  21258. // loop on all the facets in the current partitioning block
  21259. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21260. fib = facetsInBlock[idx];
  21261. norm = facetNormals[fib];
  21262. p0 = facetPositions[fib];
  21263. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21264. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21265. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21266. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21267. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21268. projx = x + norm.x * t0;
  21269. projy = y + norm.y * t0;
  21270. projz = z + norm.z * t0;
  21271. tmpx = projx - x;
  21272. tmpy = projy - y;
  21273. tmpz = projz - z;
  21274. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21275. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21276. shortest = tmpDistance;
  21277. closest = fib;
  21278. if (projected) {
  21279. projected.x = projx;
  21280. projected.y = projy;
  21281. projected.z = projz;
  21282. }
  21283. }
  21284. }
  21285. }
  21286. return closest;
  21287. };
  21288. /**
  21289. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21290. * @returns the parameters
  21291. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21292. */
  21293. AbstractMesh.prototype.getFacetDataParameters = function () {
  21294. return this._facetParameters;
  21295. };
  21296. /**
  21297. * Disables the feature FacetData and frees the related memory
  21298. * @returns the current mesh
  21299. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21300. */
  21301. AbstractMesh.prototype.disableFacetData = function () {
  21302. if (this._facetDataEnabled) {
  21303. this._facetDataEnabled = false;
  21304. this._facetPositions = new Array();
  21305. this._facetNormals = new Array();
  21306. this._facetPartitioning = new Array();
  21307. this._facetParameters = null;
  21308. this._depthSortedIndices = new Uint32Array(0);
  21309. }
  21310. return this;
  21311. };
  21312. /**
  21313. * Updates the AbstractMesh indices array
  21314. * @param indices defines the data source
  21315. * @returns the current mesh
  21316. */
  21317. AbstractMesh.prototype.updateIndices = function (indices) {
  21318. return this;
  21319. };
  21320. /**
  21321. * Creates new normals data for the mesh
  21322. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21323. * @returns the current mesh
  21324. */
  21325. AbstractMesh.prototype.createNormals = function (updatable) {
  21326. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21327. var indices = this.getIndices();
  21328. var normals;
  21329. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21330. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21331. }
  21332. else {
  21333. normals = [];
  21334. }
  21335. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21336. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21337. return this;
  21338. };
  21339. /**
  21340. * Align the mesh with a normal
  21341. * @param normal defines the normal to use
  21342. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21343. * @returns the current mesh
  21344. */
  21345. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21346. if (!upDirection) {
  21347. upDirection = BABYLON.Axis.Y;
  21348. }
  21349. var axisX = BABYLON.Tmp.Vector3[0];
  21350. var axisZ = BABYLON.Tmp.Vector3[1];
  21351. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21352. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21353. if (this.rotationQuaternion) {
  21354. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21355. }
  21356. else {
  21357. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21358. }
  21359. return this;
  21360. };
  21361. /** @hidden */
  21362. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21363. var engine = this.getEngine();
  21364. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21365. this._isOccluded = false;
  21366. return;
  21367. }
  21368. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21369. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21370. if (isOcclusionQueryAvailable) {
  21371. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21372. this._isOcclusionQueryInProgress = false;
  21373. this._occlusionInternalRetryCounter = 0;
  21374. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21375. }
  21376. else {
  21377. this._occlusionInternalRetryCounter++;
  21378. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21379. this._isOcclusionQueryInProgress = false;
  21380. this._occlusionInternalRetryCounter = 0;
  21381. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21382. // if strict continue the last state of the object.
  21383. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21384. }
  21385. else {
  21386. return;
  21387. }
  21388. }
  21389. }
  21390. var scene = this.getScene();
  21391. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21392. if (!this._occlusionQuery) {
  21393. this._occlusionQuery = engine.createQuery();
  21394. }
  21395. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21396. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21397. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21398. this._isOcclusionQueryInProgress = true;
  21399. };
  21400. /** No occlusion */
  21401. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21402. /** Occlusion set to optimisitic */
  21403. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21404. /** Occlusion set to strict */
  21405. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21406. /** Use an accurante occlusion algorithm */
  21407. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21408. /** Use a conservative occlusion algorithm */
  21409. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21410. return AbstractMesh;
  21411. }(BABYLON.TransformNode));
  21412. BABYLON.AbstractMesh = AbstractMesh;
  21413. })(BABYLON || (BABYLON = {}));
  21414. //# sourceMappingURL=babylon.abstractMesh.js.map
  21415. var BABYLON;
  21416. (function (BABYLON) {
  21417. /**
  21418. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21419. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21420. * 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.
  21421. */
  21422. var Light = /** @class */ (function (_super) {
  21423. __extends(Light, _super);
  21424. /**
  21425. * Creates a Light object in the scene.
  21426. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21427. * @param name The firendly name of the light
  21428. * @param scene The scene the light belongs too
  21429. */
  21430. function Light(name, scene) {
  21431. var _this = _super.call(this, name, scene) || this;
  21432. /**
  21433. * Diffuse gives the basic color to an object.
  21434. */
  21435. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21436. /**
  21437. * Specular produces a highlight color on an object.
  21438. * Note: This is note affecting PBR materials.
  21439. */
  21440. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21441. /**
  21442. * Strength of the light.
  21443. * Note: By default it is define in the framework own unit.
  21444. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21445. */
  21446. _this.intensity = 1.0;
  21447. /**
  21448. * Defines how far from the source the light is impacting in scene units.
  21449. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21450. */
  21451. _this.range = Number.MAX_VALUE;
  21452. /**
  21453. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21454. * of light.
  21455. */
  21456. _this._photometricScale = 1.0;
  21457. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21458. _this._radius = 0.00001;
  21459. /**
  21460. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21461. * exceeding the number allowed of the materials.
  21462. */
  21463. _this.renderPriority = 0;
  21464. _this._shadowEnabled = true;
  21465. _this._excludeWithLayerMask = 0;
  21466. _this._includeOnlyWithLayerMask = 0;
  21467. _this._lightmapMode = 0;
  21468. /**
  21469. * @hidden Internal use only.
  21470. */
  21471. _this._excludedMeshesIds = new Array();
  21472. /**
  21473. * @hidden Internal use only.
  21474. */
  21475. _this._includedOnlyMeshesIds = new Array();
  21476. _this.getScene().addLight(_this);
  21477. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21478. _this._buildUniformLayout();
  21479. _this.includedOnlyMeshes = new Array();
  21480. _this.excludedMeshes = new Array();
  21481. _this._resyncMeshes();
  21482. return _this;
  21483. }
  21484. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21485. /**
  21486. * If every light affecting the material is in this lightmapMode,
  21487. * material.lightmapTexture adds or multiplies
  21488. * (depends on material.useLightmapAsShadowmap)
  21489. * after every other light calculations.
  21490. */
  21491. get: function () {
  21492. return Light._LIGHTMAP_DEFAULT;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21498. /**
  21499. * material.lightmapTexture as only diffuse lighting from this light
  21500. * adds only specular lighting from this light
  21501. * adds dynamic shadows
  21502. */
  21503. get: function () {
  21504. return Light._LIGHTMAP_SPECULAR;
  21505. },
  21506. enumerable: true,
  21507. configurable: true
  21508. });
  21509. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21510. /**
  21511. * material.lightmapTexture as only lighting
  21512. * no light calculation from this light
  21513. * only adds dynamic shadows from this light
  21514. */
  21515. get: function () {
  21516. return Light._LIGHTMAP_SHADOWSONLY;
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21522. /**
  21523. * Each light type uses the default quantity according to its type:
  21524. * point/spot lights use luminous intensity
  21525. * directional lights use illuminance
  21526. */
  21527. get: function () {
  21528. return Light._INTENSITYMODE_AUTOMATIC;
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21534. /**
  21535. * lumen (lm)
  21536. */
  21537. get: function () {
  21538. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21544. /**
  21545. * candela (lm/sr)
  21546. */
  21547. get: function () {
  21548. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21554. /**
  21555. * lux (lm/m^2)
  21556. */
  21557. get: function () {
  21558. return Light._INTENSITYMODE_ILLUMINANCE;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21564. /**
  21565. * nit (cd/m^2)
  21566. */
  21567. get: function () {
  21568. return Light._INTENSITYMODE_LUMINANCE;
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21574. /**
  21575. * Light type const id of the point light.
  21576. */
  21577. get: function () {
  21578. return Light._LIGHTTYPEID_POINTLIGHT;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21584. /**
  21585. * Light type const id of the directional light.
  21586. */
  21587. get: function () {
  21588. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21594. /**
  21595. * Light type const id of the spot light.
  21596. */
  21597. get: function () {
  21598. return Light._LIGHTTYPEID_SPOTLIGHT;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21604. /**
  21605. * Light type const id of the hemispheric light.
  21606. */
  21607. get: function () {
  21608. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. Object.defineProperty(Light.prototype, "intensityMode", {
  21614. /**
  21615. * Gets the photometric scale used to interpret the intensity.
  21616. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21617. */
  21618. get: function () {
  21619. return this._intensityMode;
  21620. },
  21621. /**
  21622. * Sets the photometric scale used to interpret the intensity.
  21623. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21624. */
  21625. set: function (value) {
  21626. this._intensityMode = value;
  21627. this._computePhotometricScale();
  21628. },
  21629. enumerable: true,
  21630. configurable: true
  21631. });
  21632. ;
  21633. ;
  21634. Object.defineProperty(Light.prototype, "radius", {
  21635. /**
  21636. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21637. */
  21638. get: function () {
  21639. return this._radius;
  21640. },
  21641. /**
  21642. * sets the light radius used by PBR Materials to simulate soft area lights.
  21643. */
  21644. set: function (value) {
  21645. this._radius = value;
  21646. this._computePhotometricScale();
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. ;
  21652. ;
  21653. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21654. /**
  21655. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21656. * the current shadow generator.
  21657. */
  21658. get: function () {
  21659. return this._shadowEnabled;
  21660. },
  21661. /**
  21662. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21663. * the current shadow generator.
  21664. */
  21665. set: function (value) {
  21666. if (this._shadowEnabled === value) {
  21667. return;
  21668. }
  21669. this._shadowEnabled = value;
  21670. this._markMeshesAsLightDirty();
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21676. /**
  21677. * Gets the only meshes impacted by this light.
  21678. */
  21679. get: function () {
  21680. return this._includedOnlyMeshes;
  21681. },
  21682. /**
  21683. * Sets the only meshes impacted by this light.
  21684. */
  21685. set: function (value) {
  21686. this._includedOnlyMeshes = value;
  21687. this._hookArrayForIncludedOnly(value);
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21693. /**
  21694. * Gets the meshes not impacted by this light.
  21695. */
  21696. get: function () {
  21697. return this._excludedMeshes;
  21698. },
  21699. /**
  21700. * Sets the meshes not impacted by this light.
  21701. */
  21702. set: function (value) {
  21703. this._excludedMeshes = value;
  21704. this._hookArrayForExcluded(value);
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21710. /**
  21711. * Gets the layer id use to find what meshes are not impacted by the light.
  21712. * Inactive if 0
  21713. */
  21714. get: function () {
  21715. return this._excludeWithLayerMask;
  21716. },
  21717. /**
  21718. * Sets the layer id use to find what meshes are not impacted by the light.
  21719. * Inactive if 0
  21720. */
  21721. set: function (value) {
  21722. this._excludeWithLayerMask = value;
  21723. this._resyncMeshes();
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21729. /**
  21730. * Gets the layer id use to find what meshes are impacted by the light.
  21731. * Inactive if 0
  21732. */
  21733. get: function () {
  21734. return this._includeOnlyWithLayerMask;
  21735. },
  21736. /**
  21737. * Sets the layer id use to find what meshes are impacted by the light.
  21738. * Inactive if 0
  21739. */
  21740. set: function (value) {
  21741. this._includeOnlyWithLayerMask = value;
  21742. this._resyncMeshes();
  21743. },
  21744. enumerable: true,
  21745. configurable: true
  21746. });
  21747. Object.defineProperty(Light.prototype, "lightmapMode", {
  21748. /**
  21749. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21750. */
  21751. get: function () {
  21752. return this._lightmapMode;
  21753. },
  21754. /**
  21755. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21756. */
  21757. set: function (value) {
  21758. if (this._lightmapMode === value) {
  21759. return;
  21760. }
  21761. this._lightmapMode = value;
  21762. this._markMeshesAsLightDirty();
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. /**
  21768. * Returns the string "Light".
  21769. * @returns the class name
  21770. */
  21771. Light.prototype.getClassName = function () {
  21772. return "Light";
  21773. };
  21774. /**
  21775. * Converts the light information to a readable string for debug purpose.
  21776. * @param fullDetails Supports for multiple levels of logging within scene loading
  21777. * @returns the human readable light info
  21778. */
  21779. Light.prototype.toString = function (fullDetails) {
  21780. var ret = "Name: " + this.name;
  21781. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21782. if (this.animations) {
  21783. for (var i = 0; i < this.animations.length; i++) {
  21784. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21785. }
  21786. }
  21787. if (fullDetails) {
  21788. }
  21789. return ret;
  21790. };
  21791. /**
  21792. * Set the enabled state of this node.
  21793. * @param value - the new enabled state
  21794. */
  21795. Light.prototype.setEnabled = function (value) {
  21796. _super.prototype.setEnabled.call(this, value);
  21797. this._resyncMeshes();
  21798. };
  21799. /**
  21800. * Returns the Light associated shadow generator if any.
  21801. * @return the associated shadow generator.
  21802. */
  21803. Light.prototype.getShadowGenerator = function () {
  21804. return this._shadowGenerator;
  21805. };
  21806. /**
  21807. * Returns a Vector3, the absolute light position in the World.
  21808. * @returns the world space position of the light
  21809. */
  21810. Light.prototype.getAbsolutePosition = function () {
  21811. return BABYLON.Vector3.Zero();
  21812. };
  21813. /**
  21814. * Specifies if the light will affect the passed mesh.
  21815. * @param mesh The mesh to test against the light
  21816. * @return true the mesh is affected otherwise, false.
  21817. */
  21818. Light.prototype.canAffectMesh = function (mesh) {
  21819. if (!mesh) {
  21820. return true;
  21821. }
  21822. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21823. return false;
  21824. }
  21825. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21826. return false;
  21827. }
  21828. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21829. return false;
  21830. }
  21831. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21832. return false;
  21833. }
  21834. return true;
  21835. };
  21836. /**
  21837. * Computes and Returns the light World matrix.
  21838. * @returns the world matrix
  21839. */
  21840. Light.prototype.getWorldMatrix = function () {
  21841. this._currentRenderId = this.getScene().getRenderId();
  21842. this._childRenderId = this._currentRenderId;
  21843. var worldMatrix = this._getWorldMatrix();
  21844. if (this.parent && this.parent.getWorldMatrix) {
  21845. if (!this._parentedWorldMatrix) {
  21846. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21847. }
  21848. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21849. this._markSyncedWithParent();
  21850. return this._parentedWorldMatrix;
  21851. }
  21852. return worldMatrix;
  21853. };
  21854. /**
  21855. * Sort function to order lights for rendering.
  21856. * @param a First Light object to compare to second.
  21857. * @param b Second Light object to compare first.
  21858. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21859. */
  21860. Light.CompareLightsPriority = function (a, b) {
  21861. //shadow-casting lights have priority over non-shadow-casting lights
  21862. //the renderPrioirty is a secondary sort criterion
  21863. if (a.shadowEnabled !== b.shadowEnabled) {
  21864. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21865. }
  21866. return b.renderPriority - a.renderPriority;
  21867. };
  21868. /**
  21869. * Releases resources associated with this node.
  21870. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21871. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21872. */
  21873. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21874. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21875. if (this._shadowGenerator) {
  21876. this._shadowGenerator.dispose();
  21877. this._shadowGenerator = null;
  21878. }
  21879. // Animations
  21880. this.getScene().stopAnimation(this);
  21881. // Remove from meshes
  21882. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21883. var mesh = _a[_i];
  21884. mesh._removeLightSource(this);
  21885. }
  21886. this._uniformBuffer.dispose();
  21887. // Remove from scene
  21888. this.getScene().removeLight(this);
  21889. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21890. };
  21891. /**
  21892. * Returns the light type ID (integer).
  21893. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21894. */
  21895. Light.prototype.getTypeID = function () {
  21896. return 0;
  21897. };
  21898. /**
  21899. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21900. * @returns the scaled intensity in intensity mode unit
  21901. */
  21902. Light.prototype.getScaledIntensity = function () {
  21903. return this._photometricScale * this.intensity;
  21904. };
  21905. /**
  21906. * Returns a new Light object, named "name", from the current one.
  21907. * @param name The name of the cloned light
  21908. * @returns the new created light
  21909. */
  21910. Light.prototype.clone = function (name) {
  21911. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21912. if (!constructor) {
  21913. return null;
  21914. }
  21915. return BABYLON.SerializationHelper.Clone(constructor, this);
  21916. };
  21917. /**
  21918. * Serializes the current light into a Serialization object.
  21919. * @returns the serialized object.
  21920. */
  21921. Light.prototype.serialize = function () {
  21922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21923. // Type
  21924. serializationObject.type = this.getTypeID();
  21925. // Parent
  21926. if (this.parent) {
  21927. serializationObject.parentId = this.parent.id;
  21928. }
  21929. // Inclusion / exclusions
  21930. if (this.excludedMeshes.length > 0) {
  21931. serializationObject.excludedMeshesIds = [];
  21932. this.excludedMeshes.forEach(function (mesh) {
  21933. serializationObject.excludedMeshesIds.push(mesh.id);
  21934. });
  21935. }
  21936. if (this.includedOnlyMeshes.length > 0) {
  21937. serializationObject.includedOnlyMeshesIds = [];
  21938. this.includedOnlyMeshes.forEach(function (mesh) {
  21939. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21940. });
  21941. }
  21942. // Animations
  21943. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21944. serializationObject.ranges = this.serializeAnimationRanges();
  21945. return serializationObject;
  21946. };
  21947. /**
  21948. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21949. * This new light is named "name" and added to the passed scene.
  21950. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21951. * @param name The friendly name of the light
  21952. * @param scene The scene the new light will belong to
  21953. * @returns the constructor function
  21954. */
  21955. Light.GetConstructorFromName = function (type, name, scene) {
  21956. switch (type) {
  21957. case 0:
  21958. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21959. case 1:
  21960. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21961. case 2:
  21962. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21963. case 3:
  21964. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21965. }
  21966. return null;
  21967. };
  21968. /**
  21969. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21970. * @param parsedLight The JSON representation of the light
  21971. * @param scene The scene to create the parsed light in
  21972. * @returns the created light after parsing
  21973. */
  21974. Light.Parse = function (parsedLight, scene) {
  21975. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21976. if (!constructor) {
  21977. return null;
  21978. }
  21979. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21980. // Inclusion / exclusions
  21981. if (parsedLight.excludedMeshesIds) {
  21982. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21983. }
  21984. if (parsedLight.includedOnlyMeshesIds) {
  21985. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21986. }
  21987. // Parent
  21988. if (parsedLight.parentId) {
  21989. light._waitingParentId = parsedLight.parentId;
  21990. }
  21991. // Animations
  21992. if (parsedLight.animations) {
  21993. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21994. var parsedAnimation = parsedLight.animations[animationIndex];
  21995. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21996. }
  21997. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21998. }
  21999. if (parsedLight.autoAnimate) {
  22000. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22001. }
  22002. return light;
  22003. };
  22004. Light.prototype._hookArrayForExcluded = function (array) {
  22005. var _this = this;
  22006. var oldPush = array.push;
  22007. array.push = function () {
  22008. var items = [];
  22009. for (var _i = 0; _i < arguments.length; _i++) {
  22010. items[_i] = arguments[_i];
  22011. }
  22012. var result = oldPush.apply(array, items);
  22013. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22014. var item = items_1[_a];
  22015. item._resyncLighSource(_this);
  22016. }
  22017. return result;
  22018. };
  22019. var oldSplice = array.splice;
  22020. array.splice = function (index, deleteCount) {
  22021. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22022. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22023. var item = deleted_1[_i];
  22024. item._resyncLighSource(_this);
  22025. }
  22026. return deleted;
  22027. };
  22028. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22029. var item = array_1[_i];
  22030. item._resyncLighSource(this);
  22031. }
  22032. };
  22033. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22034. var _this = this;
  22035. var oldPush = array.push;
  22036. array.push = function () {
  22037. var items = [];
  22038. for (var _i = 0; _i < arguments.length; _i++) {
  22039. items[_i] = arguments[_i];
  22040. }
  22041. var result = oldPush.apply(array, items);
  22042. _this._resyncMeshes();
  22043. return result;
  22044. };
  22045. var oldSplice = array.splice;
  22046. array.splice = function (index, deleteCount) {
  22047. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22048. _this._resyncMeshes();
  22049. return deleted;
  22050. };
  22051. this._resyncMeshes();
  22052. };
  22053. Light.prototype._resyncMeshes = function () {
  22054. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22055. var mesh = _a[_i];
  22056. mesh._resyncLighSource(this);
  22057. }
  22058. };
  22059. /**
  22060. * Forces the meshes to update their light related information in their rendering used effects
  22061. * @hidden Internal Use Only
  22062. */
  22063. Light.prototype._markMeshesAsLightDirty = function () {
  22064. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22065. var mesh = _a[_i];
  22066. if (mesh._lightSources.indexOf(this) !== -1) {
  22067. mesh._markSubMeshesAsLightDirty();
  22068. }
  22069. }
  22070. };
  22071. /**
  22072. * Recomputes the cached photometric scale if needed.
  22073. */
  22074. Light.prototype._computePhotometricScale = function () {
  22075. this._photometricScale = this._getPhotometricScale();
  22076. this.getScene().resetCachedMaterial();
  22077. };
  22078. /**
  22079. * Returns the Photometric Scale according to the light type and intensity mode.
  22080. */
  22081. Light.prototype._getPhotometricScale = function () {
  22082. var photometricScale = 0.0;
  22083. var lightTypeID = this.getTypeID();
  22084. //get photometric mode
  22085. var photometricMode = this.intensityMode;
  22086. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22087. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22088. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22089. }
  22090. else {
  22091. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22092. }
  22093. }
  22094. //compute photometric scale
  22095. switch (lightTypeID) {
  22096. case Light.LIGHTTYPEID_POINTLIGHT:
  22097. case Light.LIGHTTYPEID_SPOTLIGHT:
  22098. switch (photometricMode) {
  22099. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22100. photometricScale = 1.0 / (4.0 * Math.PI);
  22101. break;
  22102. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22103. photometricScale = 1.0;
  22104. break;
  22105. case Light.INTENSITYMODE_LUMINANCE:
  22106. photometricScale = this.radius * this.radius;
  22107. break;
  22108. }
  22109. break;
  22110. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22111. switch (photometricMode) {
  22112. case Light.INTENSITYMODE_ILLUMINANCE:
  22113. photometricScale = 1.0;
  22114. break;
  22115. case Light.INTENSITYMODE_LUMINANCE:
  22116. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22117. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22118. var apexAngleRadians = this.radius;
  22119. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22120. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22121. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22122. photometricScale = solidAngle;
  22123. break;
  22124. }
  22125. break;
  22126. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22127. // No fall off in hemisperic light.
  22128. photometricScale = 1.0;
  22129. break;
  22130. }
  22131. return photometricScale;
  22132. };
  22133. /**
  22134. * Reorder the light in the scene according to their defined priority.
  22135. * @hidden Internal Use Only
  22136. */
  22137. Light.prototype._reorderLightsInScene = function () {
  22138. var scene = this.getScene();
  22139. if (this._renderPriority != 0) {
  22140. scene.requireLightSorting = true;
  22141. }
  22142. this.getScene().sortLightsByPriority();
  22143. };
  22144. //lightmapMode Consts
  22145. Light._LIGHTMAP_DEFAULT = 0;
  22146. Light._LIGHTMAP_SPECULAR = 1;
  22147. Light._LIGHTMAP_SHADOWSONLY = 2;
  22148. // Intensity Mode Consts
  22149. Light._INTENSITYMODE_AUTOMATIC = 0;
  22150. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22151. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22152. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22153. Light._INTENSITYMODE_LUMINANCE = 4;
  22154. // Light types ids const.
  22155. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22156. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22157. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22158. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22159. __decorate([
  22160. BABYLON.serializeAsColor3()
  22161. ], Light.prototype, "diffuse", void 0);
  22162. __decorate([
  22163. BABYLON.serializeAsColor3()
  22164. ], Light.prototype, "specular", void 0);
  22165. __decorate([
  22166. BABYLON.serialize()
  22167. ], Light.prototype, "intensity", void 0);
  22168. __decorate([
  22169. BABYLON.serialize()
  22170. ], Light.prototype, "range", void 0);
  22171. __decorate([
  22172. BABYLON.serialize()
  22173. ], Light.prototype, "intensityMode", null);
  22174. __decorate([
  22175. BABYLON.serialize()
  22176. ], Light.prototype, "radius", null);
  22177. __decorate([
  22178. BABYLON.serialize()
  22179. ], Light.prototype, "_renderPriority", void 0);
  22180. __decorate([
  22181. BABYLON.expandToProperty("_reorderLightsInScene")
  22182. ], Light.prototype, "renderPriority", void 0);
  22183. __decorate([
  22184. BABYLON.serialize("shadowEnabled")
  22185. ], Light.prototype, "_shadowEnabled", void 0);
  22186. __decorate([
  22187. BABYLON.serialize("excludeWithLayerMask")
  22188. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22189. __decorate([
  22190. BABYLON.serialize("includeOnlyWithLayerMask")
  22191. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22192. __decorate([
  22193. BABYLON.serialize("lightmapMode")
  22194. ], Light.prototype, "_lightmapMode", void 0);
  22195. return Light;
  22196. }(BABYLON.Node));
  22197. BABYLON.Light = Light;
  22198. })(BABYLON || (BABYLON = {}));
  22199. //# sourceMappingURL=babylon.light.js.map
  22200. var BABYLON;
  22201. (function (BABYLON) {
  22202. var Camera = /** @class */ (function (_super) {
  22203. __extends(Camera, _super);
  22204. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22205. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22206. var _this = _super.call(this, name, scene) || this;
  22207. /**
  22208. * The vector the camera should consider as up.
  22209. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22210. */
  22211. _this.upVector = BABYLON.Vector3.Up();
  22212. _this.orthoLeft = null;
  22213. _this.orthoRight = null;
  22214. _this.orthoBottom = null;
  22215. _this.orthoTop = null;
  22216. /**
  22217. * FOV is set in Radians. (default is 0.8)
  22218. */
  22219. _this.fov = 0.8;
  22220. _this.minZ = 1;
  22221. _this.maxZ = 10000.0;
  22222. _this.inertia = 0.9;
  22223. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22224. _this.isIntermediate = false;
  22225. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22226. /**
  22227. * Restricts the camera to viewing objects with the same layerMask.
  22228. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22229. */
  22230. _this.layerMask = 0x0FFFFFFF;
  22231. /**
  22232. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22233. */
  22234. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22235. // Camera rig members
  22236. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22237. _this._rigCameras = new Array();
  22238. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22239. _this._skipRendering = false;
  22240. _this.customRenderTargets = new Array();
  22241. // Observables
  22242. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22243. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22244. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22245. _this.onRestoreStateObservable = new BABYLON.Observable();
  22246. // Cache
  22247. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22248. _this._projectionMatrix = new BABYLON.Matrix();
  22249. _this._doNotComputeProjectionMatrix = false;
  22250. _this._worldMatrix = BABYLON.Matrix.Identity();
  22251. _this._postProcesses = new Array();
  22252. _this._transformMatrix = BABYLON.Matrix.Zero();
  22253. _this._activeMeshes = new BABYLON.SmartArray(256);
  22254. _this._globalPosition = BABYLON.Vector3.Zero();
  22255. _this._refreshFrustumPlanes = true;
  22256. _this.getScene().addCamera(_this);
  22257. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22258. _this.getScene().activeCamera = _this;
  22259. }
  22260. _this.position = position;
  22261. return _this;
  22262. }
  22263. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22264. get: function () {
  22265. return Camera._PERSPECTIVE_CAMERA;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22271. get: function () {
  22272. return Camera._ORTHOGRAPHIC_CAMERA;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22278. /**
  22279. * This is the default FOV mode for perspective cameras.
  22280. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22281. *
  22282. */
  22283. get: function () {
  22284. return Camera._FOVMODE_VERTICAL_FIXED;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22290. /**
  22291. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22292. *
  22293. */
  22294. get: function () {
  22295. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22301. get: function () {
  22302. return Camera._RIG_MODE_NONE;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22308. get: function () {
  22309. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22310. },
  22311. enumerable: true,
  22312. configurable: true
  22313. });
  22314. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22315. get: function () {
  22316. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22317. },
  22318. enumerable: true,
  22319. configurable: true
  22320. });
  22321. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22322. get: function () {
  22323. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22324. },
  22325. enumerable: true,
  22326. configurable: true
  22327. });
  22328. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22329. get: function () {
  22330. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22331. },
  22332. enumerable: true,
  22333. configurable: true
  22334. });
  22335. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22336. get: function () {
  22337. return Camera._RIG_MODE_VR;
  22338. },
  22339. enumerable: true,
  22340. configurable: true
  22341. });
  22342. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22343. get: function () {
  22344. return Camera._RIG_MODE_WEBVR;
  22345. },
  22346. enumerable: true,
  22347. configurable: true
  22348. });
  22349. /**
  22350. * Store current camera state (fov, position, etc..)
  22351. */
  22352. Camera.prototype.storeState = function () {
  22353. this._stateStored = true;
  22354. this._storedFov = this.fov;
  22355. return this;
  22356. };
  22357. /**
  22358. * Restores the camera state values if it has been stored. You must call storeState() first
  22359. */
  22360. Camera.prototype._restoreStateValues = function () {
  22361. if (!this._stateStored) {
  22362. return false;
  22363. }
  22364. this.fov = this._storedFov;
  22365. return true;
  22366. };
  22367. /**
  22368. * Restored camera state. You must call storeState() first
  22369. */
  22370. Camera.prototype.restoreState = function () {
  22371. if (this._restoreStateValues()) {
  22372. this.onRestoreStateObservable.notifyObservers(this);
  22373. return true;
  22374. }
  22375. return false;
  22376. };
  22377. Camera.prototype.getClassName = function () {
  22378. return "Camera";
  22379. };
  22380. /**
  22381. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22382. */
  22383. Camera.prototype.toString = function (fullDetails) {
  22384. var ret = "Name: " + this.name;
  22385. ret += ", type: " + this.getClassName();
  22386. if (this.animations) {
  22387. for (var i = 0; i < this.animations.length; i++) {
  22388. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22389. }
  22390. }
  22391. if (fullDetails) {
  22392. }
  22393. return ret;
  22394. };
  22395. Object.defineProperty(Camera.prototype, "globalPosition", {
  22396. get: function () {
  22397. return this._globalPosition;
  22398. },
  22399. enumerable: true,
  22400. configurable: true
  22401. });
  22402. Camera.prototype.getActiveMeshes = function () {
  22403. return this._activeMeshes;
  22404. };
  22405. Camera.prototype.isActiveMesh = function (mesh) {
  22406. return (this._activeMeshes.indexOf(mesh) !== -1);
  22407. };
  22408. /**
  22409. * Is this camera ready to be used/rendered
  22410. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22411. * @return true if the camera is ready
  22412. */
  22413. Camera.prototype.isReady = function (completeCheck) {
  22414. if (completeCheck === void 0) { completeCheck = false; }
  22415. if (completeCheck) {
  22416. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22417. var pp = _a[_i];
  22418. if (pp && !pp.isReady()) {
  22419. return false;
  22420. }
  22421. }
  22422. }
  22423. return _super.prototype.isReady.call(this, completeCheck);
  22424. };
  22425. //Cache
  22426. Camera.prototype._initCache = function () {
  22427. _super.prototype._initCache.call(this);
  22428. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22429. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22430. this._cache.mode = undefined;
  22431. this._cache.minZ = undefined;
  22432. this._cache.maxZ = undefined;
  22433. this._cache.fov = undefined;
  22434. this._cache.fovMode = undefined;
  22435. this._cache.aspectRatio = undefined;
  22436. this._cache.orthoLeft = undefined;
  22437. this._cache.orthoRight = undefined;
  22438. this._cache.orthoBottom = undefined;
  22439. this._cache.orthoTop = undefined;
  22440. this._cache.renderWidth = undefined;
  22441. this._cache.renderHeight = undefined;
  22442. };
  22443. Camera.prototype._updateCache = function (ignoreParentClass) {
  22444. if (!ignoreParentClass) {
  22445. _super.prototype._updateCache.call(this);
  22446. }
  22447. this._cache.position.copyFrom(this.position);
  22448. this._cache.upVector.copyFrom(this.upVector);
  22449. };
  22450. // Synchronized
  22451. Camera.prototype._isSynchronized = function () {
  22452. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22453. };
  22454. Camera.prototype._isSynchronizedViewMatrix = function () {
  22455. if (!_super.prototype._isSynchronized.call(this))
  22456. return false;
  22457. return this._cache.position.equals(this.position)
  22458. && this._cache.upVector.equals(this.upVector)
  22459. && this.isSynchronizedWithParent();
  22460. };
  22461. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22462. var check = this._cache.mode === this.mode
  22463. && this._cache.minZ === this.minZ
  22464. && this._cache.maxZ === this.maxZ;
  22465. if (!check) {
  22466. return false;
  22467. }
  22468. var engine = this.getEngine();
  22469. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22470. check = this._cache.fov === this.fov
  22471. && this._cache.fovMode === this.fovMode
  22472. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22473. }
  22474. else {
  22475. check = this._cache.orthoLeft === this.orthoLeft
  22476. && this._cache.orthoRight === this.orthoRight
  22477. && this._cache.orthoBottom === this.orthoBottom
  22478. && this._cache.orthoTop === this.orthoTop
  22479. && this._cache.renderWidth === engine.getRenderWidth()
  22480. && this._cache.renderHeight === engine.getRenderHeight();
  22481. }
  22482. return check;
  22483. };
  22484. // Controls
  22485. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22486. };
  22487. Camera.prototype.detachControl = function (element) {
  22488. };
  22489. Camera.prototype.update = function () {
  22490. this._checkInputs();
  22491. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22492. this._updateRigCameras();
  22493. }
  22494. };
  22495. Camera.prototype._checkInputs = function () {
  22496. this.onAfterCheckInputsObservable.notifyObservers(this);
  22497. };
  22498. Object.defineProperty(Camera.prototype, "rigCameras", {
  22499. get: function () {
  22500. return this._rigCameras;
  22501. },
  22502. enumerable: true,
  22503. configurable: true
  22504. });
  22505. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22506. get: function () {
  22507. return this._rigPostProcess;
  22508. },
  22509. enumerable: true,
  22510. configurable: true
  22511. });
  22512. /**
  22513. * Internal, gets the first post proces.
  22514. * @returns the first post process to be run on this camera.
  22515. */
  22516. Camera.prototype._getFirstPostProcess = function () {
  22517. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22518. if (this._postProcesses[ppIndex] !== null) {
  22519. return this._postProcesses[ppIndex];
  22520. }
  22521. }
  22522. return null;
  22523. };
  22524. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22525. // invalidate framebuffer
  22526. var firstPostProcess = this._getFirstPostProcess();
  22527. if (firstPostProcess) {
  22528. firstPostProcess.markTextureDirty();
  22529. }
  22530. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22531. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22532. var cam = this._rigCameras[i];
  22533. var rigPostProcess = cam._rigPostProcess;
  22534. // for VR rig, there does not have to be a post process
  22535. if (rigPostProcess) {
  22536. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22537. if (isPass) {
  22538. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22539. cam.isIntermediate = this._postProcesses.length === 0;
  22540. }
  22541. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22542. rigPostProcess.markTextureDirty();
  22543. }
  22544. else {
  22545. cam._postProcesses = this._postProcesses.slice(0);
  22546. }
  22547. }
  22548. };
  22549. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22550. if (insertAt === void 0) { insertAt = null; }
  22551. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22552. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22553. return 0;
  22554. }
  22555. if (insertAt == null || insertAt < 0) {
  22556. this._postProcesses.push(postProcess);
  22557. }
  22558. else if (this._postProcesses[insertAt] === null) {
  22559. this._postProcesses[insertAt] = postProcess;
  22560. }
  22561. else {
  22562. this._postProcesses.splice(insertAt, 0, postProcess);
  22563. }
  22564. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22565. return this._postProcesses.indexOf(postProcess);
  22566. };
  22567. Camera.prototype.detachPostProcess = function (postProcess) {
  22568. var idx = this._postProcesses.indexOf(postProcess);
  22569. if (idx !== -1) {
  22570. this._postProcesses[idx] = null;
  22571. }
  22572. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22573. };
  22574. Camera.prototype.getWorldMatrix = function () {
  22575. if (this._isSynchronizedViewMatrix()) {
  22576. return this._worldMatrix;
  22577. }
  22578. // Getting the the view matrix will also compute the world matrix.
  22579. this.getViewMatrix();
  22580. return this._worldMatrix;
  22581. };
  22582. Camera.prototype._getViewMatrix = function () {
  22583. return BABYLON.Matrix.Identity();
  22584. };
  22585. Camera.prototype.getViewMatrix = function (force) {
  22586. if (!force && this._isSynchronizedViewMatrix()) {
  22587. return this._computedViewMatrix;
  22588. }
  22589. this.updateCache();
  22590. this._computedViewMatrix = this._getViewMatrix();
  22591. this._currentRenderId = this.getScene().getRenderId();
  22592. this._childRenderId = this._currentRenderId;
  22593. this._refreshFrustumPlanes = true;
  22594. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22595. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22596. }
  22597. this.onViewMatrixChangedObservable.notifyObservers(this);
  22598. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22599. return this._computedViewMatrix;
  22600. };
  22601. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22602. this._doNotComputeProjectionMatrix = true;
  22603. if (projection !== undefined) {
  22604. this._projectionMatrix = projection;
  22605. }
  22606. };
  22607. ;
  22608. Camera.prototype.unfreezeProjectionMatrix = function () {
  22609. this._doNotComputeProjectionMatrix = false;
  22610. };
  22611. ;
  22612. Camera.prototype.getProjectionMatrix = function (force) {
  22613. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22614. return this._projectionMatrix;
  22615. }
  22616. // Cache
  22617. this._cache.mode = this.mode;
  22618. this._cache.minZ = this.minZ;
  22619. this._cache.maxZ = this.maxZ;
  22620. // Matrix
  22621. this._refreshFrustumPlanes = true;
  22622. var engine = this.getEngine();
  22623. var scene = this.getScene();
  22624. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22625. this._cache.fov = this.fov;
  22626. this._cache.fovMode = this.fovMode;
  22627. this._cache.aspectRatio = engine.getAspectRatio(this);
  22628. if (this.minZ <= 0) {
  22629. this.minZ = 0.1;
  22630. }
  22631. if (scene.useRightHandedSystem) {
  22632. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22633. }
  22634. else {
  22635. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22636. }
  22637. }
  22638. else {
  22639. var halfWidth = engine.getRenderWidth() / 2.0;
  22640. var halfHeight = engine.getRenderHeight() / 2.0;
  22641. if (scene.useRightHandedSystem) {
  22642. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22643. }
  22644. else {
  22645. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22646. }
  22647. this._cache.orthoLeft = this.orthoLeft;
  22648. this._cache.orthoRight = this.orthoRight;
  22649. this._cache.orthoBottom = this.orthoBottom;
  22650. this._cache.orthoTop = this.orthoTop;
  22651. this._cache.renderWidth = engine.getRenderWidth();
  22652. this._cache.renderHeight = engine.getRenderHeight();
  22653. }
  22654. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22655. return this._projectionMatrix;
  22656. };
  22657. Camera.prototype.getTranformationMatrix = function () {
  22658. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22659. return this._transformMatrix;
  22660. };
  22661. Camera.prototype.updateFrustumPlanes = function () {
  22662. if (!this._refreshFrustumPlanes) {
  22663. return;
  22664. }
  22665. this.getTranformationMatrix();
  22666. if (!this._frustumPlanes) {
  22667. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22668. }
  22669. else {
  22670. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22671. }
  22672. this._refreshFrustumPlanes = false;
  22673. };
  22674. Camera.prototype.isInFrustum = function (target) {
  22675. this.updateFrustumPlanes();
  22676. return target.isInFrustum(this._frustumPlanes);
  22677. };
  22678. Camera.prototype.isCompletelyInFrustum = function (target) {
  22679. this.updateFrustumPlanes();
  22680. return target.isCompletelyInFrustum(this._frustumPlanes);
  22681. };
  22682. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22683. if (length === void 0) { length = 100; }
  22684. if (!transform) {
  22685. transform = this.getWorldMatrix();
  22686. }
  22687. if (!origin) {
  22688. origin = this.position;
  22689. }
  22690. var forward = new BABYLON.Vector3(0, 0, 1);
  22691. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22692. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22693. return new BABYLON.Ray(origin, direction, length);
  22694. };
  22695. /**
  22696. * Releases resources associated with this node.
  22697. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22698. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22699. */
  22700. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22701. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22702. // Observables
  22703. this.onViewMatrixChangedObservable.clear();
  22704. this.onProjectionMatrixChangedObservable.clear();
  22705. this.onAfterCheckInputsObservable.clear();
  22706. this.onRestoreStateObservable.clear();
  22707. // Inputs
  22708. if (this.inputs) {
  22709. this.inputs.clear();
  22710. }
  22711. // Animations
  22712. this.getScene().stopAnimation(this);
  22713. // Remove from scene
  22714. this.getScene().removeCamera(this);
  22715. while (this._rigCameras.length > 0) {
  22716. var camera = this._rigCameras.pop();
  22717. if (camera) {
  22718. camera.dispose();
  22719. }
  22720. }
  22721. // Postprocesses
  22722. if (this._rigPostProcess) {
  22723. this._rigPostProcess.dispose(this);
  22724. this._rigPostProcess = null;
  22725. this._postProcesses = [];
  22726. }
  22727. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22728. this._rigPostProcess = null;
  22729. this._postProcesses = [];
  22730. }
  22731. else {
  22732. var i = this._postProcesses.length;
  22733. while (--i >= 0) {
  22734. var postProcess = this._postProcesses[i];
  22735. if (postProcess) {
  22736. postProcess.dispose(this);
  22737. }
  22738. }
  22739. }
  22740. // Render targets
  22741. var i = this.customRenderTargets.length;
  22742. while (--i >= 0) {
  22743. this.customRenderTargets[i].dispose();
  22744. }
  22745. this.customRenderTargets = [];
  22746. // Active Meshes
  22747. this._activeMeshes.dispose();
  22748. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22749. };
  22750. Object.defineProperty(Camera.prototype, "leftCamera", {
  22751. // ---- Camera rigs section ----
  22752. get: function () {
  22753. if (this._rigCameras.length < 1) {
  22754. return null;
  22755. }
  22756. return this._rigCameras[0];
  22757. },
  22758. enumerable: true,
  22759. configurable: true
  22760. });
  22761. Object.defineProperty(Camera.prototype, "rightCamera", {
  22762. get: function () {
  22763. if (this._rigCameras.length < 2) {
  22764. return null;
  22765. }
  22766. return this._rigCameras[1];
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. Camera.prototype.getLeftTarget = function () {
  22772. if (this._rigCameras.length < 1) {
  22773. return null;
  22774. }
  22775. return this._rigCameras[0].getTarget();
  22776. };
  22777. Camera.prototype.getRightTarget = function () {
  22778. if (this._rigCameras.length < 2) {
  22779. return null;
  22780. }
  22781. return this._rigCameras[1].getTarget();
  22782. };
  22783. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22784. if (this.cameraRigMode === mode) {
  22785. return;
  22786. }
  22787. while (this._rigCameras.length > 0) {
  22788. var camera = this._rigCameras.pop();
  22789. if (camera) {
  22790. camera.dispose();
  22791. }
  22792. }
  22793. this.cameraRigMode = mode;
  22794. this._cameraRigParams = {};
  22795. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22796. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22797. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22798. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22799. // create the rig cameras, unless none
  22800. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22801. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22802. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22803. if (leftCamera && rightCamera) {
  22804. this._rigCameras.push(leftCamera);
  22805. this._rigCameras.push(rightCamera);
  22806. }
  22807. }
  22808. switch (this.cameraRigMode) {
  22809. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22810. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22811. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22812. break;
  22813. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22815. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22816. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22817. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22818. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22819. break;
  22820. case Camera.RIG_MODE_VR:
  22821. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22822. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22823. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22824. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22825. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22826. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22827. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22828. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22829. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22830. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22831. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22832. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22833. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22834. if (metrics.compensateDistortion) {
  22835. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22836. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22837. }
  22838. break;
  22839. case Camera.RIG_MODE_WEBVR:
  22840. if (rigParams.vrDisplay) {
  22841. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22842. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22843. //Left eye
  22844. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22845. this._rigCameras[0].setCameraRigParameter("left", true);
  22846. //leaving this for future reference
  22847. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22848. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22849. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22850. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22851. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22852. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22853. this._rigCameras[0].parent = this;
  22854. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22855. //Right eye
  22856. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22857. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22858. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22859. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22860. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22861. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22862. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22863. this._rigCameras[1].parent = this;
  22864. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22865. if (Camera.UseAlternateWebVRRendering) {
  22866. this._rigCameras[1]._skipRendering = true;
  22867. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22868. }
  22869. }
  22870. break;
  22871. }
  22872. this._cascadePostProcessesToRigCams();
  22873. this.update();
  22874. };
  22875. Camera.prototype._getVRProjectionMatrix = function () {
  22876. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22877. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22878. return this._projectionMatrix;
  22879. };
  22880. Camera.prototype._updateCameraRotationMatrix = function () {
  22881. //Here for WebVR
  22882. };
  22883. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22884. //Here for WebVR
  22885. };
  22886. /**
  22887. * This function MUST be overwritten by the different WebVR cameras available.
  22888. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22889. */
  22890. Camera.prototype._getWebVRProjectionMatrix = function () {
  22891. return BABYLON.Matrix.Identity();
  22892. };
  22893. /**
  22894. * This function MUST be overwritten by the different WebVR cameras available.
  22895. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22896. */
  22897. Camera.prototype._getWebVRViewMatrix = function () {
  22898. return BABYLON.Matrix.Identity();
  22899. };
  22900. Camera.prototype.setCameraRigParameter = function (name, value) {
  22901. if (!this._cameraRigParams) {
  22902. this._cameraRigParams = {};
  22903. }
  22904. this._cameraRigParams[name] = value;
  22905. //provisionnally:
  22906. if (name === "interaxialDistance") {
  22907. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22908. }
  22909. };
  22910. /**
  22911. * needs to be overridden by children so sub has required properties to be copied
  22912. */
  22913. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22914. return null;
  22915. };
  22916. /**
  22917. * May need to be overridden by children
  22918. */
  22919. Camera.prototype._updateRigCameras = function () {
  22920. for (var i = 0; i < this._rigCameras.length; i++) {
  22921. this._rigCameras[i].minZ = this.minZ;
  22922. this._rigCameras[i].maxZ = this.maxZ;
  22923. this._rigCameras[i].fov = this.fov;
  22924. }
  22925. // only update viewport when ANAGLYPH
  22926. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22927. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22928. }
  22929. };
  22930. Camera.prototype._setupInputs = function () {
  22931. };
  22932. Camera.prototype.serialize = function () {
  22933. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22934. // Type
  22935. serializationObject.type = this.getClassName();
  22936. // Parent
  22937. if (this.parent) {
  22938. serializationObject.parentId = this.parent.id;
  22939. }
  22940. if (this.inputs) {
  22941. this.inputs.serialize(serializationObject);
  22942. }
  22943. // Animations
  22944. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22945. serializationObject.ranges = this.serializeAnimationRanges();
  22946. return serializationObject;
  22947. };
  22948. Camera.prototype.clone = function (name) {
  22949. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22950. };
  22951. Camera.prototype.getDirection = function (localAxis) {
  22952. var result = BABYLON.Vector3.Zero();
  22953. this.getDirectionToRef(localAxis, result);
  22954. return result;
  22955. };
  22956. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22957. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22958. };
  22959. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22960. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22961. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22962. switch (type) {
  22963. case "ArcRotateCamera":
  22964. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22965. case "DeviceOrientationCamera":
  22966. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22967. case "FollowCamera":
  22968. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22969. case "ArcFollowCamera":
  22970. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22971. case "GamepadCamera":
  22972. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22973. case "TouchCamera":
  22974. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22975. case "VirtualJoysticksCamera":
  22976. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22977. case "WebVRFreeCamera":
  22978. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22979. case "WebVRGamepadCamera":
  22980. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22981. case "VRDeviceOrientationFreeCamera":
  22982. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22983. case "VRDeviceOrientationGamepadCamera":
  22984. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22985. case "AnaglyphArcRotateCamera":
  22986. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22987. case "AnaglyphFreeCamera":
  22988. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22989. case "AnaglyphGamepadCamera":
  22990. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22991. case "AnaglyphUniversalCamera":
  22992. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22993. case "StereoscopicArcRotateCamera":
  22994. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22995. case "StereoscopicFreeCamera":
  22996. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22997. case "StereoscopicGamepadCamera":
  22998. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22999. case "StereoscopicUniversalCamera":
  23000. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23001. case "FreeCamera": // Forcing Universal here
  23002. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23003. default: // Universal Camera is the default value
  23004. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23005. }
  23006. };
  23007. Camera.prototype.computeWorldMatrix = function () {
  23008. return this.getWorldMatrix();
  23009. };
  23010. Camera.Parse = function (parsedCamera, scene) {
  23011. var type = parsedCamera.type;
  23012. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23013. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23014. // Parent
  23015. if (parsedCamera.parentId) {
  23016. camera._waitingParentId = parsedCamera.parentId;
  23017. }
  23018. //If camera has an input manager, let it parse inputs settings
  23019. if (camera.inputs) {
  23020. camera.inputs.parse(parsedCamera);
  23021. camera._setupInputs();
  23022. }
  23023. if (camera.setPosition) { // need to force position
  23024. camera.position.copyFromFloats(0, 0, 0);
  23025. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23026. }
  23027. // Target
  23028. if (parsedCamera.target) {
  23029. if (camera.setTarget) {
  23030. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23031. }
  23032. }
  23033. // Apply 3d rig, when found
  23034. if (parsedCamera.cameraRigMode) {
  23035. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23036. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23037. }
  23038. // Animations
  23039. if (parsedCamera.animations) {
  23040. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23041. var parsedAnimation = parsedCamera.animations[animationIndex];
  23042. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23043. }
  23044. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23045. }
  23046. if (parsedCamera.autoAnimate) {
  23047. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23048. }
  23049. return camera;
  23050. };
  23051. // Statics
  23052. Camera._PERSPECTIVE_CAMERA = 0;
  23053. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23054. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23055. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23056. Camera._RIG_MODE_NONE = 0;
  23057. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23058. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23059. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23060. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23061. Camera._RIG_MODE_VR = 20;
  23062. Camera._RIG_MODE_WEBVR = 21;
  23063. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23064. Camera.UseAlternateWebVRRendering = false;
  23065. __decorate([
  23066. BABYLON.serializeAsVector3()
  23067. ], Camera.prototype, "position", void 0);
  23068. __decorate([
  23069. BABYLON.serializeAsVector3()
  23070. ], Camera.prototype, "upVector", void 0);
  23071. __decorate([
  23072. BABYLON.serialize()
  23073. ], Camera.prototype, "orthoLeft", void 0);
  23074. __decorate([
  23075. BABYLON.serialize()
  23076. ], Camera.prototype, "orthoRight", void 0);
  23077. __decorate([
  23078. BABYLON.serialize()
  23079. ], Camera.prototype, "orthoBottom", void 0);
  23080. __decorate([
  23081. BABYLON.serialize()
  23082. ], Camera.prototype, "orthoTop", void 0);
  23083. __decorate([
  23084. BABYLON.serialize()
  23085. ], Camera.prototype, "fov", void 0);
  23086. __decorate([
  23087. BABYLON.serialize()
  23088. ], Camera.prototype, "minZ", void 0);
  23089. __decorate([
  23090. BABYLON.serialize()
  23091. ], Camera.prototype, "maxZ", void 0);
  23092. __decorate([
  23093. BABYLON.serialize()
  23094. ], Camera.prototype, "inertia", void 0);
  23095. __decorate([
  23096. BABYLON.serialize()
  23097. ], Camera.prototype, "mode", void 0);
  23098. __decorate([
  23099. BABYLON.serialize()
  23100. ], Camera.prototype, "layerMask", void 0);
  23101. __decorate([
  23102. BABYLON.serialize()
  23103. ], Camera.prototype, "fovMode", void 0);
  23104. __decorate([
  23105. BABYLON.serialize()
  23106. ], Camera.prototype, "cameraRigMode", void 0);
  23107. __decorate([
  23108. BABYLON.serialize()
  23109. ], Camera.prototype, "interaxialDistance", void 0);
  23110. __decorate([
  23111. BABYLON.serialize()
  23112. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23113. return Camera;
  23114. }(BABYLON.Node));
  23115. BABYLON.Camera = Camera;
  23116. })(BABYLON || (BABYLON = {}));
  23117. //# sourceMappingURL=babylon.camera.js.map
  23118. var BABYLON;
  23119. (function (BABYLON) {
  23120. var RenderingManager = /** @class */ (function () {
  23121. function RenderingManager(scene) {
  23122. this._renderingGroups = new Array();
  23123. this._autoClearDepthStencil = {};
  23124. this._customOpaqueSortCompareFn = {};
  23125. this._customAlphaTestSortCompareFn = {};
  23126. this._customTransparentSortCompareFn = {};
  23127. this._renderinGroupInfo = null;
  23128. this._scene = scene;
  23129. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23130. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23131. }
  23132. }
  23133. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23134. if (depth === void 0) { depth = true; }
  23135. if (stencil === void 0) { stencil = true; }
  23136. if (this._depthStencilBufferAlreadyCleaned) {
  23137. return;
  23138. }
  23139. this._scene.getEngine().clear(null, false, depth, stencil);
  23140. this._depthStencilBufferAlreadyCleaned = true;
  23141. };
  23142. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23143. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23144. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23145. var info = null;
  23146. if (observable) {
  23147. if (!this._renderinGroupInfo) {
  23148. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23149. }
  23150. info = this._renderinGroupInfo;
  23151. info.scene = this._scene;
  23152. info.camera = this._scene.activeCamera;
  23153. }
  23154. // Dispatch sprites
  23155. if (renderSprites) {
  23156. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23157. var manager = this._scene.spriteManagers[index];
  23158. this.dispatchSprites(manager);
  23159. }
  23160. }
  23161. // Render
  23162. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23163. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23164. var renderingGroup = this._renderingGroups[index];
  23165. if (!renderingGroup && !observable)
  23166. continue;
  23167. var renderingGroupMask = 0;
  23168. // Fire PRECLEAR stage
  23169. if (observable && info) {
  23170. renderingGroupMask = Math.pow(2, index);
  23171. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23172. info.renderingGroupId = index;
  23173. observable.notifyObservers(info, renderingGroupMask);
  23174. }
  23175. // Clear depth/stencil if needed
  23176. if (RenderingManager.AUTOCLEAR) {
  23177. var autoClear = this._autoClearDepthStencil[index];
  23178. if (autoClear && autoClear.autoClear) {
  23179. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23180. }
  23181. }
  23182. if (observable && info) {
  23183. // Fire PREOPAQUE stage
  23184. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23185. observable.notifyObservers(info, renderingGroupMask);
  23186. // Fire PRETRANSPARENT stage
  23187. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23188. observable.notifyObservers(info, renderingGroupMask);
  23189. }
  23190. if (renderingGroup)
  23191. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23192. // Fire POSTTRANSPARENT stage
  23193. if (observable && info) {
  23194. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23195. observable.notifyObservers(info, renderingGroupMask);
  23196. }
  23197. }
  23198. };
  23199. RenderingManager.prototype.reset = function () {
  23200. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23201. var renderingGroup = this._renderingGroups[index];
  23202. if (renderingGroup) {
  23203. renderingGroup.prepare();
  23204. }
  23205. }
  23206. };
  23207. RenderingManager.prototype.dispose = function () {
  23208. this.freeRenderingGroups();
  23209. this._renderingGroups.length = 0;
  23210. };
  23211. /**
  23212. * Clear the info related to rendering groups preventing retention points during dispose.
  23213. */
  23214. RenderingManager.prototype.freeRenderingGroups = function () {
  23215. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23216. var renderingGroup = this._renderingGroups[index];
  23217. if (renderingGroup) {
  23218. renderingGroup.dispose();
  23219. }
  23220. }
  23221. };
  23222. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23223. if (this._renderingGroups[renderingGroupId] === undefined) {
  23224. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23225. }
  23226. };
  23227. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23228. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23229. this._prepareRenderingGroup(renderingGroupId);
  23230. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23231. };
  23232. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23233. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23234. this._prepareRenderingGroup(renderingGroupId);
  23235. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23236. };
  23237. /**
  23238. * @param subMesh The submesh to dispatch
  23239. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23240. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23241. */
  23242. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23243. if (mesh === undefined) {
  23244. mesh = subMesh.getMesh();
  23245. }
  23246. var renderingGroupId = mesh.renderingGroupId || 0;
  23247. this._prepareRenderingGroup(renderingGroupId);
  23248. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23249. };
  23250. /**
  23251. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23252. * This allowed control for front to back rendering or reversly depending of the special needs.
  23253. *
  23254. * @param renderingGroupId The rendering group id corresponding to its index
  23255. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23256. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23257. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23258. */
  23259. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23260. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23261. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23262. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23263. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23264. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23265. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23266. if (this._renderingGroups[renderingGroupId]) {
  23267. var group = this._renderingGroups[renderingGroupId];
  23268. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23269. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23270. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23271. }
  23272. };
  23273. /**
  23274. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23275. *
  23276. * @param renderingGroupId The rendering group id corresponding to its index
  23277. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23278. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23279. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23280. */
  23281. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23282. if (depth === void 0) { depth = true; }
  23283. if (stencil === void 0) { stencil = true; }
  23284. this._autoClearDepthStencil[renderingGroupId] = {
  23285. autoClear: autoClearDepthStencil,
  23286. depth: depth,
  23287. stencil: stencil
  23288. };
  23289. };
  23290. /**
  23291. * The max id used for rendering groups (not included)
  23292. */
  23293. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23294. /**
  23295. * The min id used for rendering groups (included)
  23296. */
  23297. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23298. /**
  23299. * Used to globally prevent autoclearing scenes.
  23300. */
  23301. RenderingManager.AUTOCLEAR = true;
  23302. return RenderingManager;
  23303. }());
  23304. BABYLON.RenderingManager = RenderingManager;
  23305. })(BABYLON || (BABYLON = {}));
  23306. //# sourceMappingURL=babylon.renderingManager.js.map
  23307. var BABYLON;
  23308. (function (BABYLON) {
  23309. var RenderingGroup = /** @class */ (function () {
  23310. /**
  23311. * Creates a new rendering group.
  23312. * @param index The rendering group index
  23313. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23314. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23315. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23316. */
  23317. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23318. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23319. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23320. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23321. this.index = index;
  23322. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23323. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23324. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23325. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23326. this._particleSystems = new BABYLON.SmartArray(256);
  23327. this._spriteManagers = new BABYLON.SmartArray(256);
  23328. this._edgesRenderers = new BABYLON.SmartArray(16);
  23329. this._scene = scene;
  23330. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23331. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23332. this.transparentSortCompareFn = transparentSortCompareFn;
  23333. }
  23334. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23335. /**
  23336. * Set the opaque sort comparison function.
  23337. * If null the sub meshes will be render in the order they were created
  23338. */
  23339. set: function (value) {
  23340. this._opaqueSortCompareFn = value;
  23341. if (value) {
  23342. this._renderOpaque = this.renderOpaqueSorted;
  23343. }
  23344. else {
  23345. this._renderOpaque = RenderingGroup.renderUnsorted;
  23346. }
  23347. },
  23348. enumerable: true,
  23349. configurable: true
  23350. });
  23351. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23352. /**
  23353. * Set the alpha test sort comparison function.
  23354. * If null the sub meshes will be render in the order they were created
  23355. */
  23356. set: function (value) {
  23357. this._alphaTestSortCompareFn = value;
  23358. if (value) {
  23359. this._renderAlphaTest = this.renderAlphaTestSorted;
  23360. }
  23361. else {
  23362. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23363. }
  23364. },
  23365. enumerable: true,
  23366. configurable: true
  23367. });
  23368. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23369. /**
  23370. * Set the transparent sort comparison function.
  23371. * If null the sub meshes will be render in the order they were created
  23372. */
  23373. set: function (value) {
  23374. if (value) {
  23375. this._transparentSortCompareFn = value;
  23376. }
  23377. else {
  23378. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23379. }
  23380. this._renderTransparent = this.renderTransparentSorted;
  23381. },
  23382. enumerable: true,
  23383. configurable: true
  23384. });
  23385. /**
  23386. * Render all the sub meshes contained in the group.
  23387. * @param customRenderFunction Used to override the default render behaviour of the group.
  23388. * @returns true if rendered some submeshes.
  23389. */
  23390. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23391. if (customRenderFunction) {
  23392. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23393. return;
  23394. }
  23395. var engine = this._scene.getEngine();
  23396. // Depth only
  23397. if (this._depthOnlySubMeshes.length !== 0) {
  23398. engine.setColorWrite(false);
  23399. this._renderAlphaTest(this._depthOnlySubMeshes);
  23400. engine.setColorWrite(true);
  23401. }
  23402. // Opaque
  23403. if (this._opaqueSubMeshes.length !== 0) {
  23404. this._renderOpaque(this._opaqueSubMeshes);
  23405. }
  23406. // Alpha test
  23407. if (this._alphaTestSubMeshes.length !== 0) {
  23408. this._renderAlphaTest(this._alphaTestSubMeshes);
  23409. }
  23410. var stencilState = engine.getStencilBuffer();
  23411. engine.setStencilBuffer(false);
  23412. // Sprites
  23413. if (renderSprites) {
  23414. this._renderSprites();
  23415. }
  23416. // Particles
  23417. if (renderParticles) {
  23418. this._renderParticles(activeMeshes);
  23419. }
  23420. if (this.onBeforeTransparentRendering) {
  23421. this.onBeforeTransparentRendering();
  23422. }
  23423. // Transparent
  23424. if (this._transparentSubMeshes.length !== 0) {
  23425. this._renderTransparent(this._transparentSubMeshes);
  23426. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23427. }
  23428. // Set back stencil to false in case it changes before the edge renderer.
  23429. engine.setStencilBuffer(false);
  23430. // Edges
  23431. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23432. this._edgesRenderers.data[edgesRendererIndex].render();
  23433. }
  23434. // Restore Stencil state.
  23435. engine.setStencilBuffer(stencilState);
  23436. };
  23437. /**
  23438. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23439. * @param subMeshes The submeshes to render
  23440. */
  23441. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23442. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23443. };
  23444. /**
  23445. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23446. * @param subMeshes The submeshes to render
  23447. */
  23448. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23449. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23450. };
  23451. /**
  23452. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23453. * @param subMeshes The submeshes to render
  23454. */
  23455. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23456. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23457. };
  23458. /**
  23459. * Renders the submeshes in a specified order.
  23460. * @param subMeshes The submeshes to sort before render
  23461. * @param sortCompareFn The comparison function use to sort
  23462. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23463. * @param transparent Specifies to activate blending if true
  23464. */
  23465. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23466. var subIndex = 0;
  23467. var subMesh;
  23468. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23469. for (; subIndex < subMeshes.length; subIndex++) {
  23470. subMesh = subMeshes.data[subIndex];
  23471. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23472. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23473. }
  23474. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23475. if (sortCompareFn) {
  23476. sortedArray.sort(sortCompareFn);
  23477. }
  23478. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23479. subMesh = sortedArray[subIndex];
  23480. if (transparent) {
  23481. var material = subMesh.getMaterial();
  23482. if (material && material.needDepthPrePass) {
  23483. var engine = material.getScene().getEngine();
  23484. engine.setColorWrite(false);
  23485. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23486. subMesh.render(false);
  23487. engine.setColorWrite(true);
  23488. }
  23489. }
  23490. subMesh.render(transparent);
  23491. }
  23492. };
  23493. /**
  23494. * Renders the submeshes in the order they were dispatched (no sort applied).
  23495. * @param subMeshes The submeshes to render
  23496. */
  23497. RenderingGroup.renderUnsorted = function (subMeshes) {
  23498. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23499. var submesh = subMeshes.data[subIndex];
  23500. submesh.render(false);
  23501. }
  23502. };
  23503. /**
  23504. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23505. * are rendered back to front if in the same alpha index.
  23506. *
  23507. * @param a The first submesh
  23508. * @param b The second submesh
  23509. * @returns The result of the comparison
  23510. */
  23511. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23512. // Alpha index first
  23513. if (a._alphaIndex > b._alphaIndex) {
  23514. return 1;
  23515. }
  23516. if (a._alphaIndex < b._alphaIndex) {
  23517. return -1;
  23518. }
  23519. // Then distance to camera
  23520. return RenderingGroup.backToFrontSortCompare(a, b);
  23521. };
  23522. /**
  23523. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23524. * are rendered back to front.
  23525. *
  23526. * @param a The first submesh
  23527. * @param b The second submesh
  23528. * @returns The result of the comparison
  23529. */
  23530. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23531. // Then distance to camera
  23532. if (a._distanceToCamera < b._distanceToCamera) {
  23533. return 1;
  23534. }
  23535. if (a._distanceToCamera > b._distanceToCamera) {
  23536. return -1;
  23537. }
  23538. return 0;
  23539. };
  23540. /**
  23541. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23542. * are rendered front to back (prevent overdraw).
  23543. *
  23544. * @param a The first submesh
  23545. * @param b The second submesh
  23546. * @returns The result of the comparison
  23547. */
  23548. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23549. // Then distance to camera
  23550. if (a._distanceToCamera < b._distanceToCamera) {
  23551. return -1;
  23552. }
  23553. if (a._distanceToCamera > b._distanceToCamera) {
  23554. return 1;
  23555. }
  23556. return 0;
  23557. };
  23558. /**
  23559. * Resets the different lists of submeshes to prepare a new frame.
  23560. */
  23561. RenderingGroup.prototype.prepare = function () {
  23562. this._opaqueSubMeshes.reset();
  23563. this._transparentSubMeshes.reset();
  23564. this._alphaTestSubMeshes.reset();
  23565. this._depthOnlySubMeshes.reset();
  23566. this._particleSystems.reset();
  23567. this._spriteManagers.reset();
  23568. this._edgesRenderers.reset();
  23569. };
  23570. RenderingGroup.prototype.dispose = function () {
  23571. this._opaqueSubMeshes.dispose();
  23572. this._transparentSubMeshes.dispose();
  23573. this._alphaTestSubMeshes.dispose();
  23574. this._depthOnlySubMeshes.dispose();
  23575. this._particleSystems.dispose();
  23576. this._spriteManagers.dispose();
  23577. this._edgesRenderers.dispose();
  23578. };
  23579. /**
  23580. * Inserts the submesh in its correct queue depending on its material.
  23581. * @param subMesh The submesh to dispatch
  23582. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23583. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23584. */
  23585. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23586. // Get mesh and materials if not provided
  23587. if (mesh === undefined) {
  23588. mesh = subMesh.getMesh();
  23589. }
  23590. if (material === undefined) {
  23591. material = subMesh.getMaterial();
  23592. }
  23593. if (material === null || material === undefined) {
  23594. return;
  23595. }
  23596. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23597. this._transparentSubMeshes.push(subMesh);
  23598. }
  23599. else if (material.needAlphaTesting()) { // Alpha test
  23600. if (material.needDepthPrePass) {
  23601. this._depthOnlySubMeshes.push(subMesh);
  23602. }
  23603. this._alphaTestSubMeshes.push(subMesh);
  23604. }
  23605. else {
  23606. if (material.needDepthPrePass) {
  23607. this._depthOnlySubMeshes.push(subMesh);
  23608. }
  23609. this._opaqueSubMeshes.push(subMesh); // Opaque
  23610. }
  23611. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23612. this._edgesRenderers.push(mesh._edgesRenderer);
  23613. }
  23614. };
  23615. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23616. this._spriteManagers.push(spriteManager);
  23617. };
  23618. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23619. this._particleSystems.push(particleSystem);
  23620. };
  23621. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23622. if (this._particleSystems.length === 0) {
  23623. return;
  23624. }
  23625. // Particles
  23626. var activeCamera = this._scene.activeCamera;
  23627. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23628. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23629. var particleSystem = this._particleSystems.data[particleIndex];
  23630. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23631. continue;
  23632. }
  23633. var emitter = particleSystem.emitter;
  23634. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23635. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23636. }
  23637. }
  23638. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23639. };
  23640. RenderingGroup.prototype._renderSprites = function () {
  23641. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23642. return;
  23643. }
  23644. // Sprites
  23645. var activeCamera = this._scene.activeCamera;
  23646. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23647. for (var id = 0; id < this._spriteManagers.length; id++) {
  23648. var spriteManager = this._spriteManagers.data[id];
  23649. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23650. spriteManager.render();
  23651. }
  23652. }
  23653. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23654. };
  23655. return RenderingGroup;
  23656. }());
  23657. BABYLON.RenderingGroup = RenderingGroup;
  23658. })(BABYLON || (BABYLON = {}));
  23659. //# sourceMappingURL=babylon.renderingGroup.js.map
  23660. var BABYLON;
  23661. (function (BABYLON) {
  23662. /** @hidden */
  23663. var ClickInfo = /** @class */ (function () {
  23664. function ClickInfo() {
  23665. this._singleClick = false;
  23666. this._doubleClick = false;
  23667. this._hasSwiped = false;
  23668. this._ignore = false;
  23669. }
  23670. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23671. get: function () {
  23672. return this._singleClick;
  23673. },
  23674. set: function (b) {
  23675. this._singleClick = b;
  23676. },
  23677. enumerable: true,
  23678. configurable: true
  23679. });
  23680. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23681. get: function () {
  23682. return this._doubleClick;
  23683. },
  23684. set: function (b) {
  23685. this._doubleClick = b;
  23686. },
  23687. enumerable: true,
  23688. configurable: true
  23689. });
  23690. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23691. get: function () {
  23692. return this._hasSwiped;
  23693. },
  23694. set: function (b) {
  23695. this._hasSwiped = b;
  23696. },
  23697. enumerable: true,
  23698. configurable: true
  23699. });
  23700. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23701. get: function () {
  23702. return this._ignore;
  23703. },
  23704. set: function (b) {
  23705. this._ignore = b;
  23706. },
  23707. enumerable: true,
  23708. configurable: true
  23709. });
  23710. return ClickInfo;
  23711. }());
  23712. /**
  23713. * This class is used by the onRenderingGroupObservable
  23714. */
  23715. var RenderingGroupInfo = /** @class */ (function () {
  23716. function RenderingGroupInfo() {
  23717. }
  23718. /**
  23719. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23720. * This stage will be fired no matter what
  23721. */
  23722. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23723. /**
  23724. * Called before opaque object are rendered.
  23725. * This stage will be fired only if there's 3D Opaque content to render
  23726. */
  23727. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23728. /**
  23729. * Called after the opaque objects are rendered and before the transparent ones
  23730. * This stage will be fired only if there's 3D transparent content to render
  23731. */
  23732. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23733. /**
  23734. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23735. * This stage will be fired no matter what
  23736. */
  23737. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23738. return RenderingGroupInfo;
  23739. }());
  23740. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23741. /**
  23742. * Represents a scene to be rendered by the engine.
  23743. * @see http://doc.babylonjs.com/features/scene
  23744. */
  23745. var Scene = /** @class */ (function () {
  23746. /**
  23747. * Creates a new Scene
  23748. * @param engine defines the engine to use to render this scene
  23749. */
  23750. function Scene(engine) {
  23751. // Members
  23752. /**
  23753. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23754. */
  23755. this.autoClear = true;
  23756. /**
  23757. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23758. */
  23759. this.autoClearDepthAndStencil = true;
  23760. /**
  23761. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23762. */
  23763. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23764. /**
  23765. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23766. */
  23767. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23768. this._forceWireframe = false;
  23769. this._forcePointsCloud = false;
  23770. /**
  23771. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23772. */
  23773. this.forceShowBoundingBoxes = false;
  23774. /**
  23775. * Gets or sets a boolean indicating if animations are enabled
  23776. */
  23777. this.animationsEnabled = true;
  23778. this._animationPropertiesOverride = null;
  23779. /**
  23780. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23781. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23782. */
  23783. this.useConstantAnimationDeltaTime = false;
  23784. /**
  23785. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23786. * Please note that it requires to run a ray cast through the scene on every frame
  23787. */
  23788. this.constantlyUpdateMeshUnderPointer = false;
  23789. /**
  23790. * Defines the HTML cursor to use when hovering over interactive elements
  23791. */
  23792. this.hoverCursor = "pointer";
  23793. /**
  23794. * Defines the HTML default cursor to use (empty by default)
  23795. */
  23796. this.defaultCursor = "";
  23797. /**
  23798. * This is used to call preventDefault() on pointer down
  23799. * in order to block unwanted artifacts like system double clicks
  23800. */
  23801. this.preventDefaultOnPointerDown = true;
  23802. // Metadata
  23803. /**
  23804. * Gets or sets user defined metadata
  23805. */
  23806. this.metadata = null;
  23807. /**
  23808. * Use this array to add regular expressions used to disable offline support for specific urls
  23809. */
  23810. this.disableOfflineSupportExceptionRules = new Array();
  23811. /**
  23812. * An event triggered when the scene is disposed.
  23813. */
  23814. this.onDisposeObservable = new BABYLON.Observable();
  23815. this._onDisposeObserver = null;
  23816. /**
  23817. * An event triggered before rendering the scene (right after animations and physics)
  23818. */
  23819. this.onBeforeRenderObservable = new BABYLON.Observable();
  23820. this._onBeforeRenderObserver = null;
  23821. /**
  23822. * An event triggered after rendering the scene
  23823. */
  23824. this.onAfterRenderObservable = new BABYLON.Observable();
  23825. this._onAfterRenderObserver = null;
  23826. /**
  23827. * An event triggered before animating the scene
  23828. */
  23829. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered after animations processing
  23832. */
  23833. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered before draw calls are ready to be sent
  23836. */
  23837. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23838. /**
  23839. * An event triggered after draw calls have been sent
  23840. */
  23841. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered when physic simulation is about to be run
  23844. */
  23845. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered when physic simulation has been done
  23848. */
  23849. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23850. /**
  23851. * An event triggered when the scene is ready
  23852. */
  23853. this.onReadyObservable = new BABYLON.Observable();
  23854. /**
  23855. * An event triggered before rendering a camera
  23856. */
  23857. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23858. this._onBeforeCameraRenderObserver = null;
  23859. /**
  23860. * An event triggered after rendering a camera
  23861. */
  23862. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23863. this._onAfterCameraRenderObserver = null;
  23864. /**
  23865. * An event triggered when active meshes evaluation is about to start
  23866. */
  23867. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23868. /**
  23869. * An event triggered when active meshes evaluation is done
  23870. */
  23871. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23872. /**
  23873. * An event triggered when particles rendering is about to start
  23874. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23875. */
  23876. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23877. /**
  23878. * An event triggered when particles rendering is done
  23879. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23880. */
  23881. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered when sprites rendering is about to start
  23884. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23885. */
  23886. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23887. /**
  23888. * An event triggered when sprites rendering is done
  23889. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23890. */
  23891. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23892. /**
  23893. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23894. */
  23895. this.onDataLoadedObservable = new BABYLON.Observable();
  23896. /**
  23897. * An event triggered when a camera is created
  23898. */
  23899. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23900. /**
  23901. * An event triggered when a camera is removed
  23902. */
  23903. this.onCameraRemovedObservable = new BABYLON.Observable();
  23904. /**
  23905. * An event triggered when a light is created
  23906. */
  23907. this.onNewLightAddedObservable = new BABYLON.Observable();
  23908. /**
  23909. * An event triggered when a light is removed
  23910. */
  23911. this.onLightRemovedObservable = new BABYLON.Observable();
  23912. /**
  23913. * An event triggered when a geometry is created
  23914. */
  23915. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23916. /**
  23917. * An event triggered when a geometry is removed
  23918. */
  23919. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23920. /**
  23921. * An event triggered when a transform node is created
  23922. */
  23923. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23924. /**
  23925. * An event triggered when a transform node is removed
  23926. */
  23927. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23928. /**
  23929. * An event triggered when a mesh is created
  23930. */
  23931. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23932. /**
  23933. * An event triggered when a mesh is removed
  23934. */
  23935. this.onMeshRemovedObservable = new BABYLON.Observable();
  23936. /**
  23937. * An event triggered when render targets are about to be rendered
  23938. * Can happen multiple times per frame.
  23939. */
  23940. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23941. /**
  23942. * An event triggered when render targets were rendered.
  23943. * Can happen multiple times per frame.
  23944. */
  23945. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23946. /**
  23947. * An event triggered before calculating deterministic simulation step
  23948. */
  23949. this.onBeforeStepObservable = new BABYLON.Observable();
  23950. /**
  23951. * An event triggered after calculating deterministic simulation step
  23952. */
  23953. this.onAfterStepObservable = new BABYLON.Observable();
  23954. /**
  23955. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23956. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23957. * 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)
  23958. */
  23959. this.onRenderingGroupObservable = new BABYLON.Observable();
  23960. // Animations
  23961. /**
  23962. * Gets a list of Animations associated with the scene
  23963. */
  23964. this.animations = [];
  23965. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23966. /**
  23967. * 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).
  23968. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23969. */
  23970. this.onPrePointerObservable = new BABYLON.Observable();
  23971. /**
  23972. * Observable event triggered each time an input event is received from the rendering canvas
  23973. */
  23974. this.onPointerObservable = new BABYLON.Observable();
  23975. this._meshPickProceed = false;
  23976. this._currentPickResult = null;
  23977. this._previousPickResult = null;
  23978. this._totalPointersPressed = 0;
  23979. this._doubleClickOccured = false;
  23980. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23981. this.cameraToUseForPointers = null;
  23982. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23983. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23984. this._startingPointerTime = 0;
  23985. this._previousStartingPointerTime = 0;
  23986. this._pointerCaptures = {};
  23987. // Deterministic lockstep
  23988. this._timeAccumulator = 0;
  23989. this._currentStepId = 0;
  23990. this._currentInternalStep = 0;
  23991. // Keyboard
  23992. /**
  23993. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23994. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23995. */
  23996. this.onPreKeyboardObservable = new BABYLON.Observable();
  23997. /**
  23998. * Observable event triggered each time an keyboard event is received from the hosting window
  23999. */
  24000. this.onKeyboardObservable = new BABYLON.Observable();
  24001. // Coordinates system
  24002. this._useRightHandedSystem = false;
  24003. // Fog
  24004. this._fogEnabled = true;
  24005. this._fogMode = Scene.FOGMODE_NONE;
  24006. /**
  24007. * Gets or sets the fog color to use
  24008. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24009. */
  24010. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24011. /**
  24012. * Gets or sets the fog density to use
  24013. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24014. */
  24015. this.fogDensity = 0.1;
  24016. /**
  24017. * Gets or sets the fog start distance to use
  24018. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24019. */
  24020. this.fogStart = 0;
  24021. /**
  24022. * Gets or sets the fog end distance to use
  24023. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24024. */
  24025. this.fogEnd = 1000.0;
  24026. // Lights
  24027. this._shadowsEnabled = true;
  24028. this._lightsEnabled = true;
  24029. /**
  24030. * All of the lights added to this scene
  24031. * @see http://doc.babylonjs.com/babylon101/lights
  24032. */
  24033. this.lights = new Array();
  24034. // Cameras
  24035. /** All of the cameras added to this scene.
  24036. * @see http://doc.babylonjs.com/babylon101/cameras
  24037. */
  24038. this.cameras = new Array();
  24039. /** All of the active cameras added to this scene. */
  24040. this.activeCameras = new Array();
  24041. // Meshes
  24042. /**
  24043. * All of the tranform nodes added to this scene
  24044. * @see http://doc.babylonjs.com/how_to/transformnode
  24045. */
  24046. this.transformNodes = new Array();
  24047. /**
  24048. * All of the (abstract) meshes added to this scene
  24049. */
  24050. this.meshes = new Array();
  24051. /**
  24052. * All of the animation groups added to this scene
  24053. * @see http://doc.babylonjs.com/how_to/group
  24054. */
  24055. this.animationGroups = new Array();
  24056. // Geometries
  24057. this._geometries = new Array();
  24058. /**
  24059. * All of the materials added to this scene
  24060. * @see http://doc.babylonjs.com/babylon101/materials
  24061. */
  24062. this.materials = new Array();
  24063. /**
  24064. * All of the multi-materials added to this scene
  24065. * @see http://doc.babylonjs.com/how_to/multi_materials
  24066. */
  24067. this.multiMaterials = new Array();
  24068. // Textures
  24069. this._texturesEnabled = true;
  24070. /**
  24071. * All of the textures added to this scene
  24072. */
  24073. this.textures = new Array();
  24074. // Particles
  24075. /**
  24076. * Gets or sets a boolean indicating if particles are enabled on this scene
  24077. */
  24078. this.particlesEnabled = true;
  24079. /**
  24080. * All of the particle systems added to this scene
  24081. * @see http://doc.babylonjs.com/babylon101/particles
  24082. */
  24083. this.particleSystems = new Array();
  24084. // Sprites
  24085. /**
  24086. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24087. */
  24088. this.spritesEnabled = true;
  24089. /**
  24090. * All of the sprite managers added to this scene
  24091. * @see http://doc.babylonjs.com/babylon101/sprites
  24092. */
  24093. this.spriteManagers = new Array();
  24094. /**
  24095. * The list of layers (background and foreground) of the scene
  24096. */
  24097. this.layers = new Array();
  24098. /**
  24099. * The list of effect layers (highlights/glow) added to the scene
  24100. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24101. * @see http://doc.babylonjs.com/how_to/glow_layer
  24102. */
  24103. this.effectLayers = new Array();
  24104. // Skeletons
  24105. this._skeletonsEnabled = true;
  24106. /**
  24107. * The list of skeletons added to the scene
  24108. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24109. */
  24110. this.skeletons = new Array();
  24111. // Morph targets
  24112. /**
  24113. * The list of morph target managers added to the scene
  24114. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24115. */
  24116. this.morphTargetManagers = new Array();
  24117. // Lens flares
  24118. /**
  24119. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24120. */
  24121. this.lensFlaresEnabled = true;
  24122. /**
  24123. * The list of lens flare system added to the scene
  24124. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24125. */
  24126. this.lensFlareSystems = new Array();
  24127. // Collisions
  24128. /**
  24129. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24130. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24131. */
  24132. this.collisionsEnabled = true;
  24133. /**
  24134. * Defines the gravity applied to this scene (used only for collisions)
  24135. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24136. */
  24137. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24138. // Postprocesses
  24139. /**
  24140. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24141. */
  24142. this.postProcessesEnabled = true;
  24143. /**
  24144. * The list of postprocesses added to the scene
  24145. */
  24146. this.postProcesses = new Array();
  24147. // Customs render targets
  24148. /**
  24149. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24150. */
  24151. this.renderTargetsEnabled = true;
  24152. /**
  24153. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24154. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24155. */
  24156. this.dumpNextRenderTargets = false;
  24157. /**
  24158. * The list of user defined render targets added to the scene
  24159. */
  24160. this.customRenderTargets = new Array();
  24161. /**
  24162. * Gets the list of meshes imported to the scene through SceneLoader
  24163. */
  24164. this.importedMeshesFiles = new Array();
  24165. // Probes
  24166. /**
  24167. * Gets or sets a boolean indicating if probes are enabled on this scene
  24168. */
  24169. this.probesEnabled = true;
  24170. /**
  24171. * The list of reflection probes added to the scene
  24172. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24173. */
  24174. this.reflectionProbes = new Array();
  24175. /** @hidden */
  24176. this._actionManagers = new Array();
  24177. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24178. // Procedural textures
  24179. /**
  24180. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24181. */
  24182. this.proceduralTexturesEnabled = true;
  24183. /**
  24184. * The list of procedural textures added to the scene
  24185. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24186. */
  24187. this.proceduralTextures = new Array();
  24188. /**
  24189. * The list of sound tracks added to the scene
  24190. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24191. */
  24192. this.soundTracks = new Array();
  24193. this._audioEnabled = true;
  24194. this._headphone = false;
  24195. // Performance counters
  24196. this._totalVertices = new BABYLON.PerfCounter();
  24197. /** @hidden */
  24198. this._activeIndices = new BABYLON.PerfCounter();
  24199. /** @hidden */
  24200. this._activeParticles = new BABYLON.PerfCounter();
  24201. /** @hidden */
  24202. this._activeBones = new BABYLON.PerfCounter();
  24203. this._animationTime = 0;
  24204. /**
  24205. * Gets or sets a general scale for animation speed
  24206. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24207. */
  24208. this.animationTimeScale = 1;
  24209. this._renderId = 0;
  24210. this._executeWhenReadyTimeoutId = -1;
  24211. this._intermediateRendering = false;
  24212. this._viewUpdateFlag = -1;
  24213. this._projectionUpdateFlag = -1;
  24214. this._alternateViewUpdateFlag = -1;
  24215. this._alternateProjectionUpdateFlag = -1;
  24216. /** @hidden */
  24217. this._toBeDisposed = new BABYLON.SmartArray(256);
  24218. this._activeRequests = new Array();
  24219. this._pendingData = new Array();
  24220. this._isDisposed = false;
  24221. /**
  24222. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24223. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24224. */
  24225. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24226. this._activeMeshes = new BABYLON.SmartArray(256);
  24227. this._processedMaterials = new BABYLON.SmartArray(256);
  24228. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24229. /** @hidden */
  24230. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24231. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24232. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24233. /** @hidden */
  24234. this._activeAnimatables = new Array();
  24235. this._transformMatrix = BABYLON.Matrix.Zero();
  24236. this._useAlternateCameraConfiguration = false;
  24237. this._alternateRendering = false;
  24238. /**
  24239. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24240. * This is useful if there are more lights that the maximum simulteanous authorized
  24241. */
  24242. this.requireLightSorting = false;
  24243. this._depthRenderer = {};
  24244. this._activeMeshesFrozen = false;
  24245. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24246. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24247. this._engine.scenes.push(this);
  24248. this._uid = null;
  24249. this._renderingManager = new BABYLON.RenderingManager(this);
  24250. if (BABYLON.PostProcessManager) {
  24251. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24252. }
  24253. if (BABYLON.OutlineRenderer) {
  24254. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24255. }
  24256. if (BABYLON.Tools.IsWindowObjectExist()) {
  24257. this.attachControl();
  24258. }
  24259. //simplification queue
  24260. if (BABYLON.SimplificationQueue) {
  24261. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24262. }
  24263. //collision coordinator initialization. For now legacy per default.
  24264. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24265. // Uniform Buffer
  24266. this._createUbo();
  24267. // Default Image processing definition
  24268. if (BABYLON.ImageProcessingConfiguration) {
  24269. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24270. }
  24271. }
  24272. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24273. /** The fog is deactivated */
  24274. get: function () {
  24275. return Scene._FOGMODE_NONE;
  24276. },
  24277. enumerable: true,
  24278. configurable: true
  24279. });
  24280. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24281. /** The fog density is following an exponential function */
  24282. get: function () {
  24283. return Scene._FOGMODE_EXP;
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24289. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24290. get: function () {
  24291. return Scene._FOGMODE_EXP2;
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24297. /** The fog density is following a linear function. */
  24298. get: function () {
  24299. return Scene._FOGMODE_LINEAR;
  24300. },
  24301. enumerable: true,
  24302. configurable: true
  24303. });
  24304. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24305. /**
  24306. * Texture used in all pbr material as the reflection texture.
  24307. * As in the majority of the scene they are the same (exception for multi room and so on),
  24308. * this is easier to reference from here than from all the materials.
  24309. */
  24310. get: function () {
  24311. return this._environmentTexture;
  24312. },
  24313. /**
  24314. * Texture used in all pbr material as the reflection texture.
  24315. * As in the majority of the scene they are the same (exception for multi room and so on),
  24316. * this is easier to set here than in all the materials.
  24317. */
  24318. set: function (value) {
  24319. if (this._environmentTexture === value) {
  24320. return;
  24321. }
  24322. this._environmentTexture = value;
  24323. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24324. },
  24325. enumerable: true,
  24326. configurable: true
  24327. });
  24328. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24329. /**
  24330. * Default image processing configuration used either in the rendering
  24331. * Forward main pass or through the imageProcessingPostProcess if present.
  24332. * As in the majority of the scene they are the same (exception for multi camera),
  24333. * this is easier to reference from here than from all the materials and post process.
  24334. *
  24335. * No setter as we it is a shared configuration, you can set the values instead.
  24336. */
  24337. get: function () {
  24338. return this._imageProcessingConfiguration;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24344. get: function () {
  24345. return this._forceWireframe;
  24346. },
  24347. /**
  24348. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24349. */
  24350. set: function (value) {
  24351. if (this._forceWireframe === value) {
  24352. return;
  24353. }
  24354. this._forceWireframe = value;
  24355. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24361. get: function () {
  24362. return this._forcePointsCloud;
  24363. },
  24364. /**
  24365. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24366. */
  24367. set: function (value) {
  24368. if (this._forcePointsCloud === value) {
  24369. return;
  24370. }
  24371. this._forcePointsCloud = value;
  24372. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24378. /**
  24379. * Gets or sets the animation properties override
  24380. */
  24381. get: function () {
  24382. return this._animationPropertiesOverride;
  24383. },
  24384. set: function (value) {
  24385. this._animationPropertiesOverride = value;
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Scene.prototype, "onDispose", {
  24391. /** Sets a function to be executed when this scene is disposed. */
  24392. set: function (callback) {
  24393. if (this._onDisposeObserver) {
  24394. this.onDisposeObservable.remove(this._onDisposeObserver);
  24395. }
  24396. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene.prototype, "beforeRender", {
  24402. /** Sets a function to be executed before rendering this scene */
  24403. set: function (callback) {
  24404. if (this._onBeforeRenderObserver) {
  24405. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24406. }
  24407. if (callback) {
  24408. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24409. }
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene.prototype, "afterRender", {
  24415. /** Sets a function to be executed after rendering this scene */
  24416. set: function (callback) {
  24417. if (this._onAfterRenderObserver) {
  24418. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24419. }
  24420. if (callback) {
  24421. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24422. }
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24428. /** Sets a function to be executed before rendering a camera*/
  24429. set: function (callback) {
  24430. if (this._onBeforeCameraRenderObserver) {
  24431. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24432. }
  24433. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24439. /** Sets a function to be executed after rendering a camera*/
  24440. set: function (callback) {
  24441. if (this._onAfterCameraRenderObserver) {
  24442. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24443. }
  24444. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24450. /**
  24451. * Gets the gamepad manager associated with the scene
  24452. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24453. */
  24454. get: function () {
  24455. if (!this._gamepadManager) {
  24456. this._gamepadManager = new BABYLON.GamepadManager(this);
  24457. }
  24458. return this._gamepadManager;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24464. /**
  24465. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24466. */
  24467. get: function () {
  24468. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24474. get: function () {
  24475. return this._useRightHandedSystem;
  24476. },
  24477. /**
  24478. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24479. */
  24480. set: function (value) {
  24481. if (this._useRightHandedSystem === value) {
  24482. return;
  24483. }
  24484. this._useRightHandedSystem = value;
  24485. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. /**
  24491. * Sets the step Id used by deterministic lock step
  24492. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24493. * @param newStepId defines the step Id
  24494. */
  24495. Scene.prototype.setStepId = function (newStepId) {
  24496. this._currentStepId = newStepId;
  24497. };
  24498. ;
  24499. /**
  24500. * Gets the step Id used by deterministic lock step
  24501. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24502. * @returns the step Id
  24503. */
  24504. Scene.prototype.getStepId = function () {
  24505. return this._currentStepId;
  24506. };
  24507. ;
  24508. /**
  24509. * Gets the internal step used by deterministic lock step
  24510. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24511. * @returns the internal step
  24512. */
  24513. Scene.prototype.getInternalStep = function () {
  24514. return this._currentInternalStep;
  24515. };
  24516. ;
  24517. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24518. get: function () {
  24519. return this._fogEnabled;
  24520. },
  24521. /**
  24522. * Gets or sets a boolean indicating if fog is enabled on this scene
  24523. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24524. */
  24525. set: function (value) {
  24526. if (this._fogEnabled === value) {
  24527. return;
  24528. }
  24529. this._fogEnabled = value;
  24530. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "fogMode", {
  24536. get: function () {
  24537. return this._fogMode;
  24538. },
  24539. /**
  24540. * Gets or sets the fog mode to use
  24541. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24542. */
  24543. set: function (value) {
  24544. if (this._fogMode === value) {
  24545. return;
  24546. }
  24547. this._fogMode = value;
  24548. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24554. get: function () {
  24555. return this._shadowsEnabled;
  24556. },
  24557. /**
  24558. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24559. */
  24560. set: function (value) {
  24561. if (this._shadowsEnabled === value) {
  24562. return;
  24563. }
  24564. this._shadowsEnabled = value;
  24565. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24571. get: function () {
  24572. return this._lightsEnabled;
  24573. },
  24574. /**
  24575. * Gets or sets a boolean indicating if lights are enabled on this scene
  24576. */
  24577. set: function (value) {
  24578. if (this._lightsEnabled === value) {
  24579. return;
  24580. }
  24581. this._lightsEnabled = value;
  24582. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24588. /** The default material used on meshes when no material is affected */
  24589. get: function () {
  24590. if (!this._defaultMaterial) {
  24591. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24592. }
  24593. return this._defaultMaterial;
  24594. },
  24595. /** The default material used on meshes when no material is affected */
  24596. set: function (value) {
  24597. this._defaultMaterial = value;
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24603. get: function () {
  24604. return this._texturesEnabled;
  24605. },
  24606. /**
  24607. * Gets or sets a boolean indicating if textures are enabled on this scene
  24608. */
  24609. set: function (value) {
  24610. if (this._texturesEnabled === value) {
  24611. return;
  24612. }
  24613. this._texturesEnabled = value;
  24614. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24620. get: function () {
  24621. return this._skeletonsEnabled;
  24622. },
  24623. /**
  24624. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24625. */
  24626. set: function (value) {
  24627. if (this._skeletonsEnabled === value) {
  24628. return;
  24629. }
  24630. this._skeletonsEnabled = value;
  24631. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24637. /**
  24638. * Gets the postprocess render pipeline manager
  24639. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24640. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24641. */
  24642. get: function () {
  24643. if (!this._postProcessRenderPipelineManager) {
  24644. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24645. }
  24646. return this._postProcessRenderPipelineManager;
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24652. /**
  24653. * Gets the main soundtrack associated with the scene
  24654. */
  24655. get: function () {
  24656. if (!this._mainSoundTrack) {
  24657. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24658. }
  24659. return this._mainSoundTrack;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24665. /** @hidden */
  24666. get: function () {
  24667. return this._alternateRendering;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24673. /**
  24674. * Gets the list of frustum planes (built from the active camera)
  24675. */
  24676. get: function () {
  24677. return this._frustumPlanes;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24683. /**
  24684. * Gets the current geometry buffer associated to the scene.
  24685. */
  24686. get: function () {
  24687. return this._geometryBufferRenderer;
  24688. },
  24689. /**
  24690. * Sets the current geometry buffer for the scene.
  24691. */
  24692. set: function (geometryBufferRenderer) {
  24693. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24694. this._geometryBufferRenderer = geometryBufferRenderer;
  24695. }
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "debugLayer", {
  24701. /**
  24702. * Gets the debug layer (aka Inspector) associated with the scene
  24703. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24704. */
  24705. get: function () {
  24706. if (!this._debugLayer) {
  24707. this._debugLayer = new BABYLON.DebugLayer(this);
  24708. }
  24709. return this._debugLayer;
  24710. },
  24711. enumerable: true,
  24712. configurable: true
  24713. });
  24714. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24715. /**
  24716. * Gets a boolean indicating if collisions are processed on a web worker
  24717. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24718. */
  24719. get: function () {
  24720. return this._workerCollisions;
  24721. },
  24722. set: function (enabled) {
  24723. if (!BABYLON.CollisionCoordinatorLegacy) {
  24724. return;
  24725. }
  24726. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24727. this._workerCollisions = enabled;
  24728. if (this.collisionCoordinator) {
  24729. this.collisionCoordinator.destroy();
  24730. }
  24731. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24732. this.collisionCoordinator.init(this);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24738. /**
  24739. * Gets the octree used to boost mesh selection (picking)
  24740. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24741. */
  24742. get: function () {
  24743. return this._selectionOctree;
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24749. /**
  24750. * Gets the mesh that is currently under the pointer
  24751. */
  24752. get: function () {
  24753. return this._pointerOverMesh;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. Object.defineProperty(Scene.prototype, "pointerX", {
  24759. /**
  24760. * Gets the current on-screen X position of the pointer
  24761. */
  24762. get: function () {
  24763. return this._pointerX;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(Scene.prototype, "pointerY", {
  24769. /**
  24770. * Gets the current on-screen Y position of the pointer
  24771. */
  24772. get: function () {
  24773. return this._pointerY;
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. /**
  24779. * Gets the cached material (ie. the latest rendered one)
  24780. * @returns the cached material
  24781. */
  24782. Scene.prototype.getCachedMaterial = function () {
  24783. return this._cachedMaterial;
  24784. };
  24785. /**
  24786. * Gets the cached effect (ie. the latest rendered one)
  24787. * @returns the cached effect
  24788. */
  24789. Scene.prototype.getCachedEffect = function () {
  24790. return this._cachedEffect;
  24791. };
  24792. /**
  24793. * Gets the cached visibility state (ie. the latest rendered one)
  24794. * @returns the cached visibility state
  24795. */
  24796. Scene.prototype.getCachedVisibility = function () {
  24797. return this._cachedVisibility;
  24798. };
  24799. /**
  24800. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24801. * @param material defines the current material
  24802. * @param effect defines the current effect
  24803. * @param visibility defines the current visibility state
  24804. * @returns true if one parameter is not cached
  24805. */
  24806. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24807. if (visibility === void 0) { visibility = 1; }
  24808. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24809. };
  24810. /**
  24811. * Gets the bounding box renderer associated with the scene
  24812. * @returns a BoundingBoxRenderer
  24813. */
  24814. Scene.prototype.getBoundingBoxRenderer = function () {
  24815. if (!this._boundingBoxRenderer) {
  24816. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24817. }
  24818. return this._boundingBoxRenderer;
  24819. };
  24820. /**
  24821. * Gets the outline renderer associated with the scene
  24822. * @returns a OutlineRenderer
  24823. */
  24824. Scene.prototype.getOutlineRenderer = function () {
  24825. return this._outlineRenderer;
  24826. };
  24827. /**
  24828. * Gets the engine associated with the scene
  24829. * @returns an Engine
  24830. */
  24831. Scene.prototype.getEngine = function () {
  24832. return this._engine;
  24833. };
  24834. /**
  24835. * Gets the total number of vertices rendered per frame
  24836. * @returns the total number of vertices rendered per frame
  24837. */
  24838. Scene.prototype.getTotalVertices = function () {
  24839. return this._totalVertices.current;
  24840. };
  24841. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24842. /**
  24843. * Gets the performance counter for total vertices
  24844. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24845. */
  24846. get: function () {
  24847. return this._totalVertices;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. /**
  24853. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24854. * @returns the total number of active indices rendered per frame
  24855. */
  24856. Scene.prototype.getActiveIndices = function () {
  24857. return this._activeIndices.current;
  24858. };
  24859. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24860. /**
  24861. * Gets the performance counter for active indices
  24862. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24863. */
  24864. get: function () {
  24865. return this._activeIndices;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. /**
  24871. * Gets the total number of active particles rendered per frame
  24872. * @returns the total number of active particles rendered per frame
  24873. */
  24874. Scene.prototype.getActiveParticles = function () {
  24875. return this._activeParticles.current;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24878. /**
  24879. * Gets the performance counter for active particles
  24880. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24881. */
  24882. get: function () {
  24883. return this._activeParticles;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. /**
  24889. * Gets the total number of active bones rendered per frame
  24890. * @returns the total number of active bones rendered per frame
  24891. */
  24892. Scene.prototype.getActiveBones = function () {
  24893. return this._activeBones.current;
  24894. };
  24895. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24896. /**
  24897. * Gets the performance counter for active bones
  24898. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24899. */
  24900. get: function () {
  24901. return this._activeBones;
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. /** @hidden */
  24907. Scene.prototype.getInterFramePerfCounter = function () {
  24908. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24909. return 0;
  24910. };
  24911. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24912. /** @hidden */
  24913. get: function () {
  24914. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24915. return null;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. /** @hidden */
  24921. Scene.prototype.getLastFrameDuration = function () {
  24922. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24923. return 0;
  24924. };
  24925. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24926. /** @hidden */
  24927. get: function () {
  24928. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24929. return null;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. /** @hidden */
  24935. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24936. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24937. return 0;
  24938. };
  24939. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24940. /** @hidden */
  24941. get: function () {
  24942. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24943. return null;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. /**
  24949. * Gets the array of active meshes
  24950. * @returns an array of AbstractMesh
  24951. */
  24952. Scene.prototype.getActiveMeshes = function () {
  24953. return this._activeMeshes;
  24954. };
  24955. /** @hidden */
  24956. Scene.prototype.getRenderTargetsDuration = function () {
  24957. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24958. return 0;
  24959. };
  24960. /** @hidden */
  24961. Scene.prototype.getRenderDuration = function () {
  24962. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24963. return 0;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24966. /** @hidden */
  24967. get: function () {
  24968. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24969. return null;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. /** @hidden */
  24975. Scene.prototype.getParticlesDuration = function () {
  24976. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24977. return 0;
  24978. };
  24979. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24980. /** @hidden */
  24981. get: function () {
  24982. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24983. return null;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. /** @hidden */
  24989. Scene.prototype.getSpritesDuration = function () {
  24990. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24991. return 0;
  24992. };
  24993. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24994. /** @hidden */
  24995. get: function () {
  24996. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24997. return null;
  24998. },
  24999. enumerable: true,
  25000. configurable: true
  25001. });
  25002. /**
  25003. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25004. * @returns a number
  25005. */
  25006. Scene.prototype.getAnimationRatio = function () {
  25007. return this._animationRatio;
  25008. };
  25009. /**
  25010. * Gets an unique Id for the current frame
  25011. * @returns a number
  25012. */
  25013. Scene.prototype.getRenderId = function () {
  25014. return this._renderId;
  25015. };
  25016. /** Call this function if you want to manually increment the render Id*/
  25017. Scene.prototype.incrementRenderId = function () {
  25018. this._renderId++;
  25019. };
  25020. Scene.prototype._updatePointerPosition = function (evt) {
  25021. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25022. if (!canvasRect) {
  25023. return;
  25024. }
  25025. this._pointerX = evt.clientX - canvasRect.left;
  25026. this._pointerY = evt.clientY - canvasRect.top;
  25027. this._unTranslatedPointerX = this._pointerX;
  25028. this._unTranslatedPointerY = this._pointerY;
  25029. };
  25030. Scene.prototype._createUbo = function () {
  25031. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25032. this._sceneUbo.addUniform("viewProjection", 16);
  25033. this._sceneUbo.addUniform("view", 16);
  25034. };
  25035. Scene.prototype._createAlternateUbo = function () {
  25036. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25037. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25038. this._alternateSceneUbo.addUniform("view", 16);
  25039. };
  25040. // Pointers handling
  25041. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25042. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25043. if (result) {
  25044. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25045. }
  25046. return result;
  25047. };
  25048. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25049. if (pointerInfo.pickInfo) {
  25050. if (!pointerInfo.pickInfo.ray) {
  25051. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25052. }
  25053. }
  25054. };
  25055. /**
  25056. * Use this method to simulate a pointer move on a mesh
  25057. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25058. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25059. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25060. * @returns the current scene
  25061. */
  25062. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25063. var evt = new PointerEvent("pointermove", pointerEventInit);
  25064. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25065. return this;
  25066. }
  25067. return this._processPointerMove(pickResult, evt);
  25068. };
  25069. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25070. var canvas = this._engine.getRenderingCanvas();
  25071. if (!canvas) {
  25072. return this;
  25073. }
  25074. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25075. this.setPointerOverSprite(null);
  25076. this.setPointerOverMesh(pickResult.pickedMesh);
  25077. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25078. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25079. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25080. }
  25081. else {
  25082. canvas.style.cursor = this.hoverCursor;
  25083. }
  25084. }
  25085. else {
  25086. canvas.style.cursor = this.defaultCursor;
  25087. }
  25088. }
  25089. else {
  25090. this.setPointerOverMesh(null);
  25091. // Sprites
  25092. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25093. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25094. this.setPointerOverSprite(pickResult.pickedSprite);
  25095. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25096. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25097. }
  25098. else {
  25099. canvas.style.cursor = this.hoverCursor;
  25100. }
  25101. }
  25102. else {
  25103. this.setPointerOverSprite(null);
  25104. // Restore pointer
  25105. canvas.style.cursor = this.defaultCursor;
  25106. }
  25107. }
  25108. if (pickResult) {
  25109. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25110. if (this.onPointerMove) {
  25111. this.onPointerMove(evt, pickResult, type);
  25112. }
  25113. if (this.onPointerObservable.hasObservers()) {
  25114. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25115. this._setRayOnPointerInfo(pi);
  25116. this.onPointerObservable.notifyObservers(pi, type);
  25117. }
  25118. }
  25119. return this;
  25120. };
  25121. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25122. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25123. if (pickResult) {
  25124. pi.ray = pickResult.ray;
  25125. }
  25126. this.onPrePointerObservable.notifyObservers(pi, type);
  25127. if (pi.skipOnPointerObservable) {
  25128. return true;
  25129. }
  25130. else {
  25131. return false;
  25132. }
  25133. };
  25134. /**
  25135. * Use this method to simulate a pointer down on a mesh
  25136. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25137. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25138. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25139. * @returns the current scene
  25140. */
  25141. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25142. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25143. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25144. return this;
  25145. }
  25146. return this._processPointerDown(pickResult, evt);
  25147. };
  25148. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25149. var _this = this;
  25150. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25151. this._pickedDownMesh = pickResult.pickedMesh;
  25152. var actionManager = pickResult.pickedMesh.actionManager;
  25153. if (actionManager) {
  25154. if (actionManager.hasPickTriggers) {
  25155. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25156. switch (evt.button) {
  25157. case 0:
  25158. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25159. break;
  25160. case 1:
  25161. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25162. break;
  25163. case 2:
  25164. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25165. break;
  25166. }
  25167. }
  25168. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25169. window.setTimeout(function () {
  25170. 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);
  25171. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25172. if (_this._totalPointersPressed !== 0 &&
  25173. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25174. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25175. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25176. _this._startingPointerTime = 0;
  25177. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25178. }
  25179. }
  25180. }, Scene.LongPressDelay);
  25181. }
  25182. }
  25183. }
  25184. if (pickResult) {
  25185. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25186. if (this.onPointerDown) {
  25187. this.onPointerDown(evt, pickResult, type);
  25188. }
  25189. if (this.onPointerObservable.hasObservers()) {
  25190. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25191. this._setRayOnPointerInfo(pi);
  25192. this.onPointerObservable.notifyObservers(pi, type);
  25193. }
  25194. }
  25195. return this;
  25196. };
  25197. /**
  25198. * Use this method to simulate a pointer up on a mesh
  25199. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25200. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25201. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25202. * @returns the current scene
  25203. */
  25204. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25205. var evt = new PointerEvent("pointerup", pointerEventInit);
  25206. var clickInfo = new ClickInfo();
  25207. clickInfo.singleClick = true;
  25208. clickInfo.ignore = true;
  25209. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25210. return this;
  25211. }
  25212. return this._processPointerUp(pickResult, evt, clickInfo);
  25213. };
  25214. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25215. if (pickResult && pickResult && pickResult.pickedMesh) {
  25216. this._pickedUpMesh = pickResult.pickedMesh;
  25217. if (this._pickedDownMesh === this._pickedUpMesh) {
  25218. if (this.onPointerPick) {
  25219. this.onPointerPick(evt, pickResult);
  25220. }
  25221. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25222. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25223. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25224. this._setRayOnPointerInfo(pi);
  25225. this.onPointerObservable.notifyObservers(pi, type_1);
  25226. }
  25227. }
  25228. if (pickResult.pickedMesh.actionManager) {
  25229. if (clickInfo.ignore) {
  25230. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25231. }
  25232. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. }
  25235. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25236. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. }
  25238. }
  25239. }
  25240. if (this._pickedDownMesh &&
  25241. this._pickedDownMesh.actionManager &&
  25242. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25243. this._pickedDownMesh !== this._pickedUpMesh) {
  25244. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25245. }
  25246. var type = BABYLON.PointerEventTypes.POINTERUP;
  25247. if (this.onPointerObservable.hasObservers()) {
  25248. if (!clickInfo.ignore) {
  25249. if (!clickInfo.hasSwiped) {
  25250. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25251. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25252. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25253. this._setRayOnPointerInfo(pi);
  25254. this.onPointerObservable.notifyObservers(pi, type_2);
  25255. }
  25256. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25257. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25258. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25259. this._setRayOnPointerInfo(pi);
  25260. this.onPointerObservable.notifyObservers(pi, type_3);
  25261. }
  25262. }
  25263. }
  25264. else {
  25265. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25266. this._setRayOnPointerInfo(pi);
  25267. this.onPointerObservable.notifyObservers(pi, type);
  25268. }
  25269. }
  25270. if (this.onPointerUp) {
  25271. this.onPointerUp(evt, pickResult, type);
  25272. }
  25273. return this;
  25274. };
  25275. /**
  25276. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25277. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25278. * @returns true if the pointer was captured
  25279. */
  25280. Scene.prototype.isPointerCaptured = function (pointerId) {
  25281. if (pointerId === void 0) { pointerId = 0; }
  25282. return this._pointerCaptures[pointerId];
  25283. };
  25284. /**
  25285. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25286. * @param attachUp defines if you want to attach events to pointerup
  25287. * @param attachDown defines if you want to attach events to pointerdown
  25288. * @param attachMove defines if you want to attach events to pointermove
  25289. */
  25290. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25291. var _this = this;
  25292. if (attachUp === void 0) { attachUp = true; }
  25293. if (attachDown === void 0) { attachDown = true; }
  25294. if (attachMove === void 0) { attachMove = true; }
  25295. this._initActionManager = function (act, clickInfo) {
  25296. if (!_this._meshPickProceed) {
  25297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25298. _this._currentPickResult = pickResult;
  25299. if (pickResult) {
  25300. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25301. }
  25302. _this._meshPickProceed = true;
  25303. }
  25304. return act;
  25305. };
  25306. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25307. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25308. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25309. btn !== _this._previousButtonPressed) {
  25310. _this._doubleClickOccured = false;
  25311. clickInfo.singleClick = true;
  25312. clickInfo.ignore = false;
  25313. cb(clickInfo, _this._currentPickResult);
  25314. }
  25315. };
  25316. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25317. var clickInfo = new ClickInfo();
  25318. _this._currentPickResult = null;
  25319. var act = null;
  25320. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25321. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25322. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25323. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25324. act = _this._initActionManager(act, clickInfo);
  25325. if (act)
  25326. checkPicking = act.hasPickTriggers;
  25327. }
  25328. if (checkPicking) {
  25329. var btn = evt.button;
  25330. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25331. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25332. if (!clickInfo.hasSwiped) {
  25333. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25334. if (!checkSingleClickImmediately) {
  25335. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25336. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25337. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25338. act = _this._initActionManager(act, clickInfo);
  25339. if (act)
  25340. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25341. }
  25342. }
  25343. if (checkSingleClickImmediately) {
  25344. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25345. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25346. btn !== _this._previousButtonPressed) {
  25347. clickInfo.singleClick = true;
  25348. cb(clickInfo, _this._currentPickResult);
  25349. }
  25350. }
  25351. // at least one double click is required to be check and exclusive double click is enabled
  25352. else {
  25353. // wait that no double click has been raised during the double click delay
  25354. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25355. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25356. }
  25357. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25358. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25359. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25360. act = _this._initActionManager(act, clickInfo);
  25361. if (act)
  25362. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25363. }
  25364. if (checkDoubleClick) {
  25365. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25366. if (btn === _this._previousButtonPressed &&
  25367. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25368. !_this._doubleClickOccured) {
  25369. // pointer has not moved for 2 clicks, it's a double click
  25370. if (!clickInfo.hasSwiped &&
  25371. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25372. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25373. _this._previousStartingPointerTime = 0;
  25374. _this._doubleClickOccured = true;
  25375. clickInfo.doubleClick = true;
  25376. clickInfo.ignore = false;
  25377. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25378. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25379. }
  25380. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25381. cb(clickInfo, _this._currentPickResult);
  25382. }
  25383. // if the two successive clicks are too far, it's just two simple clicks
  25384. else {
  25385. _this._doubleClickOccured = false;
  25386. _this._previousStartingPointerTime = _this._startingPointerTime;
  25387. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25388. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25389. _this._previousButtonPressed = btn;
  25390. if (Scene.ExclusiveDoubleClickMode) {
  25391. if (_this._previousDelayedSimpleClickTimeout) {
  25392. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25393. }
  25394. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25395. cb(clickInfo, _this._previousPickResult);
  25396. }
  25397. else {
  25398. cb(clickInfo, _this._currentPickResult);
  25399. }
  25400. }
  25401. }
  25402. // just the first click of the double has been raised
  25403. else {
  25404. _this._doubleClickOccured = false;
  25405. _this._previousStartingPointerTime = _this._startingPointerTime;
  25406. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25407. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25408. _this._previousButtonPressed = btn;
  25409. }
  25410. }
  25411. }
  25412. }
  25413. clickInfo.ignore = true;
  25414. cb(clickInfo, _this._currentPickResult);
  25415. };
  25416. this._spritePredicate = function (sprite) {
  25417. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25418. };
  25419. this._onPointerMove = function (evt) {
  25420. _this._updatePointerPosition(evt);
  25421. // PreObservable support
  25422. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25423. return;
  25424. }
  25425. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25426. return;
  25427. }
  25428. if (!_this.pointerMovePredicate) {
  25429. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25430. }
  25431. // Meshes
  25432. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25433. _this._processPointerMove(pickResult, evt);
  25434. };
  25435. this._onPointerDown = function (evt) {
  25436. _this._totalPointersPressed++;
  25437. _this._pickedDownMesh = null;
  25438. _this._meshPickProceed = false;
  25439. _this._updatePointerPosition(evt);
  25440. if (_this.preventDefaultOnPointerDown && canvas) {
  25441. evt.preventDefault();
  25442. canvas.focus();
  25443. }
  25444. // PreObservable support
  25445. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25446. return;
  25447. }
  25448. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25449. return;
  25450. }
  25451. _this._pointerCaptures[evt.pointerId] = true;
  25452. _this._startingPointerPosition.x = _this._pointerX;
  25453. _this._startingPointerPosition.y = _this._pointerY;
  25454. _this._startingPointerTime = Date.now();
  25455. if (!_this.pointerDownPredicate) {
  25456. _this.pointerDownPredicate = function (mesh) {
  25457. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25458. };
  25459. }
  25460. // Meshes
  25461. _this._pickedDownMesh = null;
  25462. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25463. _this._processPointerDown(pickResult, evt);
  25464. // Sprites
  25465. _this._pickedDownSprite = null;
  25466. if (_this.spriteManagers.length > 0) {
  25467. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25468. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25469. if (pickResult.pickedSprite.actionManager) {
  25470. _this._pickedDownSprite = pickResult.pickedSprite;
  25471. switch (evt.button) {
  25472. case 0:
  25473. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25474. break;
  25475. case 1:
  25476. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25477. break;
  25478. case 2:
  25479. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25480. break;
  25481. }
  25482. if (pickResult.pickedSprite.actionManager) {
  25483. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25484. }
  25485. }
  25486. }
  25487. }
  25488. };
  25489. this._onPointerUp = function (evt) {
  25490. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25491. return; // So we need to test it the pointer down was pressed before.
  25492. }
  25493. _this._totalPointersPressed--;
  25494. _this._pickedUpMesh = null;
  25495. _this._meshPickProceed = false;
  25496. _this._updatePointerPosition(evt);
  25497. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25498. // PreObservable support
  25499. if (_this.onPrePointerObservable.hasObservers()) {
  25500. if (!clickInfo.ignore) {
  25501. if (!clickInfo.hasSwiped) {
  25502. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25503. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25504. return;
  25505. }
  25506. }
  25507. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25508. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25509. return;
  25510. }
  25511. }
  25512. }
  25513. }
  25514. else {
  25515. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25516. return;
  25517. }
  25518. }
  25519. }
  25520. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25521. return;
  25522. }
  25523. _this._pointerCaptures[evt.pointerId] = false;
  25524. if (!_this.pointerUpPredicate) {
  25525. _this.pointerUpPredicate = function (mesh) {
  25526. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25527. };
  25528. }
  25529. // Meshes
  25530. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25531. _this._initActionManager(null, clickInfo);
  25532. }
  25533. if (!pickResult) {
  25534. pickResult = _this._currentPickResult;
  25535. }
  25536. _this._processPointerUp(pickResult, evt, clickInfo);
  25537. // Sprites
  25538. if (!clickInfo.ignore) {
  25539. if (_this.spriteManagers.length > 0) {
  25540. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25541. if (spritePickResult) {
  25542. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25543. if (spritePickResult.pickedSprite.actionManager) {
  25544. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25545. if (spritePickResult.pickedSprite.actionManager) {
  25546. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25547. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25548. }
  25549. }
  25550. }
  25551. }
  25552. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25553. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25554. }
  25555. }
  25556. }
  25557. }
  25558. _this._previousPickResult = _this._currentPickResult;
  25559. });
  25560. };
  25561. this._onKeyDown = function (evt) {
  25562. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25563. if (_this.onPreKeyboardObservable.hasObservers()) {
  25564. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25565. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25566. if (pi.skipOnPointerObservable) {
  25567. return;
  25568. }
  25569. }
  25570. if (_this.onKeyboardObservable.hasObservers()) {
  25571. var pi = new BABYLON.KeyboardInfo(type, evt);
  25572. _this.onKeyboardObservable.notifyObservers(pi, type);
  25573. }
  25574. if (_this.actionManager) {
  25575. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25576. }
  25577. };
  25578. this._onKeyUp = function (evt) {
  25579. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25580. if (_this.onPreKeyboardObservable.hasObservers()) {
  25581. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25582. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25583. if (pi.skipOnPointerObservable) {
  25584. return;
  25585. }
  25586. }
  25587. if (_this.onKeyboardObservable.hasObservers()) {
  25588. var pi = new BABYLON.KeyboardInfo(type, evt);
  25589. _this.onKeyboardObservable.notifyObservers(pi, type);
  25590. }
  25591. if (_this.actionManager) {
  25592. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25593. }
  25594. };
  25595. var engine = this.getEngine();
  25596. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25597. if (!canvas) {
  25598. return;
  25599. }
  25600. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25601. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25602. });
  25603. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25604. if (!canvas) {
  25605. return;
  25606. }
  25607. canvas.removeEventListener("keydown", _this._onKeyDown);
  25608. canvas.removeEventListener("keyup", _this._onKeyUp);
  25609. });
  25610. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25611. var canvas = this._engine.getRenderingCanvas();
  25612. if (!canvas) {
  25613. return;
  25614. }
  25615. if (attachMove) {
  25616. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25617. // Wheel
  25618. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25619. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25620. }
  25621. if (attachDown) {
  25622. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25623. }
  25624. if (attachUp) {
  25625. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25626. }
  25627. canvas.tabIndex = 1;
  25628. };
  25629. /** Detaches all event handlers*/
  25630. Scene.prototype.detachControl = function () {
  25631. var engine = this.getEngine();
  25632. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25633. var canvas = engine.getRenderingCanvas();
  25634. if (!canvas) {
  25635. return;
  25636. }
  25637. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25638. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25639. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25640. if (this._onCanvasBlurObserver) {
  25641. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25642. }
  25643. if (this._onCanvasFocusObserver) {
  25644. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25645. }
  25646. // Wheel
  25647. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25648. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25649. // Keyboard
  25650. canvas.removeEventListener("keydown", this._onKeyDown);
  25651. canvas.removeEventListener("keyup", this._onKeyUp);
  25652. // Observables
  25653. this.onKeyboardObservable.clear();
  25654. this.onPreKeyboardObservable.clear();
  25655. this.onPointerObservable.clear();
  25656. this.onPrePointerObservable.clear();
  25657. };
  25658. /**
  25659. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25660. * Delay loaded resources are not taking in account
  25661. * @return true if all required resources are ready
  25662. */
  25663. Scene.prototype.isReady = function () {
  25664. if (this._isDisposed) {
  25665. return false;
  25666. }
  25667. if (this._pendingData.length > 0) {
  25668. return false;
  25669. }
  25670. var index;
  25671. var engine = this.getEngine();
  25672. // Geometries
  25673. for (index = 0; index < this._geometries.length; index++) {
  25674. var geometry = this._geometries[index];
  25675. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25676. return false;
  25677. }
  25678. }
  25679. // Meshes
  25680. for (index = 0; index < this.meshes.length; index++) {
  25681. var mesh = this.meshes[index];
  25682. if (!mesh.isEnabled()) {
  25683. continue;
  25684. }
  25685. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25686. continue;
  25687. }
  25688. if (!mesh.isReady(true)) {
  25689. return false;
  25690. }
  25691. // Effect layers
  25692. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25693. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25694. var layer = _a[_i];
  25695. if (!layer.hasMesh(mesh)) {
  25696. continue;
  25697. }
  25698. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25699. var subMesh = _c[_b];
  25700. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25701. return false;
  25702. }
  25703. }
  25704. }
  25705. }
  25706. // Post-processes
  25707. if (this.activeCameras && this.activeCameras.length > 0) {
  25708. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25709. var camera = _e[_d];
  25710. if (!camera.isReady(true)) {
  25711. return false;
  25712. }
  25713. }
  25714. }
  25715. else if (this.activeCamera) {
  25716. if (!this.activeCamera.isReady(true)) {
  25717. return false;
  25718. }
  25719. }
  25720. // Particles
  25721. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25722. var particleSystem = _g[_f];
  25723. if (!particleSystem.isReady()) {
  25724. return false;
  25725. }
  25726. }
  25727. return true;
  25728. };
  25729. /** Resets all cached information relative to material (including effect and visibility) */
  25730. Scene.prototype.resetCachedMaterial = function () {
  25731. this._cachedMaterial = null;
  25732. this._cachedEffect = null;
  25733. this._cachedVisibility = null;
  25734. };
  25735. /**
  25736. * Registers a function to be called before every frame render
  25737. * @param func defines the function to register
  25738. */
  25739. Scene.prototype.registerBeforeRender = function (func) {
  25740. this.onBeforeRenderObservable.add(func);
  25741. };
  25742. /**
  25743. * Unregisters a function called before every frame render
  25744. * @param func defines the function to unregister
  25745. */
  25746. Scene.prototype.unregisterBeforeRender = function (func) {
  25747. this.onBeforeRenderObservable.removeCallback(func);
  25748. };
  25749. /**
  25750. * Registers a function to be called after every frame render
  25751. * @param func defines the function to register
  25752. */
  25753. Scene.prototype.registerAfterRender = function (func) {
  25754. this.onAfterRenderObservable.add(func);
  25755. };
  25756. /**
  25757. * Unregisters a function called after every frame render
  25758. * @param func defines the function to unregister
  25759. */
  25760. Scene.prototype.unregisterAfterRender = function (func) {
  25761. this.onAfterRenderObservable.removeCallback(func);
  25762. };
  25763. Scene.prototype._executeOnceBeforeRender = function (func) {
  25764. var _this = this;
  25765. var execFunc = function () {
  25766. func();
  25767. setTimeout(function () {
  25768. _this.unregisterBeforeRender(execFunc);
  25769. });
  25770. };
  25771. this.registerBeforeRender(execFunc);
  25772. };
  25773. /**
  25774. * The provided function will run before render once and will be disposed afterwards.
  25775. * A timeout delay can be provided so that the function will be executed in N ms.
  25776. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25777. * @param func The function to be executed.
  25778. * @param timeout optional delay in ms
  25779. */
  25780. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25781. var _this = this;
  25782. if (timeout !== undefined) {
  25783. setTimeout(function () {
  25784. _this._executeOnceBeforeRender(func);
  25785. }, timeout);
  25786. }
  25787. else {
  25788. this._executeOnceBeforeRender(func);
  25789. }
  25790. };
  25791. /** @hidden */
  25792. Scene.prototype._addPendingData = function (data) {
  25793. this._pendingData.push(data);
  25794. };
  25795. /** @hidden */
  25796. Scene.prototype._removePendingData = function (data) {
  25797. var wasLoading = this.isLoading;
  25798. var index = this._pendingData.indexOf(data);
  25799. if (index !== -1) {
  25800. this._pendingData.splice(index, 1);
  25801. }
  25802. if (wasLoading && !this.isLoading) {
  25803. this.onDataLoadedObservable.notifyObservers(this);
  25804. }
  25805. };
  25806. /**
  25807. * Returns the number of items waiting to be loaded
  25808. * @returns the number of items waiting to be loaded
  25809. */
  25810. Scene.prototype.getWaitingItemsCount = function () {
  25811. return this._pendingData.length;
  25812. };
  25813. Object.defineProperty(Scene.prototype, "isLoading", {
  25814. /**
  25815. * Returns a boolean indicating if the scene is still loading data
  25816. */
  25817. get: function () {
  25818. return this._pendingData.length > 0;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. /**
  25824. * Registers a function to be executed when the scene is ready
  25825. * @param {Function} func - the function to be executed
  25826. */
  25827. Scene.prototype.executeWhenReady = function (func) {
  25828. var _this = this;
  25829. this.onReadyObservable.add(func);
  25830. if (this._executeWhenReadyTimeoutId !== -1) {
  25831. return;
  25832. }
  25833. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25834. _this._checkIsReady();
  25835. }, 150);
  25836. };
  25837. /**
  25838. * Returns a promise that resolves when the scene is ready
  25839. * @returns A promise that resolves when the scene is ready
  25840. */
  25841. Scene.prototype.whenReadyAsync = function () {
  25842. var _this = this;
  25843. return new Promise(function (resolve) {
  25844. _this.executeWhenReady(function () {
  25845. resolve();
  25846. });
  25847. });
  25848. };
  25849. /** @hidden */
  25850. Scene.prototype._checkIsReady = function () {
  25851. var _this = this;
  25852. if (this.isReady()) {
  25853. this.onReadyObservable.notifyObservers(this);
  25854. this.onReadyObservable.clear();
  25855. this._executeWhenReadyTimeoutId = -1;
  25856. return;
  25857. }
  25858. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25859. _this._checkIsReady();
  25860. }, 150);
  25861. };
  25862. // Animations
  25863. /**
  25864. * Will start the animation sequence of a given target
  25865. * @param target defines the target
  25866. * @param from defines from which frame should animation start
  25867. * @param to defines until which frame should animation run.
  25868. * @param weight defines the weight to apply to the animation (1.0 by default)
  25869. * @param loop defines if the animation loops
  25870. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25871. * @param onAnimationEnd defines the function to be executed when the animation ends
  25872. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25873. * @returns the animatable object created for this animation
  25874. */
  25875. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25876. if (weight === void 0) { weight = 1.0; }
  25877. if (speedRatio === void 0) { speedRatio = 1.0; }
  25878. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25879. returnedAnimatable.weight = weight;
  25880. return returnedAnimatable;
  25881. };
  25882. /**
  25883. * Will start the animation sequence of a given target
  25884. * @param target defines the target
  25885. * @param from defines from which frame should animation start
  25886. * @param to defines until which frame should animation run.
  25887. * @param loop defines if the animation loops
  25888. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25889. * @param onAnimationEnd defines the function to be executed when the animation ends
  25890. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25891. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25892. * @returns the animatable object created for this animation
  25893. */
  25894. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25895. if (speedRatio === void 0) { speedRatio = 1.0; }
  25896. if (stopCurrent === void 0) { stopCurrent = true; }
  25897. if (from > to && speedRatio > 0) {
  25898. speedRatio *= -1;
  25899. }
  25900. if (stopCurrent) {
  25901. this.stopAnimation(target);
  25902. }
  25903. if (!animatable) {
  25904. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25905. }
  25906. // Local animations
  25907. if (target.animations) {
  25908. animatable.appendAnimations(target, target.animations);
  25909. }
  25910. // Children animations
  25911. if (target.getAnimatables) {
  25912. var animatables = target.getAnimatables();
  25913. for (var index = 0; index < animatables.length; index++) {
  25914. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25915. }
  25916. }
  25917. animatable.reset();
  25918. return animatable;
  25919. };
  25920. /**
  25921. * Begin a new animation on a given node
  25922. * @param target defines the target where the animation will take place
  25923. * @param animations defines the list of animations to start
  25924. * @param from defines the initial value
  25925. * @param to defines the final value
  25926. * @param loop defines if you want animation to loop (off by default)
  25927. * @param speedRatio defines the speed ratio to apply to all animations
  25928. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25929. * @returns the list of created animatables
  25930. */
  25931. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25932. if (speedRatio === undefined) {
  25933. speedRatio = 1.0;
  25934. }
  25935. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25936. return animatable;
  25937. };
  25938. /**
  25939. * Begin a new animation on a given node and its hierarchy
  25940. * @param target defines the root node where the animation will take place
  25941. * @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.
  25942. * @param animations defines the list of animations to start
  25943. * @param from defines the initial value
  25944. * @param to defines the final value
  25945. * @param loop defines if you want animation to loop (off by default)
  25946. * @param speedRatio defines the speed ratio to apply to all animations
  25947. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25948. * @returns the list of animatables created for all nodes
  25949. */
  25950. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25951. var children = target.getDescendants(directDescendantsOnly);
  25952. var result = [];
  25953. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25954. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25955. var child = children_1[_i];
  25956. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25957. }
  25958. return result;
  25959. };
  25960. /**
  25961. * Gets the animatable associated with a specific target
  25962. * @param target defines the target of the animatable
  25963. * @returns the required animatable if found
  25964. */
  25965. Scene.prototype.getAnimatableByTarget = function (target) {
  25966. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25967. if (this._activeAnimatables[index].target === target) {
  25968. return this._activeAnimatables[index];
  25969. }
  25970. }
  25971. return null;
  25972. };
  25973. /**
  25974. * Gets all animatables associated with a given target
  25975. * @param target defines the target to look animatables for
  25976. * @returns an array of Animatables
  25977. */
  25978. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25979. var result = [];
  25980. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25981. if (this._activeAnimatables[index].target === target) {
  25982. result.push(this._activeAnimatables[index]);
  25983. }
  25984. }
  25985. return result;
  25986. };
  25987. Object.defineProperty(Scene.prototype, "animatables", {
  25988. /**
  25989. * Gets all animatable attached to the scene
  25990. */
  25991. get: function () {
  25992. return this._activeAnimatables;
  25993. },
  25994. enumerable: true,
  25995. configurable: true
  25996. });
  25997. /**
  25998. * Will stop the animation of the given target
  25999. * @param target - the target
  26000. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26001. */
  26002. Scene.prototype.stopAnimation = function (target, animationName) {
  26003. var animatables = this.getAllAnimatablesByTarget(target);
  26004. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26005. var animatable = animatables_1[_i];
  26006. animatable.stop(animationName);
  26007. }
  26008. };
  26009. /**
  26010. * Stops and removes all animations that have been applied to the scene
  26011. */
  26012. Scene.prototype.stopAllAnimations = function () {
  26013. if (this._activeAnimatables) {
  26014. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26015. this._activeAnimatables[i].stop();
  26016. }
  26017. this._activeAnimatables = [];
  26018. }
  26019. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26020. var group = _a[_i];
  26021. group.stop();
  26022. }
  26023. };
  26024. Scene.prototype._animate = function () {
  26025. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26026. return;
  26027. }
  26028. // Getting time
  26029. var now = BABYLON.Tools.Now;
  26030. if (!this._animationTimeLast) {
  26031. if (this._pendingData.length > 0) {
  26032. return;
  26033. }
  26034. this._animationTimeLast = now;
  26035. }
  26036. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26037. this._animationTime += deltaTime;
  26038. this._animationTimeLast = now;
  26039. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26040. this._activeAnimatables[index]._animate(this._animationTime);
  26041. }
  26042. // Late animation bindings
  26043. this._processLateAnimationBindings();
  26044. };
  26045. /** @hidden */
  26046. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26047. var target = runtimeAnimation.target;
  26048. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26049. if (!target._lateAnimationHolders) {
  26050. target._lateAnimationHolders = {};
  26051. }
  26052. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26053. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26054. totalWeight: 0,
  26055. animations: [],
  26056. originalValue: originalValue
  26057. };
  26058. }
  26059. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26060. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26061. };
  26062. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26063. var normalizer = 1.0;
  26064. var finalPosition = BABYLON.Tmp.Vector3[0];
  26065. var finalScaling = BABYLON.Tmp.Vector3[1];
  26066. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26067. var startIndex = 0;
  26068. var originalAnimation = holder.animations[0];
  26069. var originalValue = holder.originalValue;
  26070. var scale = 1;
  26071. if (holder.totalWeight < 1.0) {
  26072. // We need to mix the original value in
  26073. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26074. scale = 1.0 - holder.totalWeight;
  26075. }
  26076. else {
  26077. startIndex = 1;
  26078. // We need to normalize the weights
  26079. normalizer = holder.totalWeight;
  26080. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26081. scale = originalAnimation.weight / normalizer;
  26082. if (scale == 1) {
  26083. return originalAnimation.currentValue;
  26084. }
  26085. }
  26086. finalScaling.scaleInPlace(scale);
  26087. finalPosition.scaleInPlace(scale);
  26088. finalQuaternion.scaleInPlace(scale);
  26089. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26090. var runtimeAnimation = holder.animations[animIndex];
  26091. var scale = runtimeAnimation.weight / normalizer;
  26092. var currentPosition = BABYLON.Tmp.Vector3[2];
  26093. var currentScaling = BABYLON.Tmp.Vector3[3];
  26094. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26095. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26096. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26097. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26098. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26099. }
  26100. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26101. return originalAnimation._workValue;
  26102. };
  26103. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26104. var originalAnimation = holder.animations[0];
  26105. var originalValue = holder.originalValue;
  26106. if (holder.animations.length === 1) {
  26107. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26108. }
  26109. var normalizer = 1.0;
  26110. var quaternions;
  26111. var weights;
  26112. if (holder.totalWeight < 1.0) {
  26113. var scale = 1.0 - holder.totalWeight;
  26114. quaternions = [];
  26115. weights = [];
  26116. quaternions.push(originalValue);
  26117. weights.push(scale);
  26118. }
  26119. else {
  26120. if (holder.animations.length === 2) { // Slerp as soon as we can
  26121. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26122. }
  26123. quaternions = [];
  26124. weights = [];
  26125. normalizer = holder.totalWeight;
  26126. }
  26127. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26128. var runtimeAnimation = holder.animations[animIndex];
  26129. quaternions.push(runtimeAnimation.currentValue);
  26130. weights.push(runtimeAnimation.weight / normalizer);
  26131. }
  26132. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26133. var cumulativeAmount = 0;
  26134. var cumulativeQuaternion = null;
  26135. for (var index = 0; index < quaternions.length;) {
  26136. if (!cumulativeQuaternion) {
  26137. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26138. cumulativeAmount = weights[index] + weights[index + 1];
  26139. index += 2;
  26140. continue;
  26141. }
  26142. cumulativeAmount += weights[index];
  26143. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26144. index++;
  26145. }
  26146. return cumulativeQuaternion;
  26147. };
  26148. Scene.prototype._processLateAnimationBindings = function () {
  26149. if (!this._registeredForLateAnimationBindings.length) {
  26150. return;
  26151. }
  26152. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26153. var target = this._registeredForLateAnimationBindings.data[index];
  26154. for (var path in target._lateAnimationHolders) {
  26155. var holder = target._lateAnimationHolders[path];
  26156. var originalAnimation = holder.animations[0];
  26157. var originalValue = holder.originalValue;
  26158. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26159. var finalValue = void 0;
  26160. if (matrixDecomposeMode) {
  26161. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26162. }
  26163. else {
  26164. var quaternionMode = originalValue.w !== undefined;
  26165. if (quaternionMode) {
  26166. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26167. }
  26168. else {
  26169. var startIndex = 0;
  26170. var normalizer = 1.0;
  26171. if (holder.totalWeight < 1.0) {
  26172. // We need to mix the original value in
  26173. if (originalValue.scale) {
  26174. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26175. }
  26176. else {
  26177. finalValue = originalValue * (1.0 - holder.totalWeight);
  26178. }
  26179. }
  26180. else {
  26181. // We need to normalize the weights
  26182. normalizer = holder.totalWeight;
  26183. var scale_1 = originalAnimation.weight / normalizer;
  26184. if (scale_1 !== 1) {
  26185. if (originalAnimation.currentValue.scale) {
  26186. finalValue = originalAnimation.currentValue.scale(scale_1);
  26187. }
  26188. else {
  26189. finalValue = originalAnimation.currentValue * scale_1;
  26190. }
  26191. }
  26192. else {
  26193. finalValue = originalAnimation.currentValue;
  26194. }
  26195. startIndex = 1;
  26196. }
  26197. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26198. var runtimeAnimation = holder.animations[animIndex];
  26199. var scale = runtimeAnimation.weight / normalizer;
  26200. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26201. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26202. }
  26203. else {
  26204. finalValue += runtimeAnimation.currentValue * scale;
  26205. }
  26206. }
  26207. }
  26208. }
  26209. target[path] = finalValue;
  26210. }
  26211. target._lateAnimationHolders = {};
  26212. }
  26213. this._registeredForLateAnimationBindings.reset();
  26214. };
  26215. // Matrix
  26216. /** @hidden */
  26217. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26218. this._useAlternateCameraConfiguration = active;
  26219. };
  26220. /**
  26221. * Gets the current view matrix
  26222. * @returns a Matrix
  26223. */
  26224. Scene.prototype.getViewMatrix = function () {
  26225. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26226. };
  26227. /**
  26228. * Gets the current projection matrix
  26229. * @returns a Matrix
  26230. */
  26231. Scene.prototype.getProjectionMatrix = function () {
  26232. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26233. };
  26234. /**
  26235. * Gets the current transform matrix
  26236. * @returns a Matrix made of View * Projection
  26237. */
  26238. Scene.prototype.getTransformMatrix = function () {
  26239. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26240. };
  26241. /**
  26242. * Sets the current transform matrix
  26243. * @param view defines the View matrix to use
  26244. * @param projection defines the Projection matrix to use
  26245. */
  26246. Scene.prototype.setTransformMatrix = function (view, projection) {
  26247. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26248. return;
  26249. }
  26250. this._viewUpdateFlag = view.updateFlag;
  26251. this._projectionUpdateFlag = projection.updateFlag;
  26252. this._viewMatrix = view;
  26253. this._projectionMatrix = projection;
  26254. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26255. // Update frustum
  26256. if (!this._frustumPlanes) {
  26257. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26258. }
  26259. else {
  26260. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26261. }
  26262. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26263. var otherCamera = this.activeCamera._alternateCamera;
  26264. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26265. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26266. }
  26267. if (this._sceneUbo.useUbo) {
  26268. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26269. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26270. this._sceneUbo.update();
  26271. }
  26272. };
  26273. /** @hidden */
  26274. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26275. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26276. return;
  26277. }
  26278. this._alternateViewUpdateFlag = view.updateFlag;
  26279. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26280. this._alternateViewMatrix = view;
  26281. this._alternateProjectionMatrix = projection;
  26282. if (!this._alternateTransformMatrix) {
  26283. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26284. }
  26285. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26286. if (!this._alternateSceneUbo) {
  26287. this._createAlternateUbo();
  26288. }
  26289. if (this._alternateSceneUbo.useUbo) {
  26290. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26291. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26292. this._alternateSceneUbo.update();
  26293. }
  26294. };
  26295. /**
  26296. * Gets the uniform buffer used to store scene data
  26297. * @returns a UniformBuffer
  26298. */
  26299. Scene.prototype.getSceneUniformBuffer = function () {
  26300. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26301. };
  26302. /**
  26303. * Gets an unique (relatively to the current scene) Id
  26304. * @returns an unique number for the scene
  26305. */
  26306. Scene.prototype.getUniqueId = function () {
  26307. var result = Scene._uniqueIdCounter;
  26308. Scene._uniqueIdCounter++;
  26309. return result;
  26310. };
  26311. /**
  26312. * Add a mesh to the list of scene's meshes
  26313. * @param newMesh defines the mesh to add
  26314. * @param recursive if all child meshes should also be added to the scene
  26315. */
  26316. Scene.prototype.addMesh = function (newMesh, recursive) {
  26317. var _this = this;
  26318. if (recursive === void 0) { recursive = false; }
  26319. this.meshes.push(newMesh);
  26320. //notify the collision coordinator
  26321. if (this.collisionCoordinator) {
  26322. this.collisionCoordinator.onMeshAdded(newMesh);
  26323. }
  26324. newMesh._resyncLightSources();
  26325. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26326. if (recursive) {
  26327. newMesh.getChildMeshes().forEach(function (m) {
  26328. _this.addMesh(m);
  26329. });
  26330. }
  26331. };
  26332. /**
  26333. * Remove a mesh for the list of scene's meshes
  26334. * @param toRemove defines the mesh to remove
  26335. * @param recursive if all child meshes should also be removed from the scene
  26336. * @returns the index where the mesh was in the mesh list
  26337. */
  26338. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26339. var _this = this;
  26340. if (recursive === void 0) { recursive = false; }
  26341. var index = this.meshes.indexOf(toRemove);
  26342. if (index !== -1) {
  26343. // Remove from the scene if mesh found
  26344. this.meshes.splice(index, 1);
  26345. }
  26346. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26347. if (recursive) {
  26348. toRemove.getChildMeshes().forEach(function (m) {
  26349. _this.removeMesh(m);
  26350. });
  26351. }
  26352. return index;
  26353. };
  26354. /**
  26355. * Add a transform node to the list of scene's transform nodes
  26356. * @param newTransformNode defines the transform node to add
  26357. */
  26358. Scene.prototype.addTransformNode = function (newTransformNode) {
  26359. this.transformNodes.push(newTransformNode);
  26360. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26361. };
  26362. /**
  26363. * Remove a transform node for the list of scene's transform nodes
  26364. * @param toRemove defines the transform node to remove
  26365. * @returns the index where the transform node was in the transform node list
  26366. */
  26367. Scene.prototype.removeTransformNode = function (toRemove) {
  26368. var index = this.transformNodes.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. // Remove from the scene if found
  26371. this.transformNodes.splice(index, 1);
  26372. }
  26373. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26374. return index;
  26375. };
  26376. /**
  26377. * Remove a skeleton for the list of scene's skeletons
  26378. * @param toRemove defines the skeleton to remove
  26379. * @returns the index where the skeleton was in the skeleton list
  26380. */
  26381. Scene.prototype.removeSkeleton = function (toRemove) {
  26382. var index = this.skeletons.indexOf(toRemove);
  26383. if (index !== -1) {
  26384. // Remove from the scene if found
  26385. this.skeletons.splice(index, 1);
  26386. }
  26387. return index;
  26388. };
  26389. /**
  26390. * Remove a morph target for the list of scene's morph targets
  26391. * @param toRemove defines the morph target to remove
  26392. * @returns the index where the morph target was in the morph target list
  26393. */
  26394. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26395. var index = this.morphTargetManagers.indexOf(toRemove);
  26396. if (index !== -1) {
  26397. // Remove from the scene if found
  26398. this.morphTargetManagers.splice(index, 1);
  26399. }
  26400. return index;
  26401. };
  26402. /**
  26403. * Remove a light for the list of scene's lights
  26404. * @param toRemove defines the light to remove
  26405. * @returns the index where the light was in the light list
  26406. */
  26407. Scene.prototype.removeLight = function (toRemove) {
  26408. var index = this.lights.indexOf(toRemove);
  26409. if (index !== -1) {
  26410. // Remove from meshes
  26411. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26412. var mesh = _a[_i];
  26413. mesh._removeLightSource(toRemove);
  26414. }
  26415. // Remove from the scene if mesh found
  26416. this.lights.splice(index, 1);
  26417. this.sortLightsByPriority();
  26418. }
  26419. this.onLightRemovedObservable.notifyObservers(toRemove);
  26420. return index;
  26421. };
  26422. /**
  26423. * Remove a camera for the list of scene's cameras
  26424. * @param toRemove defines the camera to remove
  26425. * @returns the index where the camera was in the camera list
  26426. */
  26427. Scene.prototype.removeCamera = function (toRemove) {
  26428. var index = this.cameras.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. // Remove from the scene if mesh found
  26431. this.cameras.splice(index, 1);
  26432. }
  26433. // Remove from activeCameras
  26434. var index2 = this.activeCameras.indexOf(toRemove);
  26435. if (index2 !== -1) {
  26436. // Remove from the scene if mesh found
  26437. this.activeCameras.splice(index2, 1);
  26438. }
  26439. // Reset the activeCamera
  26440. if (this.activeCamera === toRemove) {
  26441. if (this.cameras.length > 0) {
  26442. this.activeCamera = this.cameras[0];
  26443. }
  26444. else {
  26445. this.activeCamera = null;
  26446. }
  26447. }
  26448. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26449. return index;
  26450. };
  26451. /**
  26452. * Remove a particle system for the list of scene's particle systems
  26453. * @param toRemove defines the particle system to remove
  26454. * @returns the index where the particle system was in the particle system list
  26455. */
  26456. Scene.prototype.removeParticleSystem = function (toRemove) {
  26457. var index = this.particleSystems.indexOf(toRemove);
  26458. if (index !== -1) {
  26459. this.particleSystems.splice(index, 1);
  26460. }
  26461. return index;
  26462. };
  26463. /**
  26464. * Remove a animation for the list of scene's animations
  26465. * @param toRemove defines the animation to remove
  26466. * @returns the index where the animation was in the animation list
  26467. */
  26468. Scene.prototype.removeAnimation = function (toRemove) {
  26469. var index = this.animations.indexOf(toRemove);
  26470. if (index !== -1) {
  26471. this.animations.splice(index, 1);
  26472. }
  26473. return index;
  26474. };
  26475. /**
  26476. * Removes the given animation group from this scene.
  26477. * @param toRemove The animation group to remove
  26478. * @returns The index of the removed animation group
  26479. */
  26480. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26481. var index = this.animationGroups.indexOf(toRemove);
  26482. if (index !== -1) {
  26483. this.animationGroups.splice(index, 1);
  26484. }
  26485. return index;
  26486. };
  26487. /**
  26488. * Removes the given multi-material from this scene.
  26489. * @param toRemove The multi-material to remove
  26490. * @returns The index of the removed multi-material
  26491. */
  26492. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26493. var index = this.multiMaterials.indexOf(toRemove);
  26494. if (index !== -1) {
  26495. this.multiMaterials.splice(index, 1);
  26496. }
  26497. return index;
  26498. };
  26499. /**
  26500. * Removes the given material from this scene.
  26501. * @param toRemove The material to remove
  26502. * @returns The index of the removed material
  26503. */
  26504. Scene.prototype.removeMaterial = function (toRemove) {
  26505. var index = this.materials.indexOf(toRemove);
  26506. if (index !== -1) {
  26507. this.materials.splice(index, 1);
  26508. }
  26509. return index;
  26510. };
  26511. /**
  26512. * Removes the given lens flare system from this scene.
  26513. * @param toRemove The lens flare system to remove
  26514. * @returns The index of the removed lens flare system
  26515. */
  26516. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26517. var index = this.lensFlareSystems.indexOf(toRemove);
  26518. if (index !== -1) {
  26519. this.lensFlareSystems.splice(index, 1);
  26520. }
  26521. return index;
  26522. };
  26523. /**
  26524. * Removes the given action manager from this scene.
  26525. * @param toRemove The action manager to remove
  26526. * @returns The index of the removed action manager
  26527. */
  26528. Scene.prototype.removeActionManager = function (toRemove) {
  26529. var index = this._actionManagers.indexOf(toRemove);
  26530. if (index !== -1) {
  26531. this._actionManagers.splice(index, 1);
  26532. }
  26533. return index;
  26534. };
  26535. /**
  26536. * Removes the given effect layer from this scene.
  26537. * @param toRemove defines the effect layer to remove
  26538. * @returns the index of the removed effect layer
  26539. */
  26540. Scene.prototype.removeEffectLayer = function (toRemove) {
  26541. var index = this.effectLayers.indexOf(toRemove);
  26542. if (index !== -1) {
  26543. this.effectLayers.splice(index, 1);
  26544. }
  26545. return index;
  26546. };
  26547. /**
  26548. * Removes the given texture from this scene.
  26549. * @param toRemove The texture to remove
  26550. * @returns The index of the removed texture
  26551. */
  26552. Scene.prototype.removeTexture = function (toRemove) {
  26553. var index = this.textures.indexOf(toRemove);
  26554. if (index !== -1) {
  26555. this.textures.splice(index, 1);
  26556. }
  26557. return index;
  26558. };
  26559. /**
  26560. * Adds the given light to this scene
  26561. * @param newLight The light to add
  26562. */
  26563. Scene.prototype.addLight = function (newLight) {
  26564. this.lights.push(newLight);
  26565. this.sortLightsByPriority();
  26566. // Add light to all meshes (To support if the light is removed and then readded)
  26567. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26568. var mesh = _a[_i];
  26569. if (mesh._lightSources.indexOf(newLight) === -1) {
  26570. mesh._lightSources.push(newLight);
  26571. mesh._resyncLightSources();
  26572. }
  26573. }
  26574. this.onNewLightAddedObservable.notifyObservers(newLight);
  26575. };
  26576. /**
  26577. * Sorts the list list based on light priorities
  26578. */
  26579. Scene.prototype.sortLightsByPriority = function () {
  26580. if (this.requireLightSorting) {
  26581. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26582. }
  26583. };
  26584. /**
  26585. * Adds the given camera to this scene
  26586. * @param newCamera The camera to add
  26587. */
  26588. Scene.prototype.addCamera = function (newCamera) {
  26589. this.cameras.push(newCamera);
  26590. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26591. };
  26592. /**
  26593. * Adds the given skeleton to this scene
  26594. * @param newSkeleton The skeleton to add
  26595. */
  26596. Scene.prototype.addSkeleton = function (newSkeleton) {
  26597. this.skeletons.push(newSkeleton);
  26598. };
  26599. /**
  26600. * Adds the given particle system to this scene
  26601. * @param newParticleSystem The particle system to add
  26602. */
  26603. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26604. this.particleSystems.push(newParticleSystem);
  26605. };
  26606. /**
  26607. * Adds the given animation to this scene
  26608. * @param newAnimation The animation to add
  26609. */
  26610. Scene.prototype.addAnimation = function (newAnimation) {
  26611. this.animations.push(newAnimation);
  26612. };
  26613. /**
  26614. * Adds the given animation group to this scene.
  26615. * @param newAnimationGroup The animation group to add
  26616. */
  26617. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26618. this.animationGroups.push(newAnimationGroup);
  26619. };
  26620. /**
  26621. * Adds the given multi-material to this scene
  26622. * @param newMultiMaterial The multi-material to add
  26623. */
  26624. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26625. this.multiMaterials.push(newMultiMaterial);
  26626. };
  26627. /**
  26628. * Adds the given material to this scene
  26629. * @param newMaterial The material to add
  26630. */
  26631. Scene.prototype.addMaterial = function (newMaterial) {
  26632. this.materials.push(newMaterial);
  26633. };
  26634. /**
  26635. * Adds the given morph target to this scene
  26636. * @param newMorphTargetManager The morph target to add
  26637. */
  26638. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26639. this.morphTargetManagers.push(newMorphTargetManager);
  26640. };
  26641. /**
  26642. * Adds the given geometry to this scene
  26643. * @param newGeometry The geometry to add
  26644. */
  26645. Scene.prototype.addGeometry = function (newGeometry) {
  26646. this._geometries.push(newGeometry);
  26647. };
  26648. /**
  26649. * Adds the given lens flare system to this scene
  26650. * @param newLensFlareSystem The lens flare system to add
  26651. */
  26652. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26653. this.lensFlareSystems.push(newLensFlareSystem);
  26654. };
  26655. /**
  26656. * Adds the given effect layer to this scene
  26657. * @param newEffectLayer defines the effect layer to add
  26658. */
  26659. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26660. this.effectLayers.push(newEffectLayer);
  26661. };
  26662. /**
  26663. * Adds the given action manager to this scene
  26664. * @param newActionManager The action manager to add
  26665. */
  26666. Scene.prototype.addActionManager = function (newActionManager) {
  26667. this._actionManagers.push(newActionManager);
  26668. };
  26669. /**
  26670. * Adds the given texture to this scene.
  26671. * @param newTexture The texture to add
  26672. */
  26673. Scene.prototype.addTexture = function (newTexture) {
  26674. this.textures.push(newTexture);
  26675. };
  26676. /**
  26677. * Switch active camera
  26678. * @param newCamera defines the new active camera
  26679. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26680. */
  26681. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26682. if (attachControl === void 0) { attachControl = true; }
  26683. var canvas = this._engine.getRenderingCanvas();
  26684. if (!canvas) {
  26685. return;
  26686. }
  26687. if (this.activeCamera) {
  26688. this.activeCamera.detachControl(canvas);
  26689. }
  26690. this.activeCamera = newCamera;
  26691. if (attachControl) {
  26692. newCamera.attachControl(canvas);
  26693. }
  26694. };
  26695. /**
  26696. * sets the active camera of the scene using its ID
  26697. * @param id defines the camera's ID
  26698. * @return the new active camera or null if none found.
  26699. */
  26700. Scene.prototype.setActiveCameraByID = function (id) {
  26701. var camera = this.getCameraByID(id);
  26702. if (camera) {
  26703. this.activeCamera = camera;
  26704. return camera;
  26705. }
  26706. return null;
  26707. };
  26708. /**
  26709. * sets the active camera of the scene using its name
  26710. * @param name defines the camera's name
  26711. * @returns the new active camera or null if none found.
  26712. */
  26713. Scene.prototype.setActiveCameraByName = function (name) {
  26714. var camera = this.getCameraByName(name);
  26715. if (camera) {
  26716. this.activeCamera = camera;
  26717. return camera;
  26718. }
  26719. return null;
  26720. };
  26721. /**
  26722. * get an animation group using its name
  26723. * @param name defines the material's name
  26724. * @return the animation group or null if none found.
  26725. */
  26726. Scene.prototype.getAnimationGroupByName = function (name) {
  26727. for (var index = 0; index < this.animationGroups.length; index++) {
  26728. if (this.animationGroups[index].name === name) {
  26729. return this.animationGroups[index];
  26730. }
  26731. }
  26732. return null;
  26733. };
  26734. /**
  26735. * get a material using its id
  26736. * @param id defines the material's ID
  26737. * @return the material or null if none found.
  26738. */
  26739. Scene.prototype.getMaterialByID = function (id) {
  26740. for (var index = 0; index < this.materials.length; index++) {
  26741. if (this.materials[index].id === id) {
  26742. return this.materials[index];
  26743. }
  26744. }
  26745. return null;
  26746. };
  26747. /**
  26748. * Gets a material using its name
  26749. * @param name defines the material's name
  26750. * @return the material or null if none found.
  26751. */
  26752. Scene.prototype.getMaterialByName = function (name) {
  26753. for (var index = 0; index < this.materials.length; index++) {
  26754. if (this.materials[index].name === name) {
  26755. return this.materials[index];
  26756. }
  26757. }
  26758. return null;
  26759. };
  26760. /**
  26761. * Gets a lens flare system using its name
  26762. * @param name defines the name to look for
  26763. * @returns the lens flare system or null if not found
  26764. */
  26765. Scene.prototype.getLensFlareSystemByName = function (name) {
  26766. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26767. if (this.lensFlareSystems[index].name === name) {
  26768. return this.lensFlareSystems[index];
  26769. }
  26770. }
  26771. return null;
  26772. };
  26773. /**
  26774. * Gets a lens flare system using its id
  26775. * @param id defines the id to look for
  26776. * @returns the lens flare system or null if not found
  26777. */
  26778. Scene.prototype.getLensFlareSystemByID = function (id) {
  26779. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26780. if (this.lensFlareSystems[index].id === id) {
  26781. return this.lensFlareSystems[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a camera using its id
  26788. * @param id defines the id to look for
  26789. * @returns the camera or null if not found
  26790. */
  26791. Scene.prototype.getCameraByID = function (id) {
  26792. for (var index = 0; index < this.cameras.length; index++) {
  26793. if (this.cameras[index].id === id) {
  26794. return this.cameras[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a camera using its unique id
  26801. * @param uniqueId defines the unique id to look for
  26802. * @returns the camera or null if not found
  26803. */
  26804. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26805. for (var index = 0; index < this.cameras.length; index++) {
  26806. if (this.cameras[index].uniqueId === uniqueId) {
  26807. return this.cameras[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a camera using its name
  26814. * @param name defines the camera's name
  26815. * @return the camera or null if none found.
  26816. */
  26817. Scene.prototype.getCameraByName = function (name) {
  26818. for (var index = 0; index < this.cameras.length; index++) {
  26819. if (this.cameras[index].name === name) {
  26820. return this.cameras[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a bone using its id
  26827. * @param id defines the bone's id
  26828. * @return the bone or null if not found
  26829. */
  26830. Scene.prototype.getBoneByID = function (id) {
  26831. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26832. var skeleton = this.skeletons[skeletonIndex];
  26833. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26834. if (skeleton.bones[boneIndex].id === id) {
  26835. return skeleton.bones[boneIndex];
  26836. }
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a bone using its id
  26843. * @param name defines the bone's name
  26844. * @return the bone or null if not found
  26845. */
  26846. Scene.prototype.getBoneByName = function (name) {
  26847. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26848. var skeleton = this.skeletons[skeletonIndex];
  26849. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26850. if (skeleton.bones[boneIndex].name === name) {
  26851. return skeleton.bones[boneIndex];
  26852. }
  26853. }
  26854. }
  26855. return null;
  26856. };
  26857. /**
  26858. * Gets a light node using its name
  26859. * @param name defines the the light's name
  26860. * @return the light or null if none found.
  26861. */
  26862. Scene.prototype.getLightByName = function (name) {
  26863. for (var index = 0; index < this.lights.length; index++) {
  26864. if (this.lights[index].name === name) {
  26865. return this.lights[index];
  26866. }
  26867. }
  26868. return null;
  26869. };
  26870. /**
  26871. * Gets a light node using its id
  26872. * @param id defines the light's id
  26873. * @return the light or null if none found.
  26874. */
  26875. Scene.prototype.getLightByID = function (id) {
  26876. for (var index = 0; index < this.lights.length; index++) {
  26877. if (this.lights[index].id === id) {
  26878. return this.lights[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a light node using its scene-generated unique ID
  26885. * @param uniqueId defines the light's unique id
  26886. * @return the light or null if none found.
  26887. */
  26888. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26889. for (var index = 0; index < this.lights.length; index++) {
  26890. if (this.lights[index].uniqueId === uniqueId) {
  26891. return this.lights[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a particle system by id
  26898. * @param id defines the particle system id
  26899. * @return the corresponding system or null if none found
  26900. */
  26901. Scene.prototype.getParticleSystemByID = function (id) {
  26902. for (var index = 0; index < this.particleSystems.length; index++) {
  26903. if (this.particleSystems[index].id === id) {
  26904. return this.particleSystems[index];
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a geometry using its ID
  26911. * @param id defines the geometry's id
  26912. * @return the geometry or null if none found.
  26913. */
  26914. Scene.prototype.getGeometryByID = function (id) {
  26915. for (var index = 0; index < this._geometries.length; index++) {
  26916. if (this._geometries[index].id === id) {
  26917. return this._geometries[index];
  26918. }
  26919. }
  26920. return null;
  26921. };
  26922. /**
  26923. * Add a new geometry to this scene
  26924. * @param geometry defines the geometry to be added to the scene.
  26925. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26926. * @return a boolean defining if the geometry was added or not
  26927. */
  26928. Scene.prototype.pushGeometry = function (geometry, force) {
  26929. if (!force && this.getGeometryByID(geometry.id)) {
  26930. return false;
  26931. }
  26932. this._geometries.push(geometry);
  26933. //notify the collision coordinator
  26934. if (this.collisionCoordinator) {
  26935. this.collisionCoordinator.onGeometryAdded(geometry);
  26936. }
  26937. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26938. return true;
  26939. };
  26940. /**
  26941. * Removes an existing geometry
  26942. * @param geometry defines the geometry to be removed from the scene
  26943. * @return a boolean defining if the geometry was removed or not
  26944. */
  26945. Scene.prototype.removeGeometry = function (geometry) {
  26946. var index = this._geometries.indexOf(geometry);
  26947. if (index > -1) {
  26948. this._geometries.splice(index, 1);
  26949. //notify the collision coordinator
  26950. if (this.collisionCoordinator) {
  26951. this.collisionCoordinator.onGeometryDeleted(geometry);
  26952. }
  26953. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26954. return true;
  26955. }
  26956. return false;
  26957. };
  26958. /**
  26959. * Gets the list of geometries attached to the scene
  26960. * @returns an array of Geometry
  26961. */
  26962. Scene.prototype.getGeometries = function () {
  26963. return this._geometries;
  26964. };
  26965. /**
  26966. * Gets the first added mesh found of a given ID
  26967. * @param id defines the id to search for
  26968. * @return the mesh found or null if not found at all
  26969. */
  26970. Scene.prototype.getMeshByID = function (id) {
  26971. for (var index = 0; index < this.meshes.length; index++) {
  26972. if (this.meshes[index].id === id) {
  26973. return this.meshes[index];
  26974. }
  26975. }
  26976. return null;
  26977. };
  26978. /**
  26979. * Gets a list of meshes using their id
  26980. * @param id defines the id to search for
  26981. * @returns a list of meshes
  26982. */
  26983. Scene.prototype.getMeshesByID = function (id) {
  26984. return this.meshes.filter(function (m) {
  26985. return m.id === id;
  26986. });
  26987. };
  26988. /**
  26989. * Gets the first added transform node found of a given ID
  26990. * @param id defines the id to search for
  26991. * @return the found transform node or null if not found at all.
  26992. */
  26993. Scene.prototype.getTransformNodeByID = function (id) {
  26994. for (var index = 0; index < this.transformNodes.length; index++) {
  26995. if (this.transformNodes[index].id === id) {
  26996. return this.transformNodes[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets a list of transform nodes using their id
  27003. * @param id defines the id to search for
  27004. * @returns a list of transform nodes
  27005. */
  27006. Scene.prototype.getTransformNodesByID = function (id) {
  27007. return this.transformNodes.filter(function (m) {
  27008. return m.id === id;
  27009. });
  27010. };
  27011. /**
  27012. * Gets a mesh with its auto-generated unique id
  27013. * @param uniqueId defines the unique id to search for
  27014. * @return the found mesh or null if not found at all.
  27015. */
  27016. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27017. for (var index = 0; index < this.meshes.length; index++) {
  27018. if (this.meshes[index].uniqueId === uniqueId) {
  27019. return this.meshes[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a the last added mesh using a given id
  27026. * @param id defines the id to search for
  27027. * @return the found mesh or null if not found at all.
  27028. */
  27029. Scene.prototype.getLastMeshByID = function (id) {
  27030. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27031. if (this.meshes[index].id === id) {
  27032. return this.meshes[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27039. * @param id defines the id to search for
  27040. * @return the found node or null if not found at all
  27041. */
  27042. Scene.prototype.getLastEntryByID = function (id) {
  27043. var index;
  27044. for (index = this.meshes.length - 1; index >= 0; index--) {
  27045. if (this.meshes[index].id === id) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27050. if (this.transformNodes[index].id === id) {
  27051. return this.transformNodes[index];
  27052. }
  27053. }
  27054. for (index = this.cameras.length - 1; index >= 0; index--) {
  27055. if (this.cameras[index].id === id) {
  27056. return this.cameras[index];
  27057. }
  27058. }
  27059. for (index = this.lights.length - 1; index >= 0; index--) {
  27060. if (this.lights[index].id === id) {
  27061. return this.lights[index];
  27062. }
  27063. }
  27064. return null;
  27065. };
  27066. /**
  27067. * Gets a node (Mesh, Camera, Light) using a given id
  27068. * @param id defines the id to search for
  27069. * @return the found node or null if not found at all
  27070. */
  27071. Scene.prototype.getNodeByID = function (id) {
  27072. var mesh = this.getMeshByID(id);
  27073. if (mesh) {
  27074. return mesh;
  27075. }
  27076. var light = this.getLightByID(id);
  27077. if (light) {
  27078. return light;
  27079. }
  27080. var camera = this.getCameraByID(id);
  27081. if (camera) {
  27082. return camera;
  27083. }
  27084. var bone = this.getBoneByID(id);
  27085. return bone;
  27086. };
  27087. /**
  27088. * Gets a node (Mesh, Camera, Light) using a given name
  27089. * @param name defines the name to search for
  27090. * @return the found node or null if not found at all.
  27091. */
  27092. Scene.prototype.getNodeByName = function (name) {
  27093. var mesh = this.getMeshByName(name);
  27094. if (mesh) {
  27095. return mesh;
  27096. }
  27097. var light = this.getLightByName(name);
  27098. if (light) {
  27099. return light;
  27100. }
  27101. var camera = this.getCameraByName(name);
  27102. if (camera) {
  27103. return camera;
  27104. }
  27105. var bone = this.getBoneByName(name);
  27106. return bone;
  27107. };
  27108. /**
  27109. * Gets a mesh using a given name
  27110. * @param name defines the name to search for
  27111. * @return the found mesh or null if not found at all.
  27112. */
  27113. Scene.prototype.getMeshByName = function (name) {
  27114. for (var index = 0; index < this.meshes.length; index++) {
  27115. if (this.meshes[index].name === name) {
  27116. return this.meshes[index];
  27117. }
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * Gets a transform node using a given name
  27123. * @param name defines the name to search for
  27124. * @return the found transform node or null if not found at all.
  27125. */
  27126. Scene.prototype.getTransformNodeByName = function (name) {
  27127. for (var index = 0; index < this.transformNodes.length; index++) {
  27128. if (this.transformNodes[index].name === name) {
  27129. return this.transformNodes[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a sound using a given name
  27136. * @param name defines the name to search for
  27137. * @return the found sound or null if not found at all.
  27138. */
  27139. Scene.prototype.getSoundByName = function (name) {
  27140. var index;
  27141. if (BABYLON.AudioEngine) {
  27142. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27143. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27144. return this.mainSoundTrack.soundCollection[index];
  27145. }
  27146. }
  27147. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27148. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27149. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27150. return this.soundTracks[sdIndex].soundCollection[index];
  27151. }
  27152. }
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. /**
  27158. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27159. * @param id defines the id to search for
  27160. * @return the found skeleton or null if not found at all.
  27161. */
  27162. Scene.prototype.getLastSkeletonByID = function (id) {
  27163. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27164. if (this.skeletons[index].id === id) {
  27165. return this.skeletons[index];
  27166. }
  27167. }
  27168. return null;
  27169. };
  27170. /**
  27171. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27172. * @param id defines the id to search for
  27173. * @return the found skeleton or null if not found at all.
  27174. */
  27175. Scene.prototype.getSkeletonById = function (id) {
  27176. for (var index = 0; index < this.skeletons.length; index++) {
  27177. if (this.skeletons[index].id === id) {
  27178. return this.skeletons[index];
  27179. }
  27180. }
  27181. return null;
  27182. };
  27183. /**
  27184. * Gets a skeleton using a given name
  27185. * @param name defines the name to search for
  27186. * @return the found skeleton or null if not found at all.
  27187. */
  27188. Scene.prototype.getSkeletonByName = function (name) {
  27189. for (var index = 0; index < this.skeletons.length; index++) {
  27190. if (this.skeletons[index].name === name) {
  27191. return this.skeletons[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27198. * @param id defines the id to search for
  27199. * @return the found morph target manager or null if not found at all.
  27200. */
  27201. Scene.prototype.getMorphTargetManagerById = function (id) {
  27202. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27203. if (this.morphTargetManagers[index].uniqueId === id) {
  27204. return this.morphTargetManagers[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Gets a boolean indicating if the given mesh is active
  27211. * @param mesh defines the mesh to look for
  27212. * @returns true if the mesh is in the active list
  27213. */
  27214. Scene.prototype.isActiveMesh = function (mesh) {
  27215. return (this._activeMeshes.indexOf(mesh) !== -1);
  27216. };
  27217. /**
  27218. * Return a the first highlight layer of the scene with a given name.
  27219. * @param name The name of the highlight layer to look for.
  27220. * @return The highlight layer if found otherwise null.
  27221. */
  27222. Scene.prototype.getHighlightLayerByName = function (name) {
  27223. for (var index = 0; index < this.effectLayers.length; index++) {
  27224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27225. return this.effectLayers[index];
  27226. }
  27227. }
  27228. return null;
  27229. };
  27230. /**
  27231. * Return a the first highlight layer of the scene with a given name.
  27232. * @param name The name of the highlight layer to look for.
  27233. * @return The highlight layer if found otherwise null.
  27234. */
  27235. Scene.prototype.getGlowLayerByName = function (name) {
  27236. for (var index = 0; index < this.effectLayers.length; index++) {
  27237. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27238. return this.effectLayers[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. Object.defineProperty(Scene.prototype, "uid", {
  27244. /**
  27245. * Return a unique id as a string which can serve as an identifier for the scene
  27246. */
  27247. get: function () {
  27248. if (!this._uid) {
  27249. this._uid = BABYLON.Tools.RandomId();
  27250. }
  27251. return this._uid;
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. /**
  27257. * Add an externaly attached data from its key.
  27258. * This method call will fail and return false, if such key already exists.
  27259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27260. * @param key the unique key that identifies the data
  27261. * @param data the data object to associate to the key for this Engine instance
  27262. * @return true if no such key were already present and the data was added successfully, false otherwise
  27263. */
  27264. Scene.prototype.addExternalData = function (key, data) {
  27265. if (!this._externalData) {
  27266. this._externalData = new BABYLON.StringDictionary();
  27267. }
  27268. return this._externalData.add(key, data);
  27269. };
  27270. /**
  27271. * Get an externaly attached data from its key
  27272. * @param key the unique key that identifies the data
  27273. * @return the associated data, if present (can be null), or undefined if not present
  27274. */
  27275. Scene.prototype.getExternalData = function (key) {
  27276. if (!this._externalData) {
  27277. return null;
  27278. }
  27279. return this._externalData.get(key);
  27280. };
  27281. /**
  27282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27283. * @param key the unique key that identifies the data
  27284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27285. * @return the associated data, can be null if the factory returned null.
  27286. */
  27287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27288. if (!this._externalData) {
  27289. this._externalData = new BABYLON.StringDictionary();
  27290. }
  27291. return this._externalData.getOrAddWithFactory(key, factory);
  27292. };
  27293. /**
  27294. * Remove an externaly attached data from the Engine instance
  27295. * @param key the unique key that identifies the data
  27296. * @return true if the data was successfully removed, false if it doesn't exist
  27297. */
  27298. Scene.prototype.removeExternalData = function (key) {
  27299. return this._externalData.remove(key);
  27300. };
  27301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27303. if (mesh.showSubMeshesBoundingBox) {
  27304. var boundingInfo = subMesh.getBoundingInfo();
  27305. if (boundingInfo !== null && boundingInfo !== undefined) {
  27306. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27307. }
  27308. }
  27309. var material = subMesh.getMaterial();
  27310. if (material !== null && material !== undefined) {
  27311. // Render targets
  27312. if (material.getRenderTargetTextures !== undefined) {
  27313. if (this._processedMaterials.indexOf(material) === -1) {
  27314. this._processedMaterials.push(material);
  27315. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27316. }
  27317. }
  27318. // Dispatch
  27319. this._activeIndices.addCount(subMesh.indexCount, false);
  27320. this._renderingManager.dispatch(subMesh, mesh, material);
  27321. }
  27322. }
  27323. };
  27324. /**
  27325. * Clear the processed materials smart array preventing retention point in material dispose.
  27326. */
  27327. Scene.prototype.freeProcessedMaterials = function () {
  27328. this._processedMaterials.dispose();
  27329. };
  27330. /**
  27331. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27332. */
  27333. Scene.prototype.freeActiveMeshes = function () {
  27334. this._activeMeshes.dispose();
  27335. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27336. this.activeCamera._activeMeshes.dispose();
  27337. }
  27338. if (this.activeCameras) {
  27339. for (var i = 0; i < this.activeCameras.length; i++) {
  27340. var activeCamera = this.activeCameras[i];
  27341. if (activeCamera && activeCamera._activeMeshes) {
  27342. activeCamera._activeMeshes.dispose();
  27343. }
  27344. }
  27345. }
  27346. };
  27347. /**
  27348. * Clear the info related to rendering groups preventing retention points during dispose.
  27349. */
  27350. Scene.prototype.freeRenderingGroups = function () {
  27351. if (this._renderingManager) {
  27352. this._renderingManager.freeRenderingGroups();
  27353. }
  27354. if (this.textures) {
  27355. for (var i = 0; i < this.textures.length; i++) {
  27356. var texture = this.textures[i];
  27357. if (texture && texture.renderList) {
  27358. texture.freeRenderingGroups();
  27359. }
  27360. }
  27361. }
  27362. };
  27363. /** @hidden */
  27364. Scene.prototype._isInIntermediateRendering = function () {
  27365. return this._intermediateRendering;
  27366. };
  27367. /**
  27368. * Defines the current active mesh candidate provider
  27369. * @param provider defines the provider to use
  27370. */
  27371. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27372. this._activeMeshCandidateProvider = provider;
  27373. };
  27374. /**
  27375. * Gets the current active mesh candidate provider
  27376. * @returns the current active mesh candidate provider
  27377. */
  27378. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27379. return this._activeMeshCandidateProvider;
  27380. };
  27381. /**
  27382. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27383. * @returns the current scene
  27384. */
  27385. Scene.prototype.freezeActiveMeshes = function () {
  27386. if (!this.activeCamera) {
  27387. return this;
  27388. }
  27389. if (!this._frustumPlanes) {
  27390. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27391. }
  27392. this._evaluateActiveMeshes();
  27393. this._activeMeshesFrozen = true;
  27394. return this;
  27395. };
  27396. /**
  27397. * Use this function to restart evaluating active meshes on every frame
  27398. * @returns the current scene
  27399. */
  27400. Scene.prototype.unfreezeActiveMeshes = function () {
  27401. this._activeMeshesFrozen = false;
  27402. return this;
  27403. };
  27404. Scene.prototype._evaluateActiveMeshes = function () {
  27405. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27406. return;
  27407. }
  27408. if (!this.activeCamera) {
  27409. return;
  27410. }
  27411. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27412. this.activeCamera._activeMeshes.reset();
  27413. this._activeMeshes.reset();
  27414. this._renderingManager.reset();
  27415. this._processedMaterials.reset();
  27416. this._activeParticleSystems.reset();
  27417. this._activeSkeletons.reset();
  27418. this._softwareSkinnedMeshes.reset();
  27419. if (this._boundingBoxRenderer) {
  27420. this._boundingBoxRenderer.reset();
  27421. }
  27422. // Meshes
  27423. var meshes;
  27424. var len;
  27425. var checkIsEnabled = true;
  27426. // Determine mesh candidates
  27427. if (this._activeMeshCandidateProvider !== undefined) {
  27428. // Use _activeMeshCandidateProvider
  27429. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27430. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27431. if (meshes !== undefined) {
  27432. len = meshes.length;
  27433. }
  27434. else {
  27435. len = 0;
  27436. }
  27437. }
  27438. else if (this._selectionOctree !== undefined) {
  27439. // Octree
  27440. var selection = this._selectionOctree.select(this._frustumPlanes);
  27441. meshes = selection.data;
  27442. len = selection.length;
  27443. }
  27444. else {
  27445. // Full scene traversal
  27446. len = this.meshes.length;
  27447. meshes = this.meshes;
  27448. }
  27449. // Check each mesh
  27450. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27451. mesh = meshes[meshIndex];
  27452. if (mesh.isBlocked) {
  27453. continue;
  27454. }
  27455. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27456. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27457. continue;
  27458. }
  27459. mesh.computeWorldMatrix();
  27460. // Intersections
  27461. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27462. this._meshesForIntersections.pushNoDuplicate(mesh);
  27463. }
  27464. // Switch to current LOD
  27465. meshLOD = mesh.getLOD(this.activeCamera);
  27466. if (meshLOD === undefined || meshLOD === null) {
  27467. continue;
  27468. }
  27469. mesh._preActivate();
  27470. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27471. this._activeMeshes.push(mesh);
  27472. this.activeCamera._activeMeshes.push(mesh);
  27473. mesh._activate(this._renderId);
  27474. if (meshLOD !== mesh) {
  27475. meshLOD._activate(this._renderId);
  27476. }
  27477. this._activeMesh(mesh, meshLOD);
  27478. }
  27479. }
  27480. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27481. // Particle systems
  27482. if (this.particlesEnabled) {
  27483. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27484. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27485. var particleSystem = this.particleSystems[particleIndex];
  27486. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27487. continue;
  27488. }
  27489. var emitter = particleSystem.emitter;
  27490. if (!emitter.position || emitter.isEnabled()) {
  27491. this._activeParticleSystems.push(particleSystem);
  27492. particleSystem.animate();
  27493. this._renderingManager.dispatchParticles(particleSystem);
  27494. }
  27495. }
  27496. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27497. }
  27498. };
  27499. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27500. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27501. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27502. mesh.skeleton.prepare();
  27503. }
  27504. if (!mesh.computeBonesUsingShaders) {
  27505. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27506. }
  27507. }
  27508. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27509. var boundingInfo = sourceMesh.getBoundingInfo();
  27510. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27511. }
  27512. if (mesh !== undefined && mesh !== null
  27513. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27514. // Submeshes Octrees
  27515. var len;
  27516. var subMeshes;
  27517. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27518. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27519. len = intersections.length;
  27520. subMeshes = intersections.data;
  27521. }
  27522. else {
  27523. subMeshes = mesh.subMeshes;
  27524. len = subMeshes.length;
  27525. }
  27526. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27527. subMesh = subMeshes[subIndex];
  27528. this._evaluateSubMesh(subMesh, mesh);
  27529. }
  27530. }
  27531. };
  27532. /**
  27533. * Update the transform matrix to update from the current active camera
  27534. * @param force defines a boolean used to force the update even if cache is up to date
  27535. */
  27536. Scene.prototype.updateTransformMatrix = function (force) {
  27537. if (!this.activeCamera) {
  27538. return;
  27539. }
  27540. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27541. };
  27542. /**
  27543. * 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)
  27544. * @param alternateCamera defines the camera to use
  27545. */
  27546. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27547. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27548. };
  27549. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27550. if (camera && camera._skipRendering) {
  27551. return;
  27552. }
  27553. var engine = this._engine;
  27554. this.activeCamera = camera;
  27555. if (!this.activeCamera)
  27556. throw new Error("Active camera not set");
  27557. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27558. // Viewport
  27559. engine.setViewport(this.activeCamera.viewport);
  27560. // Camera
  27561. this.resetCachedMaterial();
  27562. this._renderId++;
  27563. this.updateTransformMatrix();
  27564. if (camera._alternateCamera) {
  27565. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27566. this._alternateRendering = true;
  27567. }
  27568. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27569. // Meshes
  27570. this._evaluateActiveMeshes();
  27571. // Software skinning
  27572. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27573. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27574. mesh.applySkeleton(mesh.skeleton);
  27575. }
  27576. // Render targets
  27577. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27578. var needsRestoreFrameBuffer = false;
  27579. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27580. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27581. }
  27582. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27583. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27584. }
  27585. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27586. this._intermediateRendering = true;
  27587. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27588. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27589. var renderTarget = this._renderTargets.data[renderIndex];
  27590. if (renderTarget._shouldRender()) {
  27591. this._renderId++;
  27592. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27593. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27594. }
  27595. }
  27596. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27597. this._intermediateRendering = false;
  27598. this._renderId++;
  27599. needsRestoreFrameBuffer = true; // Restore back buffer
  27600. }
  27601. // Render EffecttLayer Texture
  27602. var stencilState = this._engine.getStencilBuffer();
  27603. var renderEffects = false;
  27604. var needStencil = false;
  27605. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27606. this._intermediateRendering = true;
  27607. for (var i = 0; i < this.effectLayers.length; i++) {
  27608. var effectLayer = this.effectLayers[i];
  27609. if (effectLayer.shouldRender() &&
  27610. (!effectLayer.camera ||
  27611. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27612. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27613. renderEffects = true;
  27614. needStencil = needStencil || effectLayer.needStencil();
  27615. var renderTarget = effectLayer._mainTexture;
  27616. if (renderTarget._shouldRender()) {
  27617. this._renderId++;
  27618. renderTarget.render(false, false);
  27619. needsRestoreFrameBuffer = true;
  27620. }
  27621. }
  27622. }
  27623. this._intermediateRendering = false;
  27624. this._renderId++;
  27625. }
  27626. if (needsRestoreFrameBuffer) {
  27627. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27628. }
  27629. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27630. // Prepare Frame
  27631. if (this.postProcessManager) {
  27632. this.postProcessManager._prepareFrame();
  27633. }
  27634. // Backgrounds
  27635. var layerIndex;
  27636. var layer;
  27637. if (this.layers.length) {
  27638. engine.setDepthBuffer(false);
  27639. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27640. layer = this.layers[layerIndex];
  27641. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27642. layer.render();
  27643. }
  27644. }
  27645. engine.setDepthBuffer(true);
  27646. }
  27647. // Activate effect Layer stencil
  27648. if (needStencil) {
  27649. this._engine.setStencilBuffer(true);
  27650. }
  27651. // Render
  27652. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27653. this._renderingManager.render(null, null, true, true);
  27654. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27655. // Restore effect Layer stencil
  27656. if (needStencil) {
  27657. this._engine.setStencilBuffer(stencilState);
  27658. }
  27659. // Bounding boxes
  27660. if (this._boundingBoxRenderer) {
  27661. this._boundingBoxRenderer.render();
  27662. }
  27663. // Lens flares
  27664. if (this.lensFlaresEnabled) {
  27665. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27666. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27667. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27668. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27669. lensFlareSystem.render();
  27670. }
  27671. }
  27672. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27673. }
  27674. // Effect Layer
  27675. if (renderEffects) {
  27676. engine.setDepthBuffer(false);
  27677. for (var i = 0; i < this.effectLayers.length; i++) {
  27678. if (this.effectLayers[i].shouldRender()) {
  27679. this.effectLayers[i].render();
  27680. }
  27681. }
  27682. engine.setDepthBuffer(true);
  27683. }
  27684. // Foregrounds
  27685. if (this.layers.length) {
  27686. engine.setDepthBuffer(false);
  27687. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27688. layer = this.layers[layerIndex];
  27689. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27690. layer.render();
  27691. }
  27692. }
  27693. engine.setDepthBuffer(true);
  27694. }
  27695. // Finalize frame
  27696. if (this.postProcessManager) {
  27697. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27698. }
  27699. // Reset some special arrays
  27700. this._renderTargets.reset();
  27701. this._alternateRendering = false;
  27702. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27703. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27704. };
  27705. Scene.prototype._processSubCameras = function (camera) {
  27706. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27707. this._renderForCamera(camera);
  27708. return;
  27709. }
  27710. // rig cameras
  27711. for (var index = 0; index < camera._rigCameras.length; index++) {
  27712. this._renderForCamera(camera._rigCameras[index], camera);
  27713. }
  27714. this.activeCamera = camera;
  27715. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27716. };
  27717. Scene.prototype._checkIntersections = function () {
  27718. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27719. var sourceMesh = this._meshesForIntersections.data[index];
  27720. if (!sourceMesh.actionManager) {
  27721. continue;
  27722. }
  27723. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27724. var action = sourceMesh.actionManager.actions[actionIndex];
  27725. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27726. var parameters = action.getTriggerParameter();
  27727. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27728. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27729. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27730. if (areIntersecting && currentIntersectionInProgress === -1) {
  27731. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27732. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27733. sourceMesh._intersectionsInProgress.push(otherMesh);
  27734. }
  27735. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27736. sourceMesh._intersectionsInProgress.push(otherMesh);
  27737. }
  27738. }
  27739. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27740. //They intersected, and now they don't.
  27741. //is this trigger an exit trigger? execute an event.
  27742. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27743. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27744. }
  27745. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27746. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27747. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27748. return otherMesh === parameterMesh;
  27749. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27750. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27751. }
  27752. }
  27753. }
  27754. }
  27755. }
  27756. };
  27757. /**
  27758. * Render the scene
  27759. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27760. */
  27761. Scene.prototype.render = function (updateCameras) {
  27762. if (updateCameras === void 0) { updateCameras = true; }
  27763. if (this.isDisposed) {
  27764. return;
  27765. }
  27766. this._activeParticles.fetchNewFrame();
  27767. this._totalVertices.fetchNewFrame();
  27768. this._activeIndices.fetchNewFrame();
  27769. this._activeBones.fetchNewFrame();
  27770. this._meshesForIntersections.reset();
  27771. this.resetCachedMaterial();
  27772. this.onBeforeAnimationsObservable.notifyObservers(this);
  27773. // Actions
  27774. if (this.actionManager) {
  27775. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27776. }
  27777. //Simplification Queue
  27778. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27779. this.simplificationQueue.executeNext();
  27780. }
  27781. if (this._engine.isDeterministicLockStep()) {
  27782. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27783. var defaultFPS = (60.0 / 1000.0);
  27784. var defaultFrameTime = 1000 / 60; // frame time in MS
  27785. if (this._physicsEngine) {
  27786. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27787. }
  27788. var stepsTaken = 0;
  27789. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27790. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27791. internalSteps = Math.min(internalSteps, maxSubSteps);
  27792. do {
  27793. this.onBeforeStepObservable.notifyObservers(this);
  27794. // Animations
  27795. this._animationRatio = defaultFrameTime * defaultFPS;
  27796. this._animate();
  27797. this.onAfterAnimationsObservable.notifyObservers(this);
  27798. // Physics
  27799. if (this._physicsEngine) {
  27800. this.onBeforePhysicsObservable.notifyObservers(this);
  27801. this._physicsEngine._step(defaultFrameTime / 1000);
  27802. this.onAfterPhysicsObservable.notifyObservers(this);
  27803. }
  27804. this.onAfterStepObservable.notifyObservers(this);
  27805. this._currentStepId++;
  27806. stepsTaken++;
  27807. deltaTime -= defaultFrameTime;
  27808. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27809. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27810. }
  27811. else {
  27812. // Animations
  27813. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27814. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27815. this._animate();
  27816. this.onAfterAnimationsObservable.notifyObservers(this);
  27817. // Physics
  27818. if (this._physicsEngine) {
  27819. this.onBeforePhysicsObservable.notifyObservers(this);
  27820. this._physicsEngine._step(deltaTime / 1000.0);
  27821. this.onAfterPhysicsObservable.notifyObservers(this);
  27822. }
  27823. }
  27824. // update gamepad manager
  27825. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27826. this._gamepadManager._checkGamepadsStatus();
  27827. }
  27828. // Update Cameras
  27829. if (updateCameras) {
  27830. if (this.activeCameras.length > 0) {
  27831. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27832. var camera = this.activeCameras[cameraIndex];
  27833. camera.update();
  27834. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27835. // rig cameras
  27836. for (var index = 0; index < camera._rigCameras.length; index++) {
  27837. camera._rigCameras[index].update();
  27838. }
  27839. }
  27840. }
  27841. }
  27842. else if (this.activeCamera) {
  27843. this.activeCamera.update();
  27844. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27845. // rig cameras
  27846. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27847. this.activeCamera._rigCameras[index].update();
  27848. }
  27849. }
  27850. }
  27851. }
  27852. // Before render
  27853. this.onBeforeRenderObservable.notifyObservers(this);
  27854. // Customs render targets
  27855. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27856. var engine = this.getEngine();
  27857. var currentActiveCamera = this.activeCamera;
  27858. if (this.renderTargetsEnabled) {
  27859. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27860. this._intermediateRendering = true;
  27861. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27862. var renderTarget = this.customRenderTargets[customIndex];
  27863. if (renderTarget._shouldRender()) {
  27864. this._renderId++;
  27865. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27866. if (!this.activeCamera)
  27867. throw new Error("Active camera not set");
  27868. // Viewport
  27869. engine.setViewport(this.activeCamera.viewport);
  27870. // Camera
  27871. this.updateTransformMatrix();
  27872. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27873. }
  27874. }
  27875. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27876. this._intermediateRendering = false;
  27877. this._renderId++;
  27878. }
  27879. // Restore back buffer
  27880. if (this.customRenderTargets.length > 0) {
  27881. engine.restoreDefaultFramebuffer();
  27882. }
  27883. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27884. this.activeCamera = currentActiveCamera;
  27885. // Procedural textures
  27886. if (this.proceduralTexturesEnabled) {
  27887. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27888. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27889. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27890. if (proceduralTexture._shouldRender()) {
  27891. proceduralTexture.render();
  27892. }
  27893. }
  27894. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27895. }
  27896. // Clear
  27897. if (this.autoClearDepthAndStencil || this.autoClear) {
  27898. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27899. }
  27900. // Shadows
  27901. if (this.shadowsEnabled) {
  27902. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27903. var light = this.lights[lightIndex];
  27904. var shadowGenerator = light.getShadowGenerator();
  27905. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27906. var shadowMap = (shadowGenerator.getShadowMap());
  27907. if (this.textures.indexOf(shadowMap) !== -1) {
  27908. this._renderTargets.push(shadowMap);
  27909. }
  27910. }
  27911. }
  27912. }
  27913. // Depth renderer
  27914. for (var key in this._depthRenderer) {
  27915. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27916. }
  27917. // Geometry renderer
  27918. if (this._geometryBufferRenderer) {
  27919. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27920. }
  27921. // RenderPipeline
  27922. if (this._postProcessRenderPipelineManager) {
  27923. this._postProcessRenderPipelineManager.update();
  27924. }
  27925. // Multi-cameras?
  27926. if (this.activeCameras.length > 0) {
  27927. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27928. if (cameraIndex > 0) {
  27929. this._engine.clear(null, false, true, true);
  27930. }
  27931. this._processSubCameras(this.activeCameras[cameraIndex]);
  27932. }
  27933. }
  27934. else {
  27935. if (!this.activeCamera) {
  27936. throw new Error("No camera defined");
  27937. }
  27938. this._processSubCameras(this.activeCamera);
  27939. }
  27940. // Intersection checks
  27941. this._checkIntersections();
  27942. // Update the audio listener attached to the camera
  27943. if (BABYLON.AudioEngine) {
  27944. this._updateAudioParameters();
  27945. }
  27946. // After render
  27947. if (this.afterRender) {
  27948. this.afterRender();
  27949. }
  27950. this.onAfterRenderObservable.notifyObservers(this);
  27951. // Cleaning
  27952. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27953. var data = this._toBeDisposed.data[index];
  27954. if (data) {
  27955. data.dispose();
  27956. }
  27957. this._toBeDisposed[index] = null;
  27958. }
  27959. this._toBeDisposed.reset();
  27960. if (this.dumpNextRenderTargets) {
  27961. this.dumpNextRenderTargets = false;
  27962. }
  27963. this._activeBones.addCount(0, true);
  27964. this._activeIndices.addCount(0, true);
  27965. this._activeParticles.addCount(0, true);
  27966. };
  27967. Scene.prototype._updateAudioParameters = function () {
  27968. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27969. return;
  27970. }
  27971. var listeningCamera;
  27972. var audioEngine = BABYLON.Engine.audioEngine;
  27973. if (this.activeCameras.length > 0) {
  27974. listeningCamera = this.activeCameras[0];
  27975. }
  27976. else {
  27977. listeningCamera = this.activeCamera;
  27978. }
  27979. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27980. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27981. // for VR cameras
  27982. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27983. listeningCamera = listeningCamera.rigCameras[0];
  27984. }
  27985. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27986. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27987. cameraDirection.normalize();
  27988. // To avoid some errors on GearVR
  27989. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27990. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27991. }
  27992. var i;
  27993. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27994. var sound = this.mainSoundTrack.soundCollection[i];
  27995. if (sound.useCustomAttenuation) {
  27996. sound.updateDistanceFromListener();
  27997. }
  27998. }
  27999. for (i = 0; i < this.soundTracks.length; i++) {
  28000. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28001. sound = this.soundTracks[i].soundCollection[j];
  28002. if (sound.useCustomAttenuation) {
  28003. sound.updateDistanceFromListener();
  28004. }
  28005. }
  28006. }
  28007. }
  28008. };
  28009. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28010. // Audio
  28011. /**
  28012. * Gets or sets if audio support is enabled
  28013. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28014. */
  28015. get: function () {
  28016. return this._audioEnabled;
  28017. },
  28018. set: function (value) {
  28019. this._audioEnabled = value;
  28020. if (BABYLON.AudioEngine) {
  28021. if (this._audioEnabled) {
  28022. this._enableAudio();
  28023. }
  28024. else {
  28025. this._disableAudio();
  28026. }
  28027. }
  28028. },
  28029. enumerable: true,
  28030. configurable: true
  28031. });
  28032. Scene.prototype._disableAudio = function () {
  28033. var i;
  28034. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28035. this.mainSoundTrack.soundCollection[i].pause();
  28036. }
  28037. for (i = 0; i < this.soundTracks.length; i++) {
  28038. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28039. this.soundTracks[i].soundCollection[j].pause();
  28040. }
  28041. }
  28042. };
  28043. Scene.prototype._enableAudio = function () {
  28044. var i;
  28045. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28046. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28047. this.mainSoundTrack.soundCollection[i].play();
  28048. }
  28049. }
  28050. for (i = 0; i < this.soundTracks.length; i++) {
  28051. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28052. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28053. this.soundTracks[i].soundCollection[j].play();
  28054. }
  28055. }
  28056. }
  28057. };
  28058. Object.defineProperty(Scene.prototype, "headphone", {
  28059. /**
  28060. * Gets or sets if audio will be output to headphones
  28061. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28062. */
  28063. get: function () {
  28064. return this._headphone;
  28065. },
  28066. set: function (value) {
  28067. this._headphone = value;
  28068. if (BABYLON.AudioEngine) {
  28069. if (this._headphone) {
  28070. this._switchAudioModeForHeadphones();
  28071. }
  28072. else {
  28073. this._switchAudioModeForNormalSpeakers();
  28074. }
  28075. }
  28076. },
  28077. enumerable: true,
  28078. configurable: true
  28079. });
  28080. Scene.prototype._switchAudioModeForHeadphones = function () {
  28081. this.mainSoundTrack.switchPanningModelToHRTF();
  28082. for (var i = 0; i < this.soundTracks.length; i++) {
  28083. this.soundTracks[i].switchPanningModelToHRTF();
  28084. }
  28085. };
  28086. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28087. this.mainSoundTrack.switchPanningModelToEqualPower();
  28088. for (var i = 0; i < this.soundTracks.length; i++) {
  28089. this.soundTracks[i].switchPanningModelToEqualPower();
  28090. }
  28091. };
  28092. /**
  28093. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28094. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28095. * @returns the created depth renderer
  28096. */
  28097. Scene.prototype.enableDepthRenderer = function (camera) {
  28098. camera = camera || this.activeCamera;
  28099. if (!camera) {
  28100. throw "No camera available to enable depth renderer";
  28101. }
  28102. if (!this._depthRenderer[camera.id]) {
  28103. var textureType = 0;
  28104. if (this._engine.getCaps().textureHalfFloatRender) {
  28105. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28106. }
  28107. else if (this._engine.getCaps().textureFloatRender) {
  28108. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28109. }
  28110. else {
  28111. throw "Depth renderer does not support int texture type";
  28112. }
  28113. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28114. }
  28115. return this._depthRenderer[camera.id];
  28116. };
  28117. /**
  28118. * Disables a depth renderer for a given camera
  28119. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28120. */
  28121. Scene.prototype.disableDepthRenderer = function (camera) {
  28122. camera = camera || this.activeCamera;
  28123. if (!camera || !this._depthRenderer[camera.id]) {
  28124. return;
  28125. }
  28126. this._depthRenderer[camera.id].dispose();
  28127. delete this._depthRenderer[camera.id];
  28128. };
  28129. /**
  28130. * Enables a GeometryBufferRender and associates it with the scene
  28131. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28132. * @returns the GeometryBufferRenderer
  28133. */
  28134. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28135. if (ratio === void 0) { ratio = 1; }
  28136. if (this._geometryBufferRenderer) {
  28137. return this._geometryBufferRenderer;
  28138. }
  28139. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28140. if (!this._geometryBufferRenderer.isSupported) {
  28141. this._geometryBufferRenderer = null;
  28142. }
  28143. return this._geometryBufferRenderer;
  28144. };
  28145. /**
  28146. * Disables the GeometryBufferRender associated with the scene
  28147. */
  28148. Scene.prototype.disableGeometryBufferRenderer = function () {
  28149. if (!this._geometryBufferRenderer) {
  28150. return;
  28151. }
  28152. this._geometryBufferRenderer.dispose();
  28153. this._geometryBufferRenderer = null;
  28154. };
  28155. /**
  28156. * Freeze all materials
  28157. * A frozen material will not be updatable but should be faster to render
  28158. */
  28159. Scene.prototype.freezeMaterials = function () {
  28160. for (var i = 0; i < this.materials.length; i++) {
  28161. this.materials[i].freeze();
  28162. }
  28163. };
  28164. /**
  28165. * Unfreeze all materials
  28166. * A frozen material will not be updatable but should be faster to render
  28167. */
  28168. Scene.prototype.unfreezeMaterials = function () {
  28169. for (var i = 0; i < this.materials.length; i++) {
  28170. this.materials[i].unfreeze();
  28171. }
  28172. };
  28173. /**
  28174. * Releases all held ressources
  28175. */
  28176. Scene.prototype.dispose = function () {
  28177. this.beforeRender = null;
  28178. this.afterRender = null;
  28179. this.skeletons = [];
  28180. this.morphTargetManagers = [];
  28181. this.importedMeshesFiles = new Array();
  28182. this.stopAllAnimations();
  28183. this.resetCachedMaterial();
  28184. for (var key in this._depthRenderer) {
  28185. this._depthRenderer[key].dispose();
  28186. }
  28187. if (this._gamepadManager) {
  28188. this._gamepadManager.dispose();
  28189. this._gamepadManager = null;
  28190. }
  28191. // Smart arrays
  28192. if (this.activeCamera) {
  28193. this.activeCamera._activeMeshes.dispose();
  28194. this.activeCamera = null;
  28195. }
  28196. this._activeMeshes.dispose();
  28197. this._renderingManager.dispose();
  28198. this._processedMaterials.dispose();
  28199. this._activeParticleSystems.dispose();
  28200. this._activeSkeletons.dispose();
  28201. this._softwareSkinnedMeshes.dispose();
  28202. this._renderTargets.dispose();
  28203. this._registeredForLateAnimationBindings.dispose();
  28204. if (this._boundingBoxRenderer) {
  28205. this._boundingBoxRenderer.dispose();
  28206. }
  28207. this._meshesForIntersections.dispose();
  28208. this._toBeDisposed.dispose();
  28209. // Abort active requests
  28210. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28211. var request = _a[_i];
  28212. request.abort();
  28213. }
  28214. // Debug layer
  28215. if (this._debugLayer) {
  28216. this._debugLayer.hide();
  28217. }
  28218. // Events
  28219. this.onDisposeObservable.notifyObservers(this);
  28220. this.onDisposeObservable.clear();
  28221. this.onBeforeRenderObservable.clear();
  28222. this.onAfterRenderObservable.clear();
  28223. this.onBeforeRenderTargetsRenderObservable.clear();
  28224. this.onAfterRenderTargetsRenderObservable.clear();
  28225. this.onAfterStepObservable.clear();
  28226. this.onBeforeStepObservable.clear();
  28227. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28228. this.onAfterActiveMeshesEvaluationObservable.clear();
  28229. this.onBeforeParticlesRenderingObservable.clear();
  28230. this.onAfterParticlesRenderingObservable.clear();
  28231. this.onBeforeSpritesRenderingObservable.clear();
  28232. this.onAfterSpritesRenderingObservable.clear();
  28233. this.onBeforeDrawPhaseObservable.clear();
  28234. this.onAfterDrawPhaseObservable.clear();
  28235. this.onBeforePhysicsObservable.clear();
  28236. this.onAfterPhysicsObservable.clear();
  28237. this.onBeforeAnimationsObservable.clear();
  28238. this.onAfterAnimationsObservable.clear();
  28239. this.onDataLoadedObservable.clear();
  28240. this.detachControl();
  28241. // Release sounds & sounds tracks
  28242. if (BABYLON.AudioEngine) {
  28243. this.disposeSounds();
  28244. }
  28245. // VR Helper
  28246. if (this.VRHelper) {
  28247. this.VRHelper.dispose();
  28248. }
  28249. // Detach cameras
  28250. var canvas = this._engine.getRenderingCanvas();
  28251. if (canvas) {
  28252. var index;
  28253. for (index = 0; index < this.cameras.length; index++) {
  28254. this.cameras[index].detachControl(canvas);
  28255. }
  28256. }
  28257. // Release animation groups
  28258. while (this.animationGroups.length) {
  28259. this.animationGroups[0].dispose();
  28260. }
  28261. // Release lights
  28262. while (this.lights.length) {
  28263. this.lights[0].dispose();
  28264. }
  28265. // Release meshes
  28266. while (this.meshes.length) {
  28267. this.meshes[0].dispose(true);
  28268. }
  28269. while (this.transformNodes.length) {
  28270. this.removeTransformNode(this.transformNodes[0]);
  28271. }
  28272. // Release cameras
  28273. while (this.cameras.length) {
  28274. this.cameras[0].dispose();
  28275. }
  28276. // Release materials
  28277. if (this.defaultMaterial) {
  28278. this.defaultMaterial.dispose();
  28279. }
  28280. while (this.multiMaterials.length) {
  28281. this.multiMaterials[0].dispose();
  28282. }
  28283. while (this.materials.length) {
  28284. this.materials[0].dispose();
  28285. }
  28286. // Release particles
  28287. while (this.particleSystems.length) {
  28288. this.particleSystems[0].dispose();
  28289. }
  28290. // Release sprites
  28291. while (this.spriteManagers.length) {
  28292. this.spriteManagers[0].dispose();
  28293. }
  28294. // Release postProcesses
  28295. while (this.postProcesses.length) {
  28296. this.postProcesses[0].dispose();
  28297. }
  28298. // Release layers
  28299. while (this.layers.length) {
  28300. this.layers[0].dispose();
  28301. }
  28302. while (this.effectLayers.length) {
  28303. this.effectLayers[0].dispose();
  28304. }
  28305. // Release textures
  28306. while (this.textures.length) {
  28307. this.textures[0].dispose();
  28308. }
  28309. // Release UBO
  28310. this._sceneUbo.dispose();
  28311. if (this._alternateSceneUbo) {
  28312. this._alternateSceneUbo.dispose();
  28313. }
  28314. // Post-processes
  28315. this.postProcessManager.dispose();
  28316. if (this._postProcessRenderPipelineManager) {
  28317. this._postProcessRenderPipelineManager.dispose();
  28318. }
  28319. // Physics
  28320. if (this._physicsEngine) {
  28321. this.disablePhysicsEngine();
  28322. }
  28323. // Remove from engine
  28324. index = this._engine.scenes.indexOf(this);
  28325. if (index > -1) {
  28326. this._engine.scenes.splice(index, 1);
  28327. }
  28328. this._engine.wipeCaches(true);
  28329. this._isDisposed = true;
  28330. };
  28331. Object.defineProperty(Scene.prototype, "isDisposed", {
  28332. /**
  28333. * Gets if the scene is already disposed
  28334. */
  28335. get: function () {
  28336. return this._isDisposed;
  28337. },
  28338. enumerable: true,
  28339. configurable: true
  28340. });
  28341. /**
  28342. * Releases sounds & soundtracks
  28343. */
  28344. Scene.prototype.disposeSounds = function () {
  28345. if (!this._mainSoundTrack) {
  28346. return;
  28347. }
  28348. this.mainSoundTrack.dispose();
  28349. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28350. this.soundTracks[scIndex].dispose();
  28351. }
  28352. };
  28353. /**
  28354. * Call this function to reduce memory footprint of the scene.
  28355. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28356. */
  28357. Scene.prototype.clearCachedVertexData = function () {
  28358. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28359. var mesh = this.meshes[meshIndex];
  28360. var geometry = mesh.geometry;
  28361. if (geometry) {
  28362. geometry._indices = [];
  28363. for (var vbName in geometry._vertexBuffers) {
  28364. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28365. continue;
  28366. }
  28367. geometry._vertexBuffers[vbName]._buffer._data = null;
  28368. }
  28369. }
  28370. }
  28371. };
  28372. /**
  28373. * This function will remove the local cached buffer data from texture.
  28374. * It will save memory but will prevent the texture from being rebuilt
  28375. */
  28376. Scene.prototype.cleanCachedTextureBuffer = function () {
  28377. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28378. var baseTexture = _a[_i];
  28379. var buffer = baseTexture._buffer;
  28380. if (buffer) {
  28381. baseTexture._buffer = null;
  28382. }
  28383. }
  28384. };
  28385. // Octrees
  28386. /**
  28387. * Get the world extend vectors with an optional filter
  28388. *
  28389. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28390. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28391. */
  28392. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28393. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28394. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28395. filterPredicate = filterPredicate || (function () { return true; });
  28396. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28397. mesh.computeWorldMatrix(true);
  28398. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28399. return;
  28400. }
  28401. var boundingInfo = mesh.getBoundingInfo();
  28402. var minBox = boundingInfo.boundingBox.minimumWorld;
  28403. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28404. BABYLON.Tools.CheckExtends(minBox, min, max);
  28405. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28406. });
  28407. return {
  28408. min: min,
  28409. max: max
  28410. };
  28411. };
  28412. /**
  28413. * Creates or updates the octree used to boost selection (picking)
  28414. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28415. * @param maxCapacity defines the maximum capacity per leaf
  28416. * @param maxDepth defines the maximum depth of the octree
  28417. * @returns an octree of AbstractMesh
  28418. */
  28419. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28420. if (maxCapacity === void 0) { maxCapacity = 64; }
  28421. if (maxDepth === void 0) { maxDepth = 2; }
  28422. if (!this._selectionOctree) {
  28423. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28424. }
  28425. var worldExtends = this.getWorldExtends();
  28426. // Update octree
  28427. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28428. return this._selectionOctree;
  28429. };
  28430. // Picking
  28431. /**
  28432. * Creates a ray that can be used to pick in the scene
  28433. * @param x defines the x coordinate of the origin (on-screen)
  28434. * @param y defines the y coordinate of the origin (on-screen)
  28435. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28436. * @param camera defines the camera to use for the picking
  28437. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28438. * @returns a Ray
  28439. */
  28440. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28441. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28442. var result = BABYLON.Ray.Zero();
  28443. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28444. return result;
  28445. };
  28446. /**
  28447. * Creates a ray that can be used to pick in the scene
  28448. * @param x defines the x coordinate of the origin (on-screen)
  28449. * @param y defines the y coordinate of the origin (on-screen)
  28450. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28451. * @param result defines the ray where to store the picking ray
  28452. * @param camera defines the camera to use for the picking
  28453. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28454. * @returns the current scene
  28455. */
  28456. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28457. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28458. var engine = this._engine;
  28459. if (!camera) {
  28460. if (!this.activeCamera)
  28461. throw new Error("Active camera not set");
  28462. camera = this.activeCamera;
  28463. }
  28464. var cameraViewport = camera.viewport;
  28465. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28466. // Moving coordinates to local viewport world
  28467. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28468. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28469. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28470. return this;
  28471. };
  28472. /**
  28473. * Creates a ray that can be used to pick in the scene
  28474. * @param x defines the x coordinate of the origin (on-screen)
  28475. * @param y defines the y coordinate of the origin (on-screen)
  28476. * @param camera defines the camera to use for the picking
  28477. * @returns a Ray
  28478. */
  28479. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28480. var result = BABYLON.Ray.Zero();
  28481. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28482. return result;
  28483. };
  28484. /**
  28485. * Creates a ray that can be used to pick in the scene
  28486. * @param x defines the x coordinate of the origin (on-screen)
  28487. * @param y defines the y coordinate of the origin (on-screen)
  28488. * @param result defines the ray where to store the picking ray
  28489. * @param camera defines the camera to use for the picking
  28490. * @returns the current scene
  28491. */
  28492. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28493. if (!BABYLON.PickingInfo) {
  28494. return this;
  28495. }
  28496. var engine = this._engine;
  28497. if (!camera) {
  28498. if (!this.activeCamera)
  28499. throw new Error("Active camera not set");
  28500. camera = this.activeCamera;
  28501. }
  28502. var cameraViewport = camera.viewport;
  28503. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28504. var identity = BABYLON.Matrix.Identity();
  28505. // Moving coordinates to local viewport world
  28506. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28507. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28508. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28509. return this;
  28510. };
  28511. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28512. if (!BABYLON.PickingInfo) {
  28513. return null;
  28514. }
  28515. var pickingInfo = null;
  28516. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28517. var mesh = this.meshes[meshIndex];
  28518. if (predicate) {
  28519. if (!predicate(mesh)) {
  28520. continue;
  28521. }
  28522. }
  28523. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28524. continue;
  28525. }
  28526. var world = mesh.getWorldMatrix();
  28527. var ray = rayFunction(world);
  28528. var result = mesh.intersects(ray, fastCheck);
  28529. if (!result || !result.hit)
  28530. continue;
  28531. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28532. continue;
  28533. pickingInfo = result;
  28534. if (fastCheck) {
  28535. break;
  28536. }
  28537. }
  28538. return pickingInfo || new BABYLON.PickingInfo();
  28539. };
  28540. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28541. if (!BABYLON.PickingInfo) {
  28542. return null;
  28543. }
  28544. var pickingInfos = new Array();
  28545. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28546. var mesh = this.meshes[meshIndex];
  28547. if (predicate) {
  28548. if (!predicate(mesh)) {
  28549. continue;
  28550. }
  28551. }
  28552. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28553. continue;
  28554. }
  28555. var world = mesh.getWorldMatrix();
  28556. var ray = rayFunction(world);
  28557. var result = mesh.intersects(ray, false);
  28558. if (!result || !result.hit)
  28559. continue;
  28560. pickingInfos.push(result);
  28561. }
  28562. return pickingInfos;
  28563. };
  28564. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28565. if (!BABYLON.PickingInfo) {
  28566. return null;
  28567. }
  28568. var pickingInfo = null;
  28569. if (!camera) {
  28570. if (!this.activeCamera) {
  28571. return null;
  28572. }
  28573. camera = this.activeCamera;
  28574. }
  28575. if (this.spriteManagers.length > 0) {
  28576. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28577. var spriteManager = this.spriteManagers[spriteIndex];
  28578. if (!spriteManager.isPickable) {
  28579. continue;
  28580. }
  28581. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28582. if (!result || !result.hit)
  28583. continue;
  28584. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28585. continue;
  28586. pickingInfo = result;
  28587. if (fastCheck) {
  28588. break;
  28589. }
  28590. }
  28591. }
  28592. return pickingInfo || new BABYLON.PickingInfo();
  28593. };
  28594. /** Launch a ray to try to pick a mesh in the scene
  28595. * @param x position on screen
  28596. * @param y position on screen
  28597. * @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
  28598. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28599. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28600. * @returns a PickingInfo
  28601. */
  28602. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28603. var _this = this;
  28604. if (!BABYLON.PickingInfo) {
  28605. return null;
  28606. }
  28607. var result = this._internalPick(function (world) {
  28608. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28609. return _this._tempPickingRay;
  28610. }, predicate, fastCheck);
  28611. if (result) {
  28612. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28613. }
  28614. return result;
  28615. };
  28616. /** Launch a ray to try to pick a sprite in the scene
  28617. * @param x position on screen
  28618. * @param y position on screen
  28619. * @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
  28620. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28621. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28622. * @returns a PickingInfo
  28623. */
  28624. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28625. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28626. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28627. };
  28628. /** Use the given ray to pick a mesh in the scene
  28629. * @param ray The ray to use to pick meshes
  28630. * @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
  28631. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28632. * @returns a PickingInfo
  28633. */
  28634. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28635. var _this = this;
  28636. var result = this._internalPick(function (world) {
  28637. if (!_this._pickWithRayInverseMatrix) {
  28638. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28639. }
  28640. world.invertToRef(_this._pickWithRayInverseMatrix);
  28641. if (!_this._cachedRayForTransform) {
  28642. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28643. }
  28644. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28645. return _this._cachedRayForTransform;
  28646. }, predicate, fastCheck);
  28647. if (result) {
  28648. result.ray = ray;
  28649. }
  28650. return result;
  28651. };
  28652. /**
  28653. * Launch a ray to try to pick a mesh in the scene
  28654. * @param x X position on screen
  28655. * @param y Y position on screen
  28656. * @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
  28657. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28658. * @returns an array of PickingInfo
  28659. */
  28660. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28661. var _this = this;
  28662. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28663. };
  28664. /**
  28665. * Launch a ray to try to pick a mesh in the scene
  28666. * @param ray Ray to use
  28667. * @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
  28668. * @returns an array of PickingInfo
  28669. */
  28670. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28671. var _this = this;
  28672. return this._internalMultiPick(function (world) {
  28673. if (!_this._pickWithRayInverseMatrix) {
  28674. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28675. }
  28676. world.invertToRef(_this._pickWithRayInverseMatrix);
  28677. if (!_this._cachedRayForTransform) {
  28678. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28679. }
  28680. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28681. return _this._cachedRayForTransform;
  28682. }, predicate);
  28683. };
  28684. /**
  28685. * Force the value of meshUnderPointer
  28686. * @param mesh defines the mesh to use
  28687. */
  28688. Scene.prototype.setPointerOverMesh = function (mesh) {
  28689. if (this._pointerOverMesh === mesh) {
  28690. return;
  28691. }
  28692. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28693. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28694. }
  28695. this._pointerOverMesh = mesh;
  28696. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28697. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28698. }
  28699. };
  28700. /**
  28701. * Gets the mesh under the pointer
  28702. * @returns a Mesh or null if no mesh is under the pointer
  28703. */
  28704. Scene.prototype.getPointerOverMesh = function () {
  28705. return this._pointerOverMesh;
  28706. };
  28707. /**
  28708. * Force the sprite under the pointer
  28709. * @param sprite defines the sprite to use
  28710. */
  28711. Scene.prototype.setPointerOverSprite = function (sprite) {
  28712. if (this._pointerOverSprite === sprite) {
  28713. return;
  28714. }
  28715. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28716. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28717. }
  28718. this._pointerOverSprite = sprite;
  28719. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28720. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28721. }
  28722. };
  28723. /**
  28724. * Gets the sprite under the pointer
  28725. * @returns a Sprite or null if no sprite is under the pointer
  28726. */
  28727. Scene.prototype.getPointerOverSprite = function () {
  28728. return this._pointerOverSprite;
  28729. };
  28730. // Physics
  28731. /**
  28732. * Gets the current physics engine
  28733. * @returns a PhysicsEngine or null if none attached
  28734. */
  28735. Scene.prototype.getPhysicsEngine = function () {
  28736. return this._physicsEngine;
  28737. };
  28738. /**
  28739. * Enables physics to the current scene
  28740. * @param gravity defines the scene's gravity for the physics engine
  28741. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28742. * @return a boolean indicating if the physics engine was initialized
  28743. */
  28744. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28745. if (gravity === void 0) { gravity = null; }
  28746. if (this._physicsEngine) {
  28747. return true;
  28748. }
  28749. try {
  28750. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28751. return true;
  28752. }
  28753. catch (e) {
  28754. BABYLON.Tools.Error(e.message);
  28755. return false;
  28756. }
  28757. };
  28758. /**
  28759. * Disables and disposes the physics engine associated with the scene
  28760. */
  28761. Scene.prototype.disablePhysicsEngine = function () {
  28762. if (!this._physicsEngine) {
  28763. return;
  28764. }
  28765. this._physicsEngine.dispose();
  28766. this._physicsEngine = null;
  28767. };
  28768. /**
  28769. * Gets a boolean indicating if there is an active physics engine
  28770. * @returns a boolean indicating if there is an active physics engine
  28771. */
  28772. Scene.prototype.isPhysicsEnabled = function () {
  28773. return this._physicsEngine !== undefined;
  28774. };
  28775. /**
  28776. * Deletes a physics compound impostor
  28777. * @param compound defines the compound to delete
  28778. */
  28779. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28780. var mesh = compound.parts[0].mesh;
  28781. if (mesh.physicsImpostor) {
  28782. mesh.physicsImpostor.dispose( /*true*/);
  28783. mesh.physicsImpostor = null;
  28784. }
  28785. };
  28786. // Misc.
  28787. /** @hidden */
  28788. Scene.prototype._rebuildGeometries = function () {
  28789. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28790. var geometry = _a[_i];
  28791. geometry._rebuild();
  28792. }
  28793. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28794. var mesh = _c[_b];
  28795. mesh._rebuild();
  28796. }
  28797. if (this.postProcessManager) {
  28798. this.postProcessManager._rebuild();
  28799. }
  28800. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28801. var layer = _e[_d];
  28802. layer._rebuild();
  28803. }
  28804. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28805. var effectLayer = _g[_f];
  28806. effectLayer._rebuild();
  28807. }
  28808. if (this._boundingBoxRenderer) {
  28809. this._boundingBoxRenderer._rebuild();
  28810. }
  28811. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28812. var system = _j[_h];
  28813. system.rebuild();
  28814. }
  28815. if (this._postProcessRenderPipelineManager) {
  28816. this._postProcessRenderPipelineManager._rebuild();
  28817. }
  28818. };
  28819. /** @hidden */
  28820. Scene.prototype._rebuildTextures = function () {
  28821. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28822. var texture = _a[_i];
  28823. texture._rebuild();
  28824. }
  28825. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28826. };
  28827. /**
  28828. * Creates a default light for the scene.
  28829. * @param replace Whether to replace the existing lights in the scene.
  28830. */
  28831. Scene.prototype.createDefaultLight = function (replace) {
  28832. if (replace === void 0) { replace = false; }
  28833. // Dispose existing light in replace mode.
  28834. if (replace) {
  28835. if (this.lights) {
  28836. for (var i = 0; i < this.lights.length; i++) {
  28837. this.lights[i].dispose();
  28838. }
  28839. }
  28840. }
  28841. // Light
  28842. if (this.lights.length === 0) {
  28843. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28844. }
  28845. };
  28846. /**
  28847. * Creates a default camera for the scene.
  28848. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28849. * @param replace Whether to replace the existing active camera in the scene.
  28850. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28851. */
  28852. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28853. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28854. if (replace === void 0) { replace = false; }
  28855. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28856. // Dispose existing camera in replace mode.
  28857. if (replace) {
  28858. if (this.activeCamera) {
  28859. this.activeCamera.dispose();
  28860. this.activeCamera = null;
  28861. }
  28862. }
  28863. // Camera
  28864. if (!this.activeCamera) {
  28865. var worldExtends = this.getWorldExtends();
  28866. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28867. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28868. var camera;
  28869. var radius = worldSize.length() * 1.5;
  28870. // empty scene scenario!
  28871. if (!isFinite(radius)) {
  28872. radius = 1;
  28873. worldCenter.copyFromFloats(0, 0, 0);
  28874. }
  28875. if (createArcRotateCamera) {
  28876. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28877. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28878. arcRotateCamera.wheelPrecision = 100 / radius;
  28879. camera = arcRotateCamera;
  28880. }
  28881. else {
  28882. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28883. freeCamera.setTarget(worldCenter);
  28884. camera = freeCamera;
  28885. }
  28886. camera.minZ = radius * 0.01;
  28887. camera.maxZ = radius * 1000;
  28888. camera.speed = radius * 0.2;
  28889. this.activeCamera = camera;
  28890. var canvas = this.getEngine().getRenderingCanvas();
  28891. if (attachCameraControls && canvas) {
  28892. camera.attachControl(canvas);
  28893. }
  28894. }
  28895. };
  28896. /**
  28897. * Creates a default camera and a default light
  28898. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28899. * @param replace defines if the camera and/or light will replace the existing ones
  28900. * @param attachCameraControls defines if attachControl will be called on the new camera
  28901. */
  28902. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28903. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28904. if (replace === void 0) { replace = false; }
  28905. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28906. this.createDefaultLight(replace);
  28907. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28908. };
  28909. /**
  28910. * Creates a new sky box
  28911. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28912. * @param environmentTexture defines the texture to use as environment texture
  28913. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28914. * @param scale defines the overall scale of the skybox
  28915. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28916. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28917. * @returns a new mesh holding the sky box
  28918. */
  28919. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28920. if (pbr === void 0) { pbr = false; }
  28921. if (scale === void 0) { scale = 1000; }
  28922. if (blur === void 0) { blur = 0; }
  28923. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28924. if (!environmentTexture) {
  28925. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28926. return null;
  28927. }
  28928. if (setGlobalEnvTexture) {
  28929. if (environmentTexture) {
  28930. this.environmentTexture = environmentTexture;
  28931. }
  28932. }
  28933. // Skybox
  28934. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28935. if (pbr) {
  28936. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28937. hdrSkyboxMaterial.backFaceCulling = false;
  28938. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28939. if (hdrSkyboxMaterial.reflectionTexture) {
  28940. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28941. }
  28942. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28943. hdrSkyboxMaterial.disableLighting = true;
  28944. hdrSkyboxMaterial.twoSidedLighting = true;
  28945. hdrSkybox.infiniteDistance = true;
  28946. hdrSkybox.material = hdrSkyboxMaterial;
  28947. }
  28948. else {
  28949. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28950. skyboxMaterial.backFaceCulling = false;
  28951. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28952. if (skyboxMaterial.reflectionTexture) {
  28953. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28954. }
  28955. skyboxMaterial.disableLighting = true;
  28956. hdrSkybox.infiniteDistance = true;
  28957. hdrSkybox.material = skyboxMaterial;
  28958. }
  28959. return hdrSkybox;
  28960. };
  28961. /**
  28962. * Creates a new environment
  28963. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28964. * @param options defines the options you can use to configure the environment
  28965. * @returns the new EnvironmentHelper
  28966. */
  28967. Scene.prototype.createDefaultEnvironment = function (options) {
  28968. if (BABYLON.EnvironmentHelper) {
  28969. return new BABYLON.EnvironmentHelper(options, this);
  28970. }
  28971. return null;
  28972. };
  28973. /**
  28974. * Creates a new VREXperienceHelper
  28975. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28976. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28977. * @returns a new VREXperienceHelper
  28978. */
  28979. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28980. if (webVROptions === void 0) { webVROptions = {}; }
  28981. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28982. };
  28983. // Tags
  28984. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28985. if (tagsQuery === undefined) {
  28986. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28987. return list;
  28988. }
  28989. var listByTags = [];
  28990. forEach = forEach || (function (item) { return; });
  28991. for (var i in list) {
  28992. var item = list[i];
  28993. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28994. listByTags.push(item);
  28995. forEach(item);
  28996. }
  28997. }
  28998. return listByTags;
  28999. };
  29000. /**
  29001. * Get a list of meshes by tags
  29002. * @param tagsQuery defines the tags query to use
  29003. * @param forEach defines a predicate used to filter results
  29004. * @returns an array of Mesh
  29005. */
  29006. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29007. return this._getByTags(this.meshes, tagsQuery, forEach);
  29008. };
  29009. /**
  29010. * Get a list of cameras by tags
  29011. * @param tagsQuery defines the tags query to use
  29012. * @param forEach defines a predicate used to filter results
  29013. * @returns an array of Camera
  29014. */
  29015. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29016. return this._getByTags(this.cameras, tagsQuery, forEach);
  29017. };
  29018. /**
  29019. * Get a list of lights by tags
  29020. * @param tagsQuery defines the tags query to use
  29021. * @param forEach defines a predicate used to filter results
  29022. * @returns an array of Light
  29023. */
  29024. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29025. return this._getByTags(this.lights, tagsQuery, forEach);
  29026. };
  29027. /**
  29028. * Get a list of materials by tags
  29029. * @param tagsQuery defines the tags query to use
  29030. * @param forEach defines a predicate used to filter results
  29031. * @returns an array of Material
  29032. */
  29033. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29034. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29035. };
  29036. /**
  29037. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29038. * This allowed control for front to back rendering or reversly depending of the special needs.
  29039. *
  29040. * @param renderingGroupId The rendering group id corresponding to its index
  29041. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29042. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29043. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29044. */
  29045. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29046. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29047. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29048. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29049. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29050. };
  29051. /**
  29052. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29053. *
  29054. * @param renderingGroupId The rendering group id corresponding to its index
  29055. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29056. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29057. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29058. */
  29059. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29060. if (depth === void 0) { depth = true; }
  29061. if (stencil === void 0) { stencil = true; }
  29062. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29063. };
  29064. /**
  29065. * Will flag all materials as dirty to trigger new shader compilation
  29066. * @param flag defines the flag used to specify which material part must be marked as dirty
  29067. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29068. */
  29069. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29070. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29071. var material = _a[_i];
  29072. if (predicate && !predicate(material)) {
  29073. continue;
  29074. }
  29075. material.markAsDirty(flag);
  29076. }
  29077. };
  29078. /** @hidden */
  29079. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29080. var _this = this;
  29081. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29082. this._activeRequests.push(request);
  29083. request.onCompleteObservable.add(function (request) {
  29084. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29085. });
  29086. return request;
  29087. };
  29088. /** @hidden */
  29089. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29090. var _this = this;
  29091. return new Promise(function (resolve, reject) {
  29092. _this._loadFile(url, function (data) {
  29093. resolve(data);
  29094. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29095. reject(exception);
  29096. });
  29097. });
  29098. };
  29099. // Statics
  29100. Scene._FOGMODE_NONE = 0;
  29101. Scene._FOGMODE_EXP = 1;
  29102. Scene._FOGMODE_EXP2 = 2;
  29103. Scene._FOGMODE_LINEAR = 3;
  29104. Scene._uniqueIdCounter = 0;
  29105. /**
  29106. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29107. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29108. */
  29109. Scene.MinDeltaTime = 1.0;
  29110. /**
  29111. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29112. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29113. */
  29114. Scene.MaxDeltaTime = 1000.0;
  29115. /** The distance in pixel that you have to move to prevent some events */
  29116. Scene.DragMovementThreshold = 10; // in pixels
  29117. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29118. Scene.LongPressDelay = 500; // in milliseconds
  29119. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29120. Scene.DoubleClickDelay = 300; // in milliseconds
  29121. /** If you need to check double click without raising a single click at first click, enable this flag */
  29122. Scene.ExclusiveDoubleClickMode = false;
  29123. return Scene;
  29124. }());
  29125. BABYLON.Scene = Scene;
  29126. })(BABYLON || (BABYLON = {}));
  29127. //# sourceMappingURL=babylon.scene.js.map
  29128. var BABYLON;
  29129. (function (BABYLON) {
  29130. /**
  29131. * Set of assets to keep when moving a scene into an asset container.
  29132. */
  29133. var KeepAssets = /** @class */ (function () {
  29134. function KeepAssets() {
  29135. /**
  29136. * Cameras to keep.
  29137. */
  29138. this.cameras = new Array();
  29139. /**
  29140. * Lights to keep.
  29141. */
  29142. this.lights = new Array();
  29143. /**
  29144. * Meshes to keep.
  29145. */
  29146. this.meshes = new Array();
  29147. /**
  29148. * Skeletons to keep.
  29149. */
  29150. this.skeletons = new Array();
  29151. /**
  29152. * ParticleSystems to keep.
  29153. */
  29154. this.particleSystems = new Array();
  29155. /**
  29156. * Animations to keep.
  29157. */
  29158. this.animations = new Array();
  29159. /**
  29160. * AnimationGroups to keep.
  29161. */
  29162. this.animationGroups = new Array();
  29163. /**
  29164. * MultiMaterials to keep.
  29165. */
  29166. this.multiMaterials = new Array();
  29167. /**
  29168. * Materials to keep.
  29169. */
  29170. this.materials = new Array();
  29171. /**
  29172. * MorphTargetManagers to keep.
  29173. */
  29174. this.morphTargetManagers = new Array();
  29175. /**
  29176. * Geometries to keep.
  29177. */
  29178. this.geometries = new Array();
  29179. /**
  29180. * TransformNodes to keep.
  29181. */
  29182. this.transformNodes = new Array();
  29183. /**
  29184. * LensFlareSystems to keep.
  29185. */
  29186. this.lensFlareSystems = new Array();
  29187. /**
  29188. * ShadowGenerators to keep.
  29189. */
  29190. this.shadowGenerators = new Array();
  29191. /**
  29192. * ActionManagers to keep.
  29193. */
  29194. this.actionManagers = new Array();
  29195. /**
  29196. * Sounds to keep.
  29197. */
  29198. this.sounds = new Array();
  29199. /**
  29200. * Textures to keep.
  29201. */
  29202. this.textures = new Array();
  29203. /**
  29204. * Effect layers to keep.
  29205. */
  29206. this.effectLayers = new Array();
  29207. }
  29208. return KeepAssets;
  29209. }());
  29210. BABYLON.KeepAssets = KeepAssets;
  29211. /**
  29212. * Container with a set of assets that can be added or removed from a scene.
  29213. */
  29214. var AssetContainer = /** @class */ (function () {
  29215. /**
  29216. * Instantiates an AssetContainer.
  29217. * @param scene The scene the AssetContainer belongs to.
  29218. */
  29219. function AssetContainer(scene) {
  29220. // Objects
  29221. /**
  29222. * Cameras populated in the container.
  29223. */
  29224. this.cameras = new Array();
  29225. /**
  29226. * Lights populated in the container.
  29227. */
  29228. this.lights = new Array();
  29229. /**
  29230. * Meshes populated in the container.
  29231. */
  29232. this.meshes = new Array();
  29233. /**
  29234. * Skeletons populated in the container.
  29235. */
  29236. this.skeletons = new Array();
  29237. /**
  29238. * ParticleSystems populated in the container.
  29239. */
  29240. this.particleSystems = new Array();
  29241. /**
  29242. * Animations populated in the container.
  29243. */
  29244. this.animations = new Array();
  29245. /**
  29246. * AnimationGroups populated in the container.
  29247. */
  29248. this.animationGroups = new Array();
  29249. /**
  29250. * MultiMaterials populated in the container.
  29251. */
  29252. this.multiMaterials = new Array();
  29253. /**
  29254. * Materials populated in the container.
  29255. */
  29256. this.materials = new Array();
  29257. /**
  29258. * MorphTargetManagers populated in the container.
  29259. */
  29260. this.morphTargetManagers = new Array();
  29261. /**
  29262. * Geometries populated in the container.
  29263. */
  29264. this.geometries = new Array();
  29265. /**
  29266. * TransformNodes populated in the container.
  29267. */
  29268. this.transformNodes = new Array();
  29269. /**
  29270. * LensFlareSystems populated in the container.
  29271. */
  29272. this.lensFlareSystems = new Array();
  29273. /**
  29274. * ShadowGenerators populated in the container.
  29275. */
  29276. this.shadowGenerators = new Array();
  29277. /**
  29278. * ActionManagers populated in the container.
  29279. */
  29280. this.actionManagers = new Array();
  29281. /**
  29282. * Sounds populated in the container.
  29283. */
  29284. this.sounds = new Array();
  29285. /**
  29286. * Textures populated in the container.
  29287. */
  29288. this.textures = new Array();
  29289. /**
  29290. * Effect layers populated in the container.
  29291. */
  29292. this.effectLayers = new Array();
  29293. this.scene = scene;
  29294. }
  29295. /**
  29296. * Adds all the assets from the container to the scene.
  29297. */
  29298. AssetContainer.prototype.addAllToScene = function () {
  29299. var _this = this;
  29300. this.cameras.forEach(function (o) {
  29301. _this.scene.addCamera(o);
  29302. });
  29303. this.lights.forEach(function (o) {
  29304. _this.scene.addLight(o);
  29305. });
  29306. this.meshes.forEach(function (o) {
  29307. _this.scene.addMesh(o);
  29308. });
  29309. this.skeletons.forEach(function (o) {
  29310. _this.scene.addSkeleton(o);
  29311. });
  29312. this.particleSystems.forEach(function (o) {
  29313. _this.scene.addParticleSystem(o);
  29314. });
  29315. this.animations.forEach(function (o) {
  29316. _this.scene.addAnimation(o);
  29317. });
  29318. this.animationGroups.forEach(function (o) {
  29319. _this.scene.addAnimationGroup(o);
  29320. });
  29321. this.multiMaterials.forEach(function (o) {
  29322. _this.scene.addMultiMaterial(o);
  29323. });
  29324. this.materials.forEach(function (o) {
  29325. _this.scene.addMaterial(o);
  29326. });
  29327. this.morphTargetManagers.forEach(function (o) {
  29328. _this.scene.addMorphTargetManager(o);
  29329. });
  29330. this.geometries.forEach(function (o) {
  29331. _this.scene.addGeometry(o);
  29332. });
  29333. this.transformNodes.forEach(function (o) {
  29334. _this.scene.addTransformNode(o);
  29335. });
  29336. this.lensFlareSystems.forEach(function (o) {
  29337. _this.scene.addLensFlareSystem(o);
  29338. });
  29339. this.actionManagers.forEach(function (o) {
  29340. _this.scene.addActionManager(o);
  29341. });
  29342. this.sounds.forEach(function (o) {
  29343. o.play();
  29344. o.autoplay = true;
  29345. _this.scene.mainSoundTrack.AddSound(o);
  29346. });
  29347. this.textures.forEach(function (o) {
  29348. _this.scene.addTexture(o);
  29349. });
  29350. this.effectLayers.forEach(function (o) {
  29351. _this.scene.addEffectLayer(o);
  29352. });
  29353. };
  29354. /**
  29355. * Removes all the assets in the container from the scene
  29356. */
  29357. AssetContainer.prototype.removeAllFromScene = function () {
  29358. var _this = this;
  29359. this.cameras.forEach(function (o) {
  29360. _this.scene.removeCamera(o);
  29361. });
  29362. this.lights.forEach(function (o) {
  29363. _this.scene.removeLight(o);
  29364. });
  29365. this.meshes.forEach(function (o) {
  29366. _this.scene.removeMesh(o);
  29367. });
  29368. this.skeletons.forEach(function (o) {
  29369. _this.scene.removeSkeleton(o);
  29370. });
  29371. this.particleSystems.forEach(function (o) {
  29372. _this.scene.removeParticleSystem(o);
  29373. });
  29374. this.animations.forEach(function (o) {
  29375. _this.scene.removeAnimation(o);
  29376. });
  29377. this.animationGroups.forEach(function (o) {
  29378. _this.scene.removeAnimationGroup(o);
  29379. });
  29380. this.multiMaterials.forEach(function (o) {
  29381. _this.scene.removeMultiMaterial(o);
  29382. });
  29383. this.materials.forEach(function (o) {
  29384. _this.scene.removeMaterial(o);
  29385. });
  29386. this.morphTargetManagers.forEach(function (o) {
  29387. _this.scene.removeMorphTargetManager(o);
  29388. });
  29389. this.geometries.forEach(function (o) {
  29390. _this.scene.removeGeometry(o);
  29391. });
  29392. this.transformNodes.forEach(function (o) {
  29393. _this.scene.removeTransformNode(o);
  29394. });
  29395. this.lensFlareSystems.forEach(function (o) {
  29396. _this.scene.removeLensFlareSystem(o);
  29397. });
  29398. this.actionManagers.forEach(function (o) {
  29399. _this.scene.removeActionManager(o);
  29400. });
  29401. this.sounds.forEach(function (o) {
  29402. o.stop();
  29403. o.autoplay = false;
  29404. _this.scene.mainSoundTrack.RemoveSound(o);
  29405. });
  29406. this.textures.forEach(function (o) {
  29407. _this.scene.removeTexture(o);
  29408. });
  29409. this.effectLayers.forEach(function (o) {
  29410. _this.scene.removeEffectLayer(o);
  29411. });
  29412. };
  29413. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29414. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29415. var asset = sourceAssets_1[_i];
  29416. var move = true;
  29417. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29418. var keepAsset = keepAssets_1[_a];
  29419. if (asset === keepAsset) {
  29420. move = false;
  29421. break;
  29422. }
  29423. }
  29424. if (move) {
  29425. targetAssets.push(asset);
  29426. }
  29427. }
  29428. };
  29429. /**
  29430. * Removes all the assets contained in the scene and adds them to the container.
  29431. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29432. */
  29433. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29434. if (keepAssets === undefined) {
  29435. keepAssets = new KeepAssets();
  29436. }
  29437. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29438. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29439. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29440. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29441. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29442. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29443. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29444. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29445. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29446. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29447. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29448. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29449. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29450. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29451. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29452. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29453. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29454. this.removeAllFromScene();
  29455. };
  29456. /**
  29457. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29458. * @returns the root mesh
  29459. */
  29460. AssetContainer.prototype.createRootMesh = function () {
  29461. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29462. this.meshes.forEach(function (m) {
  29463. if (!m.parent) {
  29464. rootMesh.addChild(m);
  29465. }
  29466. });
  29467. this.meshes.unshift(rootMesh);
  29468. return rootMesh;
  29469. };
  29470. return AssetContainer;
  29471. }());
  29472. BABYLON.AssetContainer = AssetContainer;
  29473. })(BABYLON || (BABYLON = {}));
  29474. //# sourceMappingURL=babylon.assetContainer.js.map
  29475. var BABYLON;
  29476. (function (BABYLON) {
  29477. var Buffer = /** @class */ (function () {
  29478. /**
  29479. * Constructor
  29480. * @param engine the engine
  29481. * @param data the data to use for this buffer
  29482. * @param updatable whether the data is updatable
  29483. * @param stride the stride (optional)
  29484. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29485. * @param instanced whether the buffer is instanced (optional)
  29486. * @param useBytes set to true if the stride in in bytes (optional)
  29487. */
  29488. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29489. if (stride === void 0) { stride = 0; }
  29490. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29491. if (instanced === void 0) { instanced = false; }
  29492. if (useBytes === void 0) { useBytes = false; }
  29493. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29494. this._engine = engine.getScene().getEngine();
  29495. }
  29496. else {
  29497. this._engine = engine;
  29498. }
  29499. this._updatable = updatable;
  29500. this._instanced = instanced;
  29501. this._data = data;
  29502. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29503. if (!postponeInternalCreation) { // by default
  29504. this.create();
  29505. }
  29506. }
  29507. /**
  29508. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29509. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29510. * @param offset defines offset in the buffer (0 by default)
  29511. * @param size defines the size in floats of attributes (position is 3 for instance)
  29512. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29513. * @param instanced defines if the vertex buffer contains indexed data
  29514. * @param useBytes defines if the offset and stride are in bytes
  29515. * @returns the new vertex buffer
  29516. */
  29517. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29518. if (useBytes === void 0) { useBytes = false; }
  29519. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29520. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29521. // a lot of these parameters are ignored as they are overriden by the buffer
  29522. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29523. };
  29524. // Properties
  29525. Buffer.prototype.isUpdatable = function () {
  29526. return this._updatable;
  29527. };
  29528. Buffer.prototype.getData = function () {
  29529. return this._data;
  29530. };
  29531. Buffer.prototype.getBuffer = function () {
  29532. return this._buffer;
  29533. };
  29534. /**
  29535. * Gets the stride in float32 units (i.e. byte stride / 4).
  29536. * May not be an integer if the byte stride is not divisible by 4.
  29537. * DEPRECATED. Use byteStride instead.
  29538. * @returns the stride in float32 units
  29539. */
  29540. Buffer.prototype.getStrideSize = function () {
  29541. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29542. };
  29543. // Methods
  29544. Buffer.prototype.create = function (data) {
  29545. if (data === void 0) { data = null; }
  29546. if (!data && this._buffer) {
  29547. return; // nothing to do
  29548. }
  29549. data = data || this._data;
  29550. if (!data) {
  29551. return;
  29552. }
  29553. if (!this._buffer) { // create buffer
  29554. if (this._updatable) {
  29555. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29556. this._data = data;
  29557. }
  29558. else {
  29559. this._buffer = this._engine.createVertexBuffer(data);
  29560. }
  29561. }
  29562. else if (this._updatable) { // update buffer
  29563. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29564. this._data = data;
  29565. }
  29566. };
  29567. Buffer.prototype._rebuild = function () {
  29568. this._buffer = null;
  29569. this.create(this._data);
  29570. };
  29571. Buffer.prototype.update = function (data) {
  29572. this.create(data);
  29573. };
  29574. /**
  29575. * Updates the data directly.
  29576. * @param data the new data
  29577. * @param offset the new offset
  29578. * @param vertexCount the vertex count (optional)
  29579. * @param useBytes set to true if the offset is in bytes
  29580. */
  29581. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29582. if (useBytes === void 0) { useBytes = false; }
  29583. if (!this._buffer) {
  29584. return;
  29585. }
  29586. if (this._updatable) { // update buffer
  29587. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29588. this._data = null;
  29589. }
  29590. };
  29591. Buffer.prototype.dispose = function () {
  29592. if (!this._buffer) {
  29593. return;
  29594. }
  29595. if (this._engine._releaseBuffer(this._buffer)) {
  29596. this._buffer = null;
  29597. }
  29598. };
  29599. return Buffer;
  29600. }());
  29601. BABYLON.Buffer = Buffer;
  29602. })(BABYLON || (BABYLON = {}));
  29603. //# sourceMappingURL=babylon.buffer.js.map
  29604. var BABYLON;
  29605. (function (BABYLON) {
  29606. var VertexBuffer = /** @class */ (function () {
  29607. /**
  29608. * Constructor
  29609. * @param engine the engine
  29610. * @param data the data to use for this vertex buffer
  29611. * @param kind the vertex buffer kind
  29612. * @param updatable whether the data is updatable
  29613. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29614. * @param stride the stride (optional)
  29615. * @param instanced whether the buffer is instanced (optional)
  29616. * @param offset the offset of the data (optional)
  29617. * @param size the number of components (optional)
  29618. * @param type the type of the component (optional)
  29619. * @param normalized whether the data contains normalized data (optional)
  29620. * @param useBytes set to true if stride and offset are in bytes (optional)
  29621. */
  29622. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29623. if (normalized === void 0) { normalized = false; }
  29624. if (useBytes === void 0) { useBytes = false; }
  29625. if (data instanceof BABYLON.Buffer) {
  29626. this._buffer = data;
  29627. this._ownsBuffer = false;
  29628. }
  29629. else {
  29630. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29631. this._ownsBuffer = true;
  29632. }
  29633. this._kind = kind;
  29634. if (type == undefined) {
  29635. var data_1 = this.getData();
  29636. this.type = VertexBuffer.FLOAT;
  29637. if (data_1 instanceof Int8Array)
  29638. this.type = VertexBuffer.BYTE;
  29639. else if (data_1 instanceof Uint8Array)
  29640. this.type = VertexBuffer.UNSIGNED_BYTE;
  29641. else if (data_1 instanceof Int16Array)
  29642. this.type = VertexBuffer.SHORT;
  29643. else if (data_1 instanceof Uint16Array)
  29644. this.type = VertexBuffer.UNSIGNED_SHORT;
  29645. else if (data_1 instanceof Int32Array)
  29646. this.type = VertexBuffer.INT;
  29647. else if (data_1 instanceof Uint32Array)
  29648. this.type = VertexBuffer.UNSIGNED_INT;
  29649. }
  29650. else {
  29651. this.type = type;
  29652. }
  29653. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29654. if (useBytes) {
  29655. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29656. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29657. this.byteOffset = offset || 0;
  29658. }
  29659. else {
  29660. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29661. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29662. this.byteOffset = (offset || 0) * typeByteLength;
  29663. }
  29664. this.normalized = normalized;
  29665. this._instanced = instanced !== undefined ? instanced : false;
  29666. this._instanceDivisor = instanced ? 1 : 0;
  29667. }
  29668. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29669. /**
  29670. * Gets or sets the instance divisor when in instanced mode
  29671. */
  29672. get: function () {
  29673. return this._instanceDivisor;
  29674. },
  29675. set: function (value) {
  29676. this._instanceDivisor = value;
  29677. if (value == 0) {
  29678. this._instanced = false;
  29679. }
  29680. else {
  29681. this._instanced = true;
  29682. }
  29683. },
  29684. enumerable: true,
  29685. configurable: true
  29686. });
  29687. VertexBuffer.prototype._rebuild = function () {
  29688. if (!this._buffer) {
  29689. return;
  29690. }
  29691. this._buffer._rebuild();
  29692. };
  29693. /**
  29694. * Returns the kind of the VertexBuffer (string).
  29695. */
  29696. VertexBuffer.prototype.getKind = function () {
  29697. return this._kind;
  29698. };
  29699. // Properties
  29700. /**
  29701. * Boolean : is the VertexBuffer updatable ?
  29702. */
  29703. VertexBuffer.prototype.isUpdatable = function () {
  29704. return this._buffer.isUpdatable();
  29705. };
  29706. /**
  29707. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29708. */
  29709. VertexBuffer.prototype.getData = function () {
  29710. return this._buffer.getData();
  29711. };
  29712. /**
  29713. * Returns the WebGLBuffer associated to the VertexBuffer.
  29714. */
  29715. VertexBuffer.prototype.getBuffer = function () {
  29716. return this._buffer.getBuffer();
  29717. };
  29718. /**
  29719. * Returns the stride as a multiple of the type byte length.
  29720. * DEPRECATED. Use byteStride instead.
  29721. */
  29722. VertexBuffer.prototype.getStrideSize = function () {
  29723. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29724. };
  29725. /**
  29726. * Returns the offset as a multiple of the type byte length.
  29727. * DEPRECATED. Use byteOffset instead.
  29728. */
  29729. VertexBuffer.prototype.getOffset = function () {
  29730. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29731. };
  29732. /**
  29733. * Returns the number of components per vertex attribute (integer).
  29734. */
  29735. VertexBuffer.prototype.getSize = function () {
  29736. return this._size;
  29737. };
  29738. /**
  29739. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29740. */
  29741. VertexBuffer.prototype.getIsInstanced = function () {
  29742. return this._instanced;
  29743. };
  29744. /**
  29745. * Returns the instancing divisor, zero for non-instanced (integer).
  29746. */
  29747. VertexBuffer.prototype.getInstanceDivisor = function () {
  29748. return this._instanceDivisor;
  29749. };
  29750. // Methods
  29751. /**
  29752. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29753. * Returns the created WebGLBuffer.
  29754. */
  29755. VertexBuffer.prototype.create = function (data) {
  29756. return this._buffer.create(data);
  29757. };
  29758. /**
  29759. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29760. * This function will create a new buffer if the current one is not updatable
  29761. * Returns the updated WebGLBuffer.
  29762. */
  29763. VertexBuffer.prototype.update = function (data) {
  29764. return this._buffer.update(data);
  29765. };
  29766. /**
  29767. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29768. * Returns the directly updated WebGLBuffer.
  29769. * @param data the new data
  29770. * @param offset the new offset
  29771. * @param useBytes set to true if the offset is in bytes
  29772. */
  29773. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29774. if (useBytes === void 0) { useBytes = false; }
  29775. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29776. };
  29777. /**
  29778. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29779. */
  29780. VertexBuffer.prototype.dispose = function () {
  29781. if (this._ownsBuffer) {
  29782. this._buffer.dispose();
  29783. }
  29784. };
  29785. /**
  29786. * Enumerates each value of this vertex buffer as numbers.
  29787. * @param count the number of values to enumerate
  29788. * @param callback the callback function called for each value
  29789. */
  29790. VertexBuffer.prototype.forEach = function (count, callback) {
  29791. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29792. };
  29793. Object.defineProperty(VertexBuffer, "PositionKind", {
  29794. get: function () {
  29795. return VertexBuffer._PositionKind;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. Object.defineProperty(VertexBuffer, "NormalKind", {
  29801. get: function () {
  29802. return VertexBuffer._NormalKind;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(VertexBuffer, "TangentKind", {
  29808. get: function () {
  29809. return VertexBuffer._TangentKind;
  29810. },
  29811. enumerable: true,
  29812. configurable: true
  29813. });
  29814. Object.defineProperty(VertexBuffer, "UVKind", {
  29815. get: function () {
  29816. return VertexBuffer._UVKind;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29822. get: function () {
  29823. return VertexBuffer._UV2Kind;
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29829. get: function () {
  29830. return VertexBuffer._UV3Kind;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29836. get: function () {
  29837. return VertexBuffer._UV4Kind;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29843. get: function () {
  29844. return VertexBuffer._UV5Kind;
  29845. },
  29846. enumerable: true,
  29847. configurable: true
  29848. });
  29849. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29850. get: function () {
  29851. return VertexBuffer._UV6Kind;
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. Object.defineProperty(VertexBuffer, "ColorKind", {
  29857. get: function () {
  29858. return VertexBuffer._ColorKind;
  29859. },
  29860. enumerable: true,
  29861. configurable: true
  29862. });
  29863. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29864. get: function () {
  29865. return VertexBuffer._MatricesIndicesKind;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29871. get: function () {
  29872. return VertexBuffer._MatricesWeightsKind;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29878. get: function () {
  29879. return VertexBuffer._MatricesIndicesExtraKind;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29885. get: function () {
  29886. return VertexBuffer._MatricesWeightsExtraKind;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. /**
  29892. * Deduces the stride given a kind.
  29893. * @param kind The kind string to deduce
  29894. * @returns The deduced stride
  29895. */
  29896. VertexBuffer.DeduceStride = function (kind) {
  29897. switch (kind) {
  29898. case VertexBuffer.UVKind:
  29899. case VertexBuffer.UV2Kind:
  29900. case VertexBuffer.UV3Kind:
  29901. case VertexBuffer.UV4Kind:
  29902. case VertexBuffer.UV5Kind:
  29903. case VertexBuffer.UV6Kind:
  29904. return 2;
  29905. case VertexBuffer.NormalKind:
  29906. case VertexBuffer.PositionKind:
  29907. return 3;
  29908. case VertexBuffer.ColorKind:
  29909. case VertexBuffer.MatricesIndicesKind:
  29910. case VertexBuffer.MatricesIndicesExtraKind:
  29911. case VertexBuffer.MatricesWeightsKind:
  29912. case VertexBuffer.MatricesWeightsExtraKind:
  29913. case VertexBuffer.TangentKind:
  29914. return 4;
  29915. default:
  29916. throw new Error("Invalid kind '" + kind + "'");
  29917. }
  29918. };
  29919. /**
  29920. * Gets the byte length of the given type.
  29921. * @param type the type
  29922. * @returns the number of bytes
  29923. */
  29924. VertexBuffer.GetTypeByteLength = function (type) {
  29925. switch (type) {
  29926. case VertexBuffer.BYTE:
  29927. case VertexBuffer.UNSIGNED_BYTE:
  29928. return 1;
  29929. case VertexBuffer.SHORT:
  29930. case VertexBuffer.UNSIGNED_SHORT:
  29931. return 2;
  29932. case VertexBuffer.INT:
  29933. case VertexBuffer.FLOAT:
  29934. return 4;
  29935. default:
  29936. throw new Error("Invalid type '" + type + "'");
  29937. }
  29938. };
  29939. /**
  29940. * Enumerates each value of the given parameters as numbers.
  29941. * @param data the data to enumerate
  29942. * @param byteOffset the byte offset of the data
  29943. * @param byteStride the byte stride of the data
  29944. * @param componentCount the number of components per element
  29945. * @param componentType the type of the component
  29946. * @param count the total number of components
  29947. * @param normalized whether the data is normalized
  29948. * @param callback the callback function called for each value
  29949. */
  29950. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29951. if (data instanceof Array) {
  29952. var offset = byteOffset / 4;
  29953. var stride = byteStride / 4;
  29954. for (var index = 0; index < count; index += componentCount) {
  29955. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29956. callback(data[offset + componentIndex], index + componentIndex);
  29957. }
  29958. offset += stride;
  29959. }
  29960. }
  29961. else {
  29962. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29963. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29964. for (var index = 0; index < count; index += componentCount) {
  29965. var componentByteOffset = byteOffset;
  29966. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29967. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29968. callback(value, index + componentIndex);
  29969. componentByteOffset += componentByteLength;
  29970. }
  29971. byteOffset += byteStride;
  29972. }
  29973. }
  29974. };
  29975. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29976. switch (type) {
  29977. case VertexBuffer.BYTE: {
  29978. var value = dataView.getInt8(byteOffset);
  29979. if (normalized) {
  29980. value = Math.max(value / 127, -1);
  29981. }
  29982. return value;
  29983. }
  29984. case VertexBuffer.UNSIGNED_BYTE: {
  29985. var value = dataView.getUint8(byteOffset);
  29986. if (normalized) {
  29987. value = value / 255;
  29988. }
  29989. return value;
  29990. }
  29991. case VertexBuffer.SHORT: {
  29992. var value = dataView.getInt16(byteOffset, true);
  29993. if (normalized) {
  29994. value = Math.max(value / 16383, -1);
  29995. }
  29996. return value;
  29997. }
  29998. case VertexBuffer.UNSIGNED_SHORT: {
  29999. var value = dataView.getUint16(byteOffset, true);
  30000. if (normalized) {
  30001. value = value / 65535;
  30002. }
  30003. return value;
  30004. }
  30005. case VertexBuffer.FLOAT: {
  30006. return dataView.getFloat32(byteOffset, true);
  30007. }
  30008. default: {
  30009. throw new Error("Invalid component type " + type);
  30010. }
  30011. }
  30012. };
  30013. /**
  30014. * The byte type.
  30015. */
  30016. VertexBuffer.BYTE = 5120;
  30017. /**
  30018. * The unsigned byte type.
  30019. */
  30020. VertexBuffer.UNSIGNED_BYTE = 5121;
  30021. /**
  30022. * The short type.
  30023. */
  30024. VertexBuffer.SHORT = 5122;
  30025. /**
  30026. * The unsigned short type.
  30027. */
  30028. VertexBuffer.UNSIGNED_SHORT = 5123;
  30029. /**
  30030. * The integer type.
  30031. */
  30032. VertexBuffer.INT = 5124;
  30033. /**
  30034. * The unsigned integer type.
  30035. */
  30036. VertexBuffer.UNSIGNED_INT = 5125;
  30037. /**
  30038. * The float type.
  30039. */
  30040. VertexBuffer.FLOAT = 5126;
  30041. // Enums
  30042. VertexBuffer._PositionKind = "position";
  30043. VertexBuffer._NormalKind = "normal";
  30044. VertexBuffer._TangentKind = "tangent";
  30045. VertexBuffer._UVKind = "uv";
  30046. VertexBuffer._UV2Kind = "uv2";
  30047. VertexBuffer._UV3Kind = "uv3";
  30048. VertexBuffer._UV4Kind = "uv4";
  30049. VertexBuffer._UV5Kind = "uv5";
  30050. VertexBuffer._UV6Kind = "uv6";
  30051. VertexBuffer._ColorKind = "color";
  30052. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30053. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30054. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30055. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30056. return VertexBuffer;
  30057. }());
  30058. BABYLON.VertexBuffer = VertexBuffer;
  30059. })(BABYLON || (BABYLON = {}));
  30060. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30061. var BABYLON;
  30062. (function (BABYLON) {
  30063. /**
  30064. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30065. */
  30066. var DummyInternalTextureTracker = /** @class */ (function () {
  30067. function DummyInternalTextureTracker() {
  30068. /**
  30069. * Gets or set the previous tracker in the list
  30070. */
  30071. this.previous = null;
  30072. /**
  30073. * Gets or set the next tracker in the list
  30074. */
  30075. this.next = null;
  30076. }
  30077. return DummyInternalTextureTracker;
  30078. }());
  30079. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30080. })(BABYLON || (BABYLON = {}));
  30081. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30082. var BABYLON;
  30083. (function (BABYLON) {
  30084. /**
  30085. * Class used to store data associated with WebGL texture data for the engine
  30086. * This class should not be used directly
  30087. */
  30088. var InternalTexture = /** @class */ (function () {
  30089. /**
  30090. * Creates a new InternalTexture
  30091. * @param engine defines the engine to use
  30092. * @param dataSource defines the type of data that will be used
  30093. */
  30094. function InternalTexture(engine, dataSource) {
  30095. /**
  30096. * Observable called when the texture is loaded
  30097. */
  30098. this.onLoadedObservable = new BABYLON.Observable();
  30099. /**
  30100. * Gets or set the previous tracker in the list
  30101. */
  30102. this.previous = null;
  30103. /**
  30104. * Gets or set the next tracker in the list
  30105. */
  30106. this.next = null;
  30107. // Private
  30108. /** @hidden */
  30109. this._initialSlot = -1;
  30110. /** @hidden */
  30111. this._designatedSlot = -1;
  30112. /** @hidden */
  30113. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30114. /** @hidden */
  30115. this._comparisonFunction = 0;
  30116. /** @hidden */
  30117. this._isRGBD = false;
  30118. /** @hidden */
  30119. this._references = 1;
  30120. this._engine = engine;
  30121. this._dataSource = dataSource;
  30122. this._webGLTexture = engine._createTexture();
  30123. }
  30124. /**
  30125. * Gets the Engine the texture belongs to.
  30126. * @returns The babylon engine
  30127. */
  30128. InternalTexture.prototype.getEngine = function () {
  30129. return this._engine;
  30130. };
  30131. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30132. /**
  30133. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30134. */
  30135. get: function () {
  30136. return this._dataSource;
  30137. },
  30138. enumerable: true,
  30139. configurable: true
  30140. });
  30141. /**
  30142. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30143. */
  30144. InternalTexture.prototype.incrementReferences = function () {
  30145. this._references++;
  30146. };
  30147. /**
  30148. * Change the size of the texture (not the size of the content)
  30149. * @param width defines the new width
  30150. * @param height defines the new height
  30151. * @param depth defines the new depth (1 by default)
  30152. */
  30153. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30154. if (depth === void 0) { depth = 1; }
  30155. this.width = width;
  30156. this.height = height;
  30157. this.depth = depth;
  30158. this.baseWidth = width;
  30159. this.baseHeight = height;
  30160. this.baseDepth = depth;
  30161. this._size = width * height * depth;
  30162. };
  30163. /** @hidden */
  30164. InternalTexture.prototype._rebuild = function () {
  30165. var _this = this;
  30166. var proxy;
  30167. this.isReady = false;
  30168. this._cachedCoordinatesMode = null;
  30169. this._cachedWrapU = null;
  30170. this._cachedWrapV = null;
  30171. this._cachedAnisotropicFilteringLevel = null;
  30172. switch (this._dataSource) {
  30173. case InternalTexture.DATASOURCE_TEMP:
  30174. return;
  30175. case InternalTexture.DATASOURCE_URL:
  30176. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30177. _this.isReady = true;
  30178. }, null, this._buffer, undefined, this.format);
  30179. proxy._swapAndDie(this);
  30180. return;
  30181. case InternalTexture.DATASOURCE_RAW:
  30182. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30183. proxy._swapAndDie(this);
  30184. this.isReady = true;
  30185. return;
  30186. case InternalTexture.DATASOURCE_RAW3D:
  30187. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30188. proxy._swapAndDie(this);
  30189. this.isReady = true;
  30190. return;
  30191. case InternalTexture.DATASOURCE_DYNAMIC:
  30192. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30193. proxy._swapAndDie(this);
  30194. // The engine will make sure to update content so no need to flag it as isReady = true
  30195. return;
  30196. case InternalTexture.DATASOURCE_RENDERTARGET:
  30197. var options = new BABYLON.RenderTargetCreationOptions();
  30198. options.generateDepthBuffer = this._generateDepthBuffer;
  30199. options.generateMipMaps = this.generateMipMaps;
  30200. options.generateStencilBuffer = this._generateStencilBuffer;
  30201. options.samplingMode = this.samplingMode;
  30202. options.type = this.type;
  30203. if (this.isCube) {
  30204. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30205. }
  30206. else {
  30207. var size = {
  30208. width: this.width,
  30209. height: this.height
  30210. };
  30211. proxy = this._engine.createRenderTargetTexture(size, options);
  30212. }
  30213. proxy._swapAndDie(this);
  30214. this.isReady = true;
  30215. return;
  30216. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30217. var depthTextureOptions = {
  30218. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30219. comparisonFunction: this._comparisonFunction,
  30220. generateStencil: this._generateStencilBuffer,
  30221. isCube: this.isCube
  30222. };
  30223. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30224. proxy._swapAndDie(this);
  30225. this.isReady = true;
  30226. return;
  30227. case InternalTexture.DATASOURCE_CUBE:
  30228. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30229. _this.isReady = true;
  30230. }, null, this.format, this._extension);
  30231. proxy._swapAndDie(this);
  30232. return;
  30233. case InternalTexture.DATASOURCE_CUBERAW:
  30234. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30235. proxy._swapAndDie(this);
  30236. this.isReady = true;
  30237. return;
  30238. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30239. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30240. if (proxy) {
  30241. proxy._swapAndDie(_this);
  30242. }
  30243. _this.isReady = true;
  30244. }, null, this.format, this._extension);
  30245. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30246. return;
  30247. }
  30248. };
  30249. InternalTexture.prototype._swapAndDie = function (target) {
  30250. target._webGLTexture = this._webGLTexture;
  30251. if (this._framebuffer) {
  30252. target._framebuffer = this._framebuffer;
  30253. }
  30254. if (this._depthStencilBuffer) {
  30255. target._depthStencilBuffer = this._depthStencilBuffer;
  30256. }
  30257. if (this._lodTextureHigh) {
  30258. if (target._lodTextureHigh) {
  30259. target._lodTextureHigh.dispose();
  30260. }
  30261. target._lodTextureHigh = this._lodTextureHigh;
  30262. }
  30263. if (this._lodTextureMid) {
  30264. if (target._lodTextureMid) {
  30265. target._lodTextureMid.dispose();
  30266. }
  30267. target._lodTextureMid = this._lodTextureMid;
  30268. }
  30269. if (this._lodTextureLow) {
  30270. if (target._lodTextureLow) {
  30271. target._lodTextureLow.dispose();
  30272. }
  30273. target._lodTextureLow = this._lodTextureLow;
  30274. }
  30275. var cache = this._engine.getLoadedTexturesCache();
  30276. var index = cache.indexOf(this);
  30277. if (index !== -1) {
  30278. cache.splice(index, 1);
  30279. }
  30280. };
  30281. /**
  30282. * Dispose the current allocated resources
  30283. */
  30284. InternalTexture.prototype.dispose = function () {
  30285. if (!this._webGLTexture) {
  30286. return;
  30287. }
  30288. this._references--;
  30289. if (this._references === 0) {
  30290. this._engine._releaseTexture(this);
  30291. this._webGLTexture = null;
  30292. this.previous = null;
  30293. this.next = null;
  30294. }
  30295. };
  30296. /**
  30297. * The source of the texture data is unknown
  30298. */
  30299. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30300. /**
  30301. * Texture data comes from an URL
  30302. */
  30303. InternalTexture.DATASOURCE_URL = 1;
  30304. /**
  30305. * Texture data is only used for temporary storage
  30306. */
  30307. InternalTexture.DATASOURCE_TEMP = 2;
  30308. /**
  30309. * Texture data comes from raw data (ArrayBuffer)
  30310. */
  30311. InternalTexture.DATASOURCE_RAW = 3;
  30312. /**
  30313. * Texture content is dynamic (video or dynamic texture)
  30314. */
  30315. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30316. /**
  30317. * Texture content is generated by rendering to it
  30318. */
  30319. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30320. /**
  30321. * Texture content is part of a multi render target process
  30322. */
  30323. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30324. /**
  30325. * Texture data comes from a cube data file
  30326. */
  30327. InternalTexture.DATASOURCE_CUBE = 7;
  30328. /**
  30329. * Texture data comes from a raw cube data
  30330. */
  30331. InternalTexture.DATASOURCE_CUBERAW = 8;
  30332. /**
  30333. * Texture data come from a prefiltered cube data file
  30334. */
  30335. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30336. /**
  30337. * Texture content is raw 3D data
  30338. */
  30339. InternalTexture.DATASOURCE_RAW3D = 10;
  30340. /**
  30341. * Texture content is a depth texture
  30342. */
  30343. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30344. return InternalTexture;
  30345. }());
  30346. BABYLON.InternalTexture = InternalTexture;
  30347. })(BABYLON || (BABYLON = {}));
  30348. //# sourceMappingURL=babylon.internalTexture.js.map
  30349. var BABYLON;
  30350. (function (BABYLON) {
  30351. var BaseTexture = /** @class */ (function () {
  30352. function BaseTexture(scene) {
  30353. this._hasAlpha = false;
  30354. this.getAlphaFromRGB = false;
  30355. this.level = 1;
  30356. this.coordinatesIndex = 0;
  30357. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30358. /**
  30359. * | Value | Type | Description |
  30360. * | ----- | ------------------ | ----------- |
  30361. * | 0 | CLAMP_ADDRESSMODE | |
  30362. * | 1 | WRAP_ADDRESSMODE | |
  30363. * | 2 | MIRROR_ADDRESSMODE | |
  30364. */
  30365. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30366. /**
  30367. * | Value | Type | Description |
  30368. * | ----- | ------------------ | ----------- |
  30369. * | 0 | CLAMP_ADDRESSMODE | |
  30370. * | 1 | WRAP_ADDRESSMODE | |
  30371. * | 2 | MIRROR_ADDRESSMODE | |
  30372. */
  30373. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30374. /**
  30375. * | Value | Type | Description |
  30376. * | ----- | ------------------ | ----------- |
  30377. * | 0 | CLAMP_ADDRESSMODE | |
  30378. * | 1 | WRAP_ADDRESSMODE | |
  30379. * | 2 | MIRROR_ADDRESSMODE | |
  30380. */
  30381. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30382. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30383. this.isCube = false;
  30384. this.is3D = false;
  30385. this.gammaSpace = true;
  30386. this.invertZ = false;
  30387. this.lodLevelInAlpha = false;
  30388. this.isRenderTarget = false;
  30389. this.animations = new Array();
  30390. /**
  30391. * An event triggered when the texture is disposed.
  30392. */
  30393. this.onDisposeObservable = new BABYLON.Observable();
  30394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30396. if (this._scene) {
  30397. this._scene.textures.push(this);
  30398. }
  30399. this._uid = null;
  30400. }
  30401. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30402. get: function () {
  30403. return this._hasAlpha;
  30404. },
  30405. set: function (value) {
  30406. if (this._hasAlpha === value) {
  30407. return;
  30408. }
  30409. this._hasAlpha = value;
  30410. if (this._scene) {
  30411. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30412. }
  30413. },
  30414. enumerable: true,
  30415. configurable: true
  30416. });
  30417. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30418. get: function () {
  30419. return this._coordinatesMode;
  30420. },
  30421. /**
  30422. * How a texture is mapped.
  30423. *
  30424. * | Value | Type | Description |
  30425. * | ----- | ----------------------------------- | ----------- |
  30426. * | 0 | EXPLICIT_MODE | |
  30427. * | 1 | SPHERICAL_MODE | |
  30428. * | 2 | PLANAR_MODE | |
  30429. * | 3 | CUBIC_MODE | |
  30430. * | 4 | PROJECTION_MODE | |
  30431. * | 5 | SKYBOX_MODE | |
  30432. * | 6 | INVCUBIC_MODE | |
  30433. * | 7 | EQUIRECTANGULAR_MODE | |
  30434. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30435. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30436. */
  30437. set: function (value) {
  30438. if (this._coordinatesMode === value) {
  30439. return;
  30440. }
  30441. this._coordinatesMode = value;
  30442. if (this._scene) {
  30443. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30444. }
  30445. },
  30446. enumerable: true,
  30447. configurable: true
  30448. });
  30449. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30450. /**
  30451. * Gets whether or not the texture contains RGBD data.
  30452. */
  30453. get: function () {
  30454. return this._texture != null && this._texture._isRGBD;
  30455. },
  30456. enumerable: true,
  30457. configurable: true
  30458. });
  30459. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30460. get: function () {
  30461. if (this._texture)
  30462. return this._texture._lodGenerationOffset;
  30463. return 0.0;
  30464. },
  30465. set: function (value) {
  30466. if (this._texture)
  30467. this._texture._lodGenerationOffset = value;
  30468. },
  30469. enumerable: true,
  30470. configurable: true
  30471. });
  30472. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30473. get: function () {
  30474. if (this._texture)
  30475. return this._texture._lodGenerationScale;
  30476. return 0.0;
  30477. },
  30478. set: function (value) {
  30479. if (this._texture)
  30480. this._texture._lodGenerationScale = value;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(BaseTexture.prototype, "uid", {
  30486. get: function () {
  30487. if (!this._uid) {
  30488. this._uid = BABYLON.Tools.RandomId();
  30489. }
  30490. return this._uid;
  30491. },
  30492. enumerable: true,
  30493. configurable: true
  30494. });
  30495. BaseTexture.prototype.toString = function () {
  30496. return this.name;
  30497. };
  30498. BaseTexture.prototype.getClassName = function () {
  30499. return "BaseTexture";
  30500. };
  30501. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30502. set: function (callback) {
  30503. if (this._onDisposeObserver) {
  30504. this.onDisposeObservable.remove(this._onDisposeObserver);
  30505. }
  30506. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30512. get: function () {
  30513. return true;
  30514. },
  30515. enumerable: true,
  30516. configurable: true
  30517. });
  30518. BaseTexture.prototype.getScene = function () {
  30519. return this._scene;
  30520. };
  30521. BaseTexture.prototype.getTextureMatrix = function () {
  30522. return BABYLON.Matrix.IdentityReadOnly;
  30523. };
  30524. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30525. return BABYLON.Matrix.IdentityReadOnly;
  30526. };
  30527. BaseTexture.prototype.getInternalTexture = function () {
  30528. return this._texture;
  30529. };
  30530. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30531. return !this.isBlocking || this.isReady();
  30532. };
  30533. BaseTexture.prototype.isReady = function () {
  30534. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30535. this.delayLoad();
  30536. return false;
  30537. }
  30538. if (this._texture) {
  30539. return this._texture.isReady;
  30540. }
  30541. return false;
  30542. };
  30543. BaseTexture.prototype.getSize = function () {
  30544. if (this._texture && this._texture.width) {
  30545. return new BABYLON.Size(this._texture.width, this._texture.height);
  30546. }
  30547. if (this._texture && this._texture._size) {
  30548. return new BABYLON.Size(this._texture._size, this._texture._size);
  30549. }
  30550. return BABYLON.Size.Zero();
  30551. };
  30552. BaseTexture.prototype.getBaseSize = function () {
  30553. if (!this.isReady() || !this._texture)
  30554. return BABYLON.Size.Zero();
  30555. if (this._texture._size) {
  30556. return new BABYLON.Size(this._texture._size, this._texture._size);
  30557. }
  30558. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30559. };
  30560. BaseTexture.prototype.scale = function (ratio) {
  30561. };
  30562. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30563. get: function () {
  30564. return false;
  30565. },
  30566. enumerable: true,
  30567. configurable: true
  30568. });
  30569. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30570. if (!this._scene) {
  30571. return null;
  30572. }
  30573. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30574. for (var index = 0; index < texturesCache.length; index++) {
  30575. var texturesCacheEntry = texturesCache[index];
  30576. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30577. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30578. texturesCacheEntry.incrementReferences();
  30579. return texturesCacheEntry;
  30580. }
  30581. }
  30582. }
  30583. return null;
  30584. };
  30585. BaseTexture.prototype._rebuild = function () {
  30586. };
  30587. BaseTexture.prototype.delayLoad = function () {
  30588. };
  30589. BaseTexture.prototype.clone = function () {
  30590. return null;
  30591. };
  30592. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30593. get: function () {
  30594. if (!this._texture) {
  30595. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30596. }
  30597. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30603. get: function () {
  30604. if (!this._texture) {
  30605. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30606. }
  30607. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. /**
  30613. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30614. * This will returns an RGBA array buffer containing either in values (0-255) or
  30615. * float values (0-1) depending of the underlying buffer type.
  30616. * @param faceIndex The face of the texture to read (in case of cube texture)
  30617. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30618. * @returns The Array buffer containing the pixels data.
  30619. */
  30620. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30621. if (faceIndex === void 0) { faceIndex = 0; }
  30622. if (level === void 0) { level = 0; }
  30623. if (!this._texture) {
  30624. return null;
  30625. }
  30626. var size = this.getSize();
  30627. var width = size.width;
  30628. var height = size.height;
  30629. var scene = this.getScene();
  30630. if (!scene) {
  30631. return null;
  30632. }
  30633. var engine = scene.getEngine();
  30634. if (level != 0) {
  30635. width = width / Math.pow(2, level);
  30636. height = height / Math.pow(2, level);
  30637. width = Math.round(width);
  30638. height = Math.round(height);
  30639. }
  30640. if (this._texture.isCube) {
  30641. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30642. }
  30643. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30644. };
  30645. BaseTexture.prototype.releaseInternalTexture = function () {
  30646. if (this._texture) {
  30647. this._texture.dispose();
  30648. this._texture = null;
  30649. }
  30650. };
  30651. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30652. get: function () {
  30653. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30654. return null;
  30655. }
  30656. if (!this._texture._sphericalPolynomial) {
  30657. this._texture._sphericalPolynomial =
  30658. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30659. }
  30660. return this._texture._sphericalPolynomial;
  30661. },
  30662. set: function (value) {
  30663. if (this._texture) {
  30664. this._texture._sphericalPolynomial = value;
  30665. }
  30666. },
  30667. enumerable: true,
  30668. configurable: true
  30669. });
  30670. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30671. get: function () {
  30672. if (this._texture) {
  30673. return this._texture._lodTextureHigh;
  30674. }
  30675. return null;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30681. get: function () {
  30682. if (this._texture) {
  30683. return this._texture._lodTextureMid;
  30684. }
  30685. return null;
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30691. get: function () {
  30692. if (this._texture) {
  30693. return this._texture._lodTextureLow;
  30694. }
  30695. return null;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. BaseTexture.prototype.dispose = function () {
  30701. if (!this._scene) {
  30702. return;
  30703. }
  30704. // Animations
  30705. this._scene.stopAnimation(this);
  30706. // Remove from scene
  30707. this._scene._removePendingData(this);
  30708. var index = this._scene.textures.indexOf(this);
  30709. if (index >= 0) {
  30710. this._scene.textures.splice(index, 1);
  30711. }
  30712. if (this._texture === undefined) {
  30713. return;
  30714. }
  30715. // Release
  30716. this.releaseInternalTexture();
  30717. // Callback
  30718. this.onDisposeObservable.notifyObservers(this);
  30719. this.onDisposeObservable.clear();
  30720. };
  30721. BaseTexture.prototype.serialize = function () {
  30722. if (!this.name) {
  30723. return null;
  30724. }
  30725. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30726. // Animations
  30727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30728. return serializationObject;
  30729. };
  30730. BaseTexture.WhenAllReady = function (textures, callback) {
  30731. var numRemaining = textures.length;
  30732. if (numRemaining === 0) {
  30733. callback();
  30734. return;
  30735. }
  30736. var _loop_1 = function () {
  30737. texture = textures[i];
  30738. if (texture.isReady()) {
  30739. if (--numRemaining === 0) {
  30740. callback();
  30741. }
  30742. }
  30743. else {
  30744. onLoadObservable = texture.onLoadObservable;
  30745. var onLoadCallback_1 = function () {
  30746. onLoadObservable.removeCallback(onLoadCallback_1);
  30747. if (--numRemaining === 0) {
  30748. callback();
  30749. }
  30750. };
  30751. onLoadObservable.add(onLoadCallback_1);
  30752. }
  30753. };
  30754. var texture, onLoadObservable;
  30755. for (var i = 0; i < textures.length; i++) {
  30756. _loop_1();
  30757. }
  30758. };
  30759. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30760. __decorate([
  30761. BABYLON.serialize()
  30762. ], BaseTexture.prototype, "name", void 0);
  30763. __decorate([
  30764. BABYLON.serialize("hasAlpha")
  30765. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30766. __decorate([
  30767. BABYLON.serialize()
  30768. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30769. __decorate([
  30770. BABYLON.serialize()
  30771. ], BaseTexture.prototype, "level", void 0);
  30772. __decorate([
  30773. BABYLON.serialize()
  30774. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30775. __decorate([
  30776. BABYLON.serialize("coordinatesMode")
  30777. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30778. __decorate([
  30779. BABYLON.serialize()
  30780. ], BaseTexture.prototype, "wrapU", void 0);
  30781. __decorate([
  30782. BABYLON.serialize()
  30783. ], BaseTexture.prototype, "wrapV", void 0);
  30784. __decorate([
  30785. BABYLON.serialize()
  30786. ], BaseTexture.prototype, "wrapR", void 0);
  30787. __decorate([
  30788. BABYLON.serialize()
  30789. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30790. __decorate([
  30791. BABYLON.serialize()
  30792. ], BaseTexture.prototype, "isCube", void 0);
  30793. __decorate([
  30794. BABYLON.serialize()
  30795. ], BaseTexture.prototype, "is3D", void 0);
  30796. __decorate([
  30797. BABYLON.serialize()
  30798. ], BaseTexture.prototype, "gammaSpace", void 0);
  30799. __decorate([
  30800. BABYLON.serialize()
  30801. ], BaseTexture.prototype, "invertZ", void 0);
  30802. __decorate([
  30803. BABYLON.serialize()
  30804. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30805. __decorate([
  30806. BABYLON.serialize()
  30807. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30808. __decorate([
  30809. BABYLON.serialize()
  30810. ], BaseTexture.prototype, "lodGenerationScale", null);
  30811. __decorate([
  30812. BABYLON.serialize()
  30813. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30814. return BaseTexture;
  30815. }());
  30816. BABYLON.BaseTexture = BaseTexture;
  30817. })(BABYLON || (BABYLON = {}));
  30818. //# sourceMappingURL=babylon.baseTexture.js.map
  30819. var BABYLON;
  30820. (function (BABYLON) {
  30821. var Texture = /** @class */ (function (_super) {
  30822. __extends(Texture, _super);
  30823. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30824. if (noMipmap === void 0) { noMipmap = false; }
  30825. if (invertY === void 0) { invertY = true; }
  30826. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30827. if (onLoad === void 0) { onLoad = null; }
  30828. if (onError === void 0) { onError = null; }
  30829. if (buffer === void 0) { buffer = null; }
  30830. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30831. var _this = _super.call(this, scene) || this;
  30832. _this.uOffset = 0;
  30833. _this.vOffset = 0;
  30834. _this.uScale = 1.0;
  30835. _this.vScale = 1.0;
  30836. _this.uAng = 0;
  30837. _this.vAng = 0;
  30838. _this.wAng = 0;
  30839. /**
  30840. * Defines the center of rotation (U)
  30841. */
  30842. _this.uRotationCenter = 0.5;
  30843. /**
  30844. * Defines the center of rotation (V)
  30845. */
  30846. _this.vRotationCenter = 0.5;
  30847. /**
  30848. * Defines the center of rotation (W)
  30849. */
  30850. _this.wRotationCenter = 0.5;
  30851. _this._isBlocking = true;
  30852. _this.name = url || "";
  30853. _this.url = url;
  30854. _this._noMipmap = noMipmap;
  30855. _this._invertY = invertY;
  30856. _this._samplingMode = samplingMode;
  30857. _this._buffer = buffer;
  30858. _this._deleteBuffer = deleteBuffer;
  30859. if (format) {
  30860. _this._format = format;
  30861. }
  30862. scene = _this.getScene();
  30863. if (!scene) {
  30864. return _this;
  30865. }
  30866. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30867. var load = function () {
  30868. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30869. _this.onLoadObservable.notifyObservers(_this);
  30870. }
  30871. if (onLoad) {
  30872. onLoad();
  30873. }
  30874. if (!_this.isBlocking && scene) {
  30875. scene.resetCachedMaterial();
  30876. }
  30877. };
  30878. if (!_this.url) {
  30879. _this._delayedOnLoad = load;
  30880. _this._delayedOnError = onError;
  30881. return _this;
  30882. }
  30883. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30884. if (!_this._texture) {
  30885. if (!scene.useDelayedTextureLoading) {
  30886. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30887. if (deleteBuffer) {
  30888. delete _this._buffer;
  30889. }
  30890. }
  30891. else {
  30892. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30893. _this._delayedOnLoad = load;
  30894. _this._delayedOnError = onError;
  30895. }
  30896. }
  30897. else {
  30898. if (_this._texture.isReady) {
  30899. BABYLON.Tools.SetImmediate(function () { return load(); });
  30900. }
  30901. else {
  30902. _this._texture.onLoadedObservable.add(load);
  30903. }
  30904. }
  30905. return _this;
  30906. }
  30907. Object.defineProperty(Texture.prototype, "noMipmap", {
  30908. get: function () {
  30909. return this._noMipmap;
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. Object.defineProperty(Texture.prototype, "isBlocking", {
  30915. get: function () {
  30916. return this._isBlocking;
  30917. },
  30918. set: function (value) {
  30919. this._isBlocking = value;
  30920. },
  30921. enumerable: true,
  30922. configurable: true
  30923. });
  30924. Object.defineProperty(Texture.prototype, "samplingMode", {
  30925. get: function () {
  30926. return this._samplingMode;
  30927. },
  30928. enumerable: true,
  30929. configurable: true
  30930. });
  30931. /**
  30932. * Update the url (and optional buffer) of this texture if url was null during construction.
  30933. * @param url the url of the texture
  30934. * @param buffer the buffer of the texture (defaults to null)
  30935. */
  30936. Texture.prototype.updateURL = function (url, buffer) {
  30937. if (buffer === void 0) { buffer = null; }
  30938. if (this.url) {
  30939. throw new Error("URL is already set");
  30940. }
  30941. this.url = url;
  30942. this._buffer = buffer;
  30943. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30944. this.delayLoad();
  30945. };
  30946. Texture.prototype.delayLoad = function () {
  30947. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30948. return;
  30949. }
  30950. var scene = this.getScene();
  30951. if (!scene) {
  30952. return;
  30953. }
  30954. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30955. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30956. if (!this._texture) {
  30957. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30958. if (this._deleteBuffer) {
  30959. delete this._buffer;
  30960. }
  30961. }
  30962. else {
  30963. if (this._delayedOnLoad) {
  30964. if (this._texture.isReady) {
  30965. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30966. }
  30967. else {
  30968. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30969. }
  30970. }
  30971. }
  30972. this._delayedOnLoad = null;
  30973. this._delayedOnError = null;
  30974. };
  30975. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30976. if (!this._texture) {
  30977. return;
  30978. }
  30979. var scene = this.getScene();
  30980. if (!scene) {
  30981. return;
  30982. }
  30983. this._samplingMode = samplingMode;
  30984. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30985. };
  30986. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30987. x *= this.uScale;
  30988. y *= this.vScale;
  30989. x -= this.uRotationCenter * this.uScale;
  30990. y -= this.vRotationCenter * this.vScale;
  30991. z -= this.wRotationCenter;
  30992. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30993. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30994. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30995. t.z += this.wRotationCenter;
  30996. };
  30997. Texture.prototype.getTextureMatrix = function () {
  30998. var _this = this;
  30999. if (this.uOffset === this._cachedUOffset &&
  31000. this.vOffset === this._cachedVOffset &&
  31001. this.uScale === this._cachedUScale &&
  31002. this.vScale === this._cachedVScale &&
  31003. this.uAng === this._cachedUAng &&
  31004. this.vAng === this._cachedVAng &&
  31005. this.wAng === this._cachedWAng) {
  31006. return this._cachedTextureMatrix;
  31007. }
  31008. this._cachedUOffset = this.uOffset;
  31009. this._cachedVOffset = this.vOffset;
  31010. this._cachedUScale = this.uScale;
  31011. this._cachedVScale = this.vScale;
  31012. this._cachedUAng = this.uAng;
  31013. this._cachedVAng = this.vAng;
  31014. this._cachedWAng = this.wAng;
  31015. if (!this._cachedTextureMatrix) {
  31016. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31017. this._rowGenerationMatrix = new BABYLON.Matrix();
  31018. this._t0 = BABYLON.Vector3.Zero();
  31019. this._t1 = BABYLON.Vector3.Zero();
  31020. this._t2 = BABYLON.Vector3.Zero();
  31021. }
  31022. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31023. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31024. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31025. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31026. this._t1.subtractInPlace(this._t0);
  31027. this._t2.subtractInPlace(this._t0);
  31028. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31029. this._cachedTextureMatrix.m[0] = this._t1.x;
  31030. this._cachedTextureMatrix.m[1] = this._t1.y;
  31031. this._cachedTextureMatrix.m[2] = this._t1.z;
  31032. this._cachedTextureMatrix.m[4] = this._t2.x;
  31033. this._cachedTextureMatrix.m[5] = this._t2.y;
  31034. this._cachedTextureMatrix.m[6] = this._t2.z;
  31035. this._cachedTextureMatrix.m[8] = this._t0.x;
  31036. this._cachedTextureMatrix.m[9] = this._t0.y;
  31037. this._cachedTextureMatrix.m[10] = this._t0.z;
  31038. var scene = this.getScene();
  31039. if (!scene) {
  31040. return this._cachedTextureMatrix;
  31041. }
  31042. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31043. return mat.hasTexture(_this);
  31044. });
  31045. return this._cachedTextureMatrix;
  31046. };
  31047. Texture.prototype.getReflectionTextureMatrix = function () {
  31048. var _this = this;
  31049. var scene = this.getScene();
  31050. if (!scene) {
  31051. return this._cachedTextureMatrix;
  31052. }
  31053. if (this.uOffset === this._cachedUOffset &&
  31054. this.vOffset === this._cachedVOffset &&
  31055. this.uScale === this._cachedUScale &&
  31056. this.vScale === this._cachedVScale &&
  31057. this.coordinatesMode === this._cachedCoordinatesMode) {
  31058. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31059. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31060. return this._cachedTextureMatrix;
  31061. }
  31062. }
  31063. else {
  31064. return this._cachedTextureMatrix;
  31065. }
  31066. }
  31067. if (!this._cachedTextureMatrix) {
  31068. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31069. }
  31070. if (!this._projectionModeMatrix) {
  31071. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31072. }
  31073. this._cachedUOffset = this.uOffset;
  31074. this._cachedVOffset = this.vOffset;
  31075. this._cachedUScale = this.uScale;
  31076. this._cachedVScale = this.vScale;
  31077. this._cachedCoordinatesMode = this.coordinatesMode;
  31078. switch (this.coordinatesMode) {
  31079. case Texture.PLANAR_MODE:
  31080. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31081. this._cachedTextureMatrix[0] = this.uScale;
  31082. this._cachedTextureMatrix[5] = this.vScale;
  31083. this._cachedTextureMatrix[12] = this.uOffset;
  31084. this._cachedTextureMatrix[13] = this.vOffset;
  31085. break;
  31086. case Texture.PROJECTION_MODE:
  31087. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31088. this._projectionModeMatrix.m[0] = 0.5;
  31089. this._projectionModeMatrix.m[5] = -0.5;
  31090. this._projectionModeMatrix.m[10] = 0.0;
  31091. this._projectionModeMatrix.m[12] = 0.5;
  31092. this._projectionModeMatrix.m[13] = 0.5;
  31093. this._projectionModeMatrix.m[14] = 1.0;
  31094. this._projectionModeMatrix.m[15] = 1.0;
  31095. var projectionMatrix = scene.getProjectionMatrix();
  31096. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31097. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31098. break;
  31099. default:
  31100. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31101. break;
  31102. }
  31103. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31104. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31105. });
  31106. return this._cachedTextureMatrix;
  31107. };
  31108. Texture.prototype.clone = function () {
  31109. var _this = this;
  31110. return BABYLON.SerializationHelper.Clone(function () {
  31111. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31112. }, this);
  31113. };
  31114. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31115. get: function () {
  31116. if (!this._onLoadObservable) {
  31117. this._onLoadObservable = new BABYLON.Observable();
  31118. }
  31119. return this._onLoadObservable;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Texture.prototype.serialize = function () {
  31125. var serializationObject = _super.prototype.serialize.call(this);
  31126. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31127. serializationObject.base64String = this._buffer;
  31128. serializationObject.name = serializationObject.name.replace("data:", "");
  31129. }
  31130. serializationObject.invertY = this._invertY;
  31131. serializationObject.samplingMode = this.samplingMode;
  31132. return serializationObject;
  31133. };
  31134. Texture.prototype.getClassName = function () {
  31135. return "Texture";
  31136. };
  31137. Texture.prototype.dispose = function () {
  31138. _super.prototype.dispose.call(this);
  31139. if (this.onLoadObservable) {
  31140. this.onLoadObservable.clear();
  31141. this._onLoadObservable = null;
  31142. }
  31143. this._delayedOnLoad = null;
  31144. this._delayedOnError = null;
  31145. };
  31146. // Statics
  31147. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31148. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31149. if (onLoad === void 0) { onLoad = null; }
  31150. if (onError === void 0) { onError = null; }
  31151. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31152. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31153. };
  31154. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31155. if (parsedTexture.customType) {
  31156. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31157. // Update Sampling Mode
  31158. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31159. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31160. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31161. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31162. }
  31163. }
  31164. return parsedCustomTexture;
  31165. }
  31166. if (parsedTexture.isCube) {
  31167. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31168. }
  31169. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31170. return null;
  31171. }
  31172. var texture = BABYLON.SerializationHelper.Parse(function () {
  31173. var generateMipMaps = true;
  31174. if (parsedTexture.noMipmap) {
  31175. generateMipMaps = false;
  31176. }
  31177. if (parsedTexture.mirrorPlane) {
  31178. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31179. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31180. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31181. return mirrorTexture;
  31182. }
  31183. else if (parsedTexture.isRenderTarget) {
  31184. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31185. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31186. return renderTargetTexture;
  31187. }
  31188. else {
  31189. var texture;
  31190. if (parsedTexture.base64String) {
  31191. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31192. }
  31193. else {
  31194. var url = rootUrl + parsedTexture.name;
  31195. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31196. url = parsedTexture.url;
  31197. }
  31198. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31199. }
  31200. return texture;
  31201. }
  31202. }, parsedTexture, scene);
  31203. // Update Sampling Mode
  31204. if (parsedTexture.samplingMode) {
  31205. var sampling = parsedTexture.samplingMode;
  31206. if (texture._samplingMode !== sampling) {
  31207. texture.updateSamplingMode(sampling);
  31208. }
  31209. }
  31210. // Animations
  31211. if (parsedTexture.animations) {
  31212. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31213. var parsedAnimation = parsedTexture.animations[animationIndex];
  31214. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31215. }
  31216. }
  31217. return texture;
  31218. };
  31219. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31220. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31221. if (noMipmap === void 0) { noMipmap = false; }
  31222. if (invertY === void 0) { invertY = true; }
  31223. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31224. if (onLoad === void 0) { onLoad = null; }
  31225. if (onError === void 0) { onError = null; }
  31226. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31227. if (name.substr(0, 5) !== "data:") {
  31228. name = "data:" + name;
  31229. }
  31230. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31231. };
  31232. // Constants
  31233. Texture.NEAREST_SAMPLINGMODE = 1;
  31234. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31235. Texture.BILINEAR_SAMPLINGMODE = 2;
  31236. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31237. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31238. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31239. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31240. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31241. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31242. Texture.NEAREST_LINEAR = 7;
  31243. Texture.NEAREST_NEAREST = 8;
  31244. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31245. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31246. Texture.LINEAR_LINEAR = 11;
  31247. Texture.LINEAR_NEAREST = 12;
  31248. Texture.EXPLICIT_MODE = 0;
  31249. Texture.SPHERICAL_MODE = 1;
  31250. Texture.PLANAR_MODE = 2;
  31251. Texture.CUBIC_MODE = 3;
  31252. Texture.PROJECTION_MODE = 4;
  31253. Texture.SKYBOX_MODE = 5;
  31254. Texture.INVCUBIC_MODE = 6;
  31255. Texture.EQUIRECTANGULAR_MODE = 7;
  31256. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31257. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31258. Texture.CLAMP_ADDRESSMODE = 0;
  31259. Texture.WRAP_ADDRESSMODE = 1;
  31260. Texture.MIRROR_ADDRESSMODE = 2;
  31261. /**
  31262. * 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
  31263. */
  31264. Texture.UseSerializedUrlIfAny = false;
  31265. __decorate([
  31266. BABYLON.serialize()
  31267. ], Texture.prototype, "url", void 0);
  31268. __decorate([
  31269. BABYLON.serialize()
  31270. ], Texture.prototype, "uOffset", void 0);
  31271. __decorate([
  31272. BABYLON.serialize()
  31273. ], Texture.prototype, "vOffset", void 0);
  31274. __decorate([
  31275. BABYLON.serialize()
  31276. ], Texture.prototype, "uScale", void 0);
  31277. __decorate([
  31278. BABYLON.serialize()
  31279. ], Texture.prototype, "vScale", void 0);
  31280. __decorate([
  31281. BABYLON.serialize()
  31282. ], Texture.prototype, "uAng", void 0);
  31283. __decorate([
  31284. BABYLON.serialize()
  31285. ], Texture.prototype, "vAng", void 0);
  31286. __decorate([
  31287. BABYLON.serialize()
  31288. ], Texture.prototype, "wAng", void 0);
  31289. __decorate([
  31290. BABYLON.serialize()
  31291. ], Texture.prototype, "uRotationCenter", void 0);
  31292. __decorate([
  31293. BABYLON.serialize()
  31294. ], Texture.prototype, "vRotationCenter", void 0);
  31295. __decorate([
  31296. BABYLON.serialize()
  31297. ], Texture.prototype, "wRotationCenter", void 0);
  31298. __decorate([
  31299. BABYLON.serialize()
  31300. ], Texture.prototype, "isBlocking", null);
  31301. return Texture;
  31302. }(BABYLON.BaseTexture));
  31303. BABYLON.Texture = Texture;
  31304. })(BABYLON || (BABYLON = {}));
  31305. //# sourceMappingURL=babylon.texture.js.map
  31306. var BABYLON;
  31307. (function (BABYLON) {
  31308. /**
  31309. * @hidden
  31310. **/
  31311. var _InstancesBatch = /** @class */ (function () {
  31312. function _InstancesBatch() {
  31313. this.mustReturn = false;
  31314. this.visibleInstances = new Array();
  31315. this.renderSelf = new Array();
  31316. }
  31317. return _InstancesBatch;
  31318. }());
  31319. BABYLON._InstancesBatch = _InstancesBatch;
  31320. var Mesh = /** @class */ (function (_super) {
  31321. __extends(Mesh, _super);
  31322. /**
  31323. * @constructor
  31324. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31325. * @param {Scene} scene The scene to add this mesh to.
  31326. * @param {Node} parent The parent of this mesh, if it has one
  31327. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31328. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31329. * When false, achieved by calling a clone(), also passing False.
  31330. * This will make creation of children, recursive.
  31331. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31332. */
  31333. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31334. if (scene === void 0) { scene = null; }
  31335. if (parent === void 0) { parent = null; }
  31336. if (source === void 0) { source = null; }
  31337. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31338. var _this = _super.call(this, name, scene) || this;
  31339. // Events
  31340. /**
  31341. * An event triggered before rendering the mesh
  31342. */
  31343. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31344. /**
  31345. * An event triggered after rendering the mesh
  31346. */
  31347. _this.onAfterRenderObservable = new BABYLON.Observable();
  31348. /**
  31349. * An event triggered before drawing the mesh
  31350. */
  31351. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31352. // Members
  31353. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31354. _this.instances = new Array();
  31355. _this._LODLevels = new Array();
  31356. _this._visibleInstances = {};
  31357. _this._renderIdForInstances = new Array();
  31358. _this._batchCache = new _InstancesBatch();
  31359. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31360. // Use by builder only to know what orientation were the mesh build in.
  31361. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31362. _this.overrideMaterialSideOrientation = null;
  31363. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31364. // Will be used to save a source mesh reference, If any
  31365. _this._source = null;
  31366. scene = _this.getScene();
  31367. if (source) {
  31368. // Geometry
  31369. if (source._geometry) {
  31370. source._geometry.applyToMesh(_this);
  31371. }
  31372. // Deep copy
  31373. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31374. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31375. // Source mesh
  31376. _this._source = source;
  31377. // Metadata
  31378. if (source.metadata && source.metadata.clone) {
  31379. _this.metadata = source.metadata.clone();
  31380. }
  31381. else {
  31382. _this.metadata = source.metadata;
  31383. }
  31384. // Tags
  31385. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31386. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31387. }
  31388. // Parent
  31389. _this.parent = source.parent;
  31390. // Pivot
  31391. _this.setPivotMatrix(source.getPivotMatrix());
  31392. _this.id = name + "." + source.id;
  31393. // Material
  31394. _this.material = source.material;
  31395. var index;
  31396. if (!doNotCloneChildren) {
  31397. // Children
  31398. var directDescendants = source.getDescendants(true);
  31399. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31400. var child = directDescendants[index_1];
  31401. if (child.clone) {
  31402. child.clone(name + "." + child.name, _this);
  31403. }
  31404. }
  31405. }
  31406. // Physics clone
  31407. var physicsEngine = _this.getScene().getPhysicsEngine();
  31408. if (clonePhysicsImpostor && physicsEngine) {
  31409. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31410. if (impostor) {
  31411. _this.physicsImpostor = impostor.clone(_this);
  31412. }
  31413. }
  31414. // Particles
  31415. for (index = 0; index < scene.particleSystems.length; index++) {
  31416. var system = scene.particleSystems[index];
  31417. if (system.emitter === source) {
  31418. system.clone(system.name, _this);
  31419. }
  31420. }
  31421. _this.computeWorldMatrix(true);
  31422. }
  31423. // Parent
  31424. if (parent !== null) {
  31425. _this.parent = parent;
  31426. }
  31427. return _this;
  31428. }
  31429. Object.defineProperty(Mesh, "FRONTSIDE", {
  31430. /**
  31431. * Mesh side orientation : usually the external or front surface
  31432. */
  31433. get: function () {
  31434. return Mesh._FRONTSIDE;
  31435. },
  31436. enumerable: true,
  31437. configurable: true
  31438. });
  31439. Object.defineProperty(Mesh, "BACKSIDE", {
  31440. /**
  31441. * Mesh side orientation : usually the internal or back surface
  31442. */
  31443. get: function () {
  31444. return Mesh._BACKSIDE;
  31445. },
  31446. enumerable: true,
  31447. configurable: true
  31448. });
  31449. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31450. /**
  31451. * Mesh side orientation : both internal and external or front and back surfaces
  31452. */
  31453. get: function () {
  31454. return Mesh._DOUBLESIDE;
  31455. },
  31456. enumerable: true,
  31457. configurable: true
  31458. });
  31459. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31460. /**
  31461. * Mesh side orientation : by default, `FRONTSIDE`
  31462. */
  31463. get: function () {
  31464. return Mesh._DEFAULTSIDE;
  31465. },
  31466. enumerable: true,
  31467. configurable: true
  31468. });
  31469. Object.defineProperty(Mesh, "NO_CAP", {
  31470. /**
  31471. * Mesh cap setting : no cap
  31472. */
  31473. get: function () {
  31474. return Mesh._NO_CAP;
  31475. },
  31476. enumerable: true,
  31477. configurable: true
  31478. });
  31479. Object.defineProperty(Mesh, "CAP_START", {
  31480. /**
  31481. * Mesh cap setting : one cap at the beginning of the mesh
  31482. */
  31483. get: function () {
  31484. return Mesh._CAP_START;
  31485. },
  31486. enumerable: true,
  31487. configurable: true
  31488. });
  31489. Object.defineProperty(Mesh, "CAP_END", {
  31490. /**
  31491. * Mesh cap setting : one cap at the end of the mesh
  31492. */
  31493. get: function () {
  31494. return Mesh._CAP_END;
  31495. },
  31496. enumerable: true,
  31497. configurable: true
  31498. });
  31499. Object.defineProperty(Mesh, "CAP_ALL", {
  31500. /**
  31501. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31502. */
  31503. get: function () {
  31504. return Mesh._CAP_ALL;
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31510. set: function (callback) {
  31511. if (this._onBeforeDrawObserver) {
  31512. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31513. }
  31514. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31520. get: function () {
  31521. return this._morphTargetManager;
  31522. },
  31523. set: function (value) {
  31524. if (this._morphTargetManager === value) {
  31525. return;
  31526. }
  31527. this._morphTargetManager = value;
  31528. this._syncGeometryWithMorphTargetManager();
  31529. },
  31530. enumerable: true,
  31531. configurable: true
  31532. });
  31533. Object.defineProperty(Mesh.prototype, "source", {
  31534. get: function () {
  31535. return this._source;
  31536. },
  31537. enumerable: true,
  31538. configurable: true
  31539. });
  31540. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31541. get: function () {
  31542. return this._unIndexed;
  31543. },
  31544. set: function (value) {
  31545. if (this._unIndexed !== value) {
  31546. this._unIndexed = value;
  31547. this._markSubMeshesAsAttributesDirty();
  31548. }
  31549. },
  31550. enumerable: true,
  31551. configurable: true
  31552. });
  31553. // Methods
  31554. /**
  31555. * Returns the string "Mesh".
  31556. */
  31557. Mesh.prototype.getClassName = function () {
  31558. return "Mesh";
  31559. };
  31560. /**
  31561. * Returns a string.
  31562. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31563. */
  31564. Mesh.prototype.toString = function (fullDetails) {
  31565. var ret = _super.prototype.toString.call(this, fullDetails);
  31566. ret += ", n vertices: " + this.getTotalVertices();
  31567. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31568. if (this.animations) {
  31569. for (var i = 0; i < this.animations.length; i++) {
  31570. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31571. }
  31572. }
  31573. if (fullDetails) {
  31574. if (this._geometry) {
  31575. var ib = this.getIndices();
  31576. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31577. if (vb && ib) {
  31578. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31579. }
  31580. }
  31581. else {
  31582. ret += ", flat shading: UNKNOWN";
  31583. }
  31584. }
  31585. return ret;
  31586. };
  31587. Mesh.prototype._unBindEffect = function () {
  31588. _super.prototype._unBindEffect.call(this);
  31589. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31590. var instance = _a[_i];
  31591. instance._unBindEffect();
  31592. }
  31593. };
  31594. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31595. /**
  31596. * True if the mesh has some Levels Of Details (LOD).
  31597. * Returns a boolean.
  31598. */
  31599. get: function () {
  31600. return this._LODLevels.length > 0;
  31601. },
  31602. enumerable: true,
  31603. configurable: true
  31604. });
  31605. /**
  31606. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31607. * @returns an array of {BABYLON.MeshLODLevel}
  31608. */
  31609. Mesh.prototype.getLODLevels = function () {
  31610. return this._LODLevels;
  31611. };
  31612. Mesh.prototype._sortLODLevels = function () {
  31613. this._LODLevels.sort(function (a, b) {
  31614. if (a.distance < b.distance) {
  31615. return 1;
  31616. }
  31617. if (a.distance > b.distance) {
  31618. return -1;
  31619. }
  31620. return 0;
  31621. });
  31622. };
  31623. /**
  31624. * Add a mesh as LOD level triggered at the given distance.
  31625. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31626. * @param distance The distance from the center of the object to show this level
  31627. * @param mesh The mesh to be added as LOD level (can be null)
  31628. * @return This mesh (for chaining)
  31629. */
  31630. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31631. if (mesh && mesh._masterMesh) {
  31632. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31633. return this;
  31634. }
  31635. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31636. this._LODLevels.push(level);
  31637. if (mesh) {
  31638. mesh._masterMesh = this;
  31639. }
  31640. this._sortLODLevels();
  31641. return this;
  31642. };
  31643. /**
  31644. * Returns the LOD level mesh at the passed distance or null if not found.
  31645. * It is related to the method `addLODLevel(distance, mesh)`.
  31646. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31647. * Returns an object Mesh or `null`.
  31648. */
  31649. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31650. for (var index = 0; index < this._LODLevels.length; index++) {
  31651. var level = this._LODLevels[index];
  31652. if (level.distance === distance) {
  31653. return level.mesh;
  31654. }
  31655. }
  31656. return null;
  31657. };
  31658. /**
  31659. * Remove a mesh from the LOD array
  31660. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31661. * @param {Mesh} mesh The mesh to be removed.
  31662. * @return {Mesh} This mesh (for chaining)
  31663. */
  31664. Mesh.prototype.removeLODLevel = function (mesh) {
  31665. for (var index = 0; index < this._LODLevels.length; index++) {
  31666. if (this._LODLevels[index].mesh === mesh) {
  31667. this._LODLevels.splice(index, 1);
  31668. if (mesh) {
  31669. mesh._masterMesh = null;
  31670. }
  31671. }
  31672. }
  31673. this._sortLODLevels();
  31674. return this;
  31675. };
  31676. /**
  31677. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31678. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31679. */
  31680. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31681. if (!this._LODLevels || this._LODLevels.length === 0) {
  31682. return this;
  31683. }
  31684. var bSphere;
  31685. if (boundingSphere) {
  31686. bSphere = boundingSphere;
  31687. }
  31688. else {
  31689. var boundingInfo = this.getBoundingInfo();
  31690. bSphere = boundingInfo.boundingSphere;
  31691. }
  31692. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31693. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31694. if (this.onLODLevelSelection) {
  31695. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31696. }
  31697. return this;
  31698. }
  31699. for (var index = 0; index < this._LODLevels.length; index++) {
  31700. var level = this._LODLevels[index];
  31701. if (level.distance < distanceToCamera) {
  31702. if (level.mesh) {
  31703. level.mesh._preActivate();
  31704. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31705. }
  31706. if (this.onLODLevelSelection) {
  31707. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31708. }
  31709. return level.mesh;
  31710. }
  31711. }
  31712. if (this.onLODLevelSelection) {
  31713. this.onLODLevelSelection(distanceToCamera, this, this);
  31714. }
  31715. return this;
  31716. };
  31717. Object.defineProperty(Mesh.prototype, "geometry", {
  31718. /**
  31719. * Returns the mesh internal Geometry object.
  31720. */
  31721. get: function () {
  31722. return this._geometry;
  31723. },
  31724. enumerable: true,
  31725. configurable: true
  31726. });
  31727. /**
  31728. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31729. */
  31730. Mesh.prototype.getTotalVertices = function () {
  31731. if (this._geometry === null || this._geometry === undefined) {
  31732. return 0;
  31733. }
  31734. return this._geometry.getTotalVertices();
  31735. };
  31736. /**
  31737. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31738. * 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.
  31739. * You can force the copy with forceCopy === true
  31740. * Returns null if the mesh has no geometry or no vertex buffer.
  31741. * Possible `kind` values :
  31742. * - BABYLON.VertexBuffer.PositionKind
  31743. * - BABYLON.VertexBuffer.UVKind
  31744. * - BABYLON.VertexBuffer.UV2Kind
  31745. * - BABYLON.VertexBuffer.UV3Kind
  31746. * - BABYLON.VertexBuffer.UV4Kind
  31747. * - BABYLON.VertexBuffer.UV5Kind
  31748. * - BABYLON.VertexBuffer.UV6Kind
  31749. * - BABYLON.VertexBuffer.ColorKind
  31750. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31751. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31752. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31753. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31754. */
  31755. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31756. if (!this._geometry) {
  31757. return null;
  31758. }
  31759. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31760. };
  31761. /**
  31762. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31763. * Returns `null` if the mesh has no geometry.
  31764. * Possible `kind` values :
  31765. * - BABYLON.VertexBuffer.PositionKind
  31766. * - BABYLON.VertexBuffer.UVKind
  31767. * - BABYLON.VertexBuffer.UV2Kind
  31768. * - BABYLON.VertexBuffer.UV3Kind
  31769. * - BABYLON.VertexBuffer.UV4Kind
  31770. * - BABYLON.VertexBuffer.UV5Kind
  31771. * - BABYLON.VertexBuffer.UV6Kind
  31772. * - BABYLON.VertexBuffer.ColorKind
  31773. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31774. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31775. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31776. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31777. */
  31778. Mesh.prototype.getVertexBuffer = function (kind) {
  31779. if (!this._geometry) {
  31780. return null;
  31781. }
  31782. return this._geometry.getVertexBuffer(kind);
  31783. };
  31784. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31785. if (!this._geometry) {
  31786. if (this._delayInfo) {
  31787. return this._delayInfo.indexOf(kind) !== -1;
  31788. }
  31789. return false;
  31790. }
  31791. return this._geometry.isVerticesDataPresent(kind);
  31792. };
  31793. /**
  31794. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31795. * Possible `kind` values :
  31796. * - BABYLON.VertexBuffer.PositionKind
  31797. * - BABYLON.VertexBuffer.UVKind
  31798. * - BABYLON.VertexBuffer.UV2Kind
  31799. * - BABYLON.VertexBuffer.UV3Kind
  31800. * - BABYLON.VertexBuffer.UV4Kind
  31801. * - BABYLON.VertexBuffer.UV5Kind
  31802. * - BABYLON.VertexBuffer.UV6Kind
  31803. * - BABYLON.VertexBuffer.ColorKind
  31804. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31805. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31806. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31807. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31808. */
  31809. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31810. if (!this._geometry) {
  31811. if (this._delayInfo) {
  31812. return this._delayInfo.indexOf(kind) !== -1;
  31813. }
  31814. return false;
  31815. }
  31816. return this._geometry.isVertexBufferUpdatable(kind);
  31817. };
  31818. /**
  31819. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31820. * Possible `kind` values :
  31821. * - BABYLON.VertexBuffer.PositionKind
  31822. * - BABYLON.VertexBuffer.UVKind
  31823. * - BABYLON.VertexBuffer.UV2Kind
  31824. * - BABYLON.VertexBuffer.UV3Kind
  31825. * - BABYLON.VertexBuffer.UV4Kind
  31826. * - BABYLON.VertexBuffer.UV5Kind
  31827. * - BABYLON.VertexBuffer.UV6Kind
  31828. * - BABYLON.VertexBuffer.ColorKind
  31829. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31830. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31831. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31832. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31833. */
  31834. Mesh.prototype.getVerticesDataKinds = function () {
  31835. if (!this._geometry) {
  31836. var result = new Array();
  31837. if (this._delayInfo) {
  31838. this._delayInfo.forEach(function (kind, index, array) {
  31839. result.push(kind);
  31840. });
  31841. }
  31842. return result;
  31843. }
  31844. return this._geometry.getVerticesDataKinds();
  31845. };
  31846. /**
  31847. * Returns a positive integer : the total number of indices in this mesh geometry.
  31848. * Returns zero if the mesh has no geometry.
  31849. */
  31850. Mesh.prototype.getTotalIndices = function () {
  31851. if (!this._geometry) {
  31852. return 0;
  31853. }
  31854. return this._geometry.getTotalIndices();
  31855. };
  31856. /**
  31857. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31858. * 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.
  31859. * Returns an empty array if the mesh has no geometry.
  31860. */
  31861. Mesh.prototype.getIndices = function (copyWhenShared) {
  31862. if (!this._geometry) {
  31863. return [];
  31864. }
  31865. return this._geometry.getIndices(copyWhenShared);
  31866. };
  31867. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31868. get: function () {
  31869. return this._masterMesh !== null && this._masterMesh !== undefined;
  31870. },
  31871. enumerable: true,
  31872. configurable: true
  31873. });
  31874. /**
  31875. * Determine if the current mesh is ready to be rendered
  31876. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31877. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31878. * @returns true if all associated assets are ready (material, textures, shaders)
  31879. */
  31880. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31881. if (completeCheck === void 0) { completeCheck = false; }
  31882. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31883. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31884. return false;
  31885. }
  31886. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31887. return false;
  31888. }
  31889. if (!this.subMeshes || this.subMeshes.length === 0) {
  31890. return true;
  31891. }
  31892. if (!completeCheck) {
  31893. return true;
  31894. }
  31895. var engine = this.getEngine();
  31896. var scene = this.getScene();
  31897. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31898. this.computeWorldMatrix();
  31899. var mat = this.material || scene.defaultMaterial;
  31900. if (mat) {
  31901. if (mat.storeEffectOnSubMeshes) {
  31902. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31903. var subMesh = _a[_i];
  31904. var effectiveMaterial = subMesh.getMaterial();
  31905. if (effectiveMaterial) {
  31906. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31907. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31908. return false;
  31909. }
  31910. }
  31911. else {
  31912. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31913. return false;
  31914. }
  31915. }
  31916. }
  31917. }
  31918. }
  31919. else {
  31920. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31921. return false;
  31922. }
  31923. }
  31924. }
  31925. // Shadows
  31926. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31927. var light = _c[_b];
  31928. var generator = light.getShadowGenerator();
  31929. if (generator) {
  31930. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31931. var subMesh = _e[_d];
  31932. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31933. return false;
  31934. }
  31935. }
  31936. }
  31937. }
  31938. // LOD
  31939. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31940. var lod = _g[_f];
  31941. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31942. return false;
  31943. }
  31944. }
  31945. return true;
  31946. };
  31947. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31948. /**
  31949. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31950. * This property is pertinent only for updatable parametric shapes.
  31951. */
  31952. get: function () {
  31953. return this._areNormalsFrozen;
  31954. },
  31955. enumerable: true,
  31956. configurable: true
  31957. });
  31958. /**
  31959. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31960. * It has no effect at all on other shapes.
  31961. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31962. * Returns the Mesh.
  31963. */
  31964. Mesh.prototype.freezeNormals = function () {
  31965. this._areNormalsFrozen = true;
  31966. return this;
  31967. };
  31968. /**
  31969. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31970. * It has no effect at all on other shapes.
  31971. * It reactivates the mesh normals computation if it was previously frozen.
  31972. * Returns the Mesh.
  31973. */
  31974. Mesh.prototype.unfreezeNormals = function () {
  31975. this._areNormalsFrozen = false;
  31976. return this;
  31977. };
  31978. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31979. /**
  31980. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31981. */
  31982. set: function (count) {
  31983. this._overridenInstanceCount = count;
  31984. },
  31985. enumerable: true,
  31986. configurable: true
  31987. });
  31988. // Methods
  31989. Mesh.prototype._preActivate = function () {
  31990. var sceneRenderId = this.getScene().getRenderId();
  31991. if (this._preActivateId === sceneRenderId) {
  31992. return this;
  31993. }
  31994. this._preActivateId = sceneRenderId;
  31995. this._visibleInstances = null;
  31996. return this;
  31997. };
  31998. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31999. if (this._visibleInstances) {
  32000. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32001. }
  32002. return this;
  32003. };
  32004. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32005. if (!this._visibleInstances) {
  32006. this._visibleInstances = {};
  32007. this._visibleInstances.defaultRenderId = renderId;
  32008. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32009. }
  32010. if (!this._visibleInstances[renderId]) {
  32011. this._visibleInstances[renderId] = new Array();
  32012. }
  32013. this._visibleInstances[renderId].push(instance);
  32014. return this;
  32015. };
  32016. /**
  32017. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32018. * This means the mesh underlying bounding box and sphere are recomputed.
  32019. * Returns the Mesh.
  32020. */
  32021. Mesh.prototype.refreshBoundingInfo = function () {
  32022. return this._refreshBoundingInfo(false);
  32023. };
  32024. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32025. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32026. return this;
  32027. }
  32028. var data = this._getPositionData(applySkeleton);
  32029. if (data) {
  32030. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32031. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32032. }
  32033. if (this.subMeshes) {
  32034. for (var index = 0; index < this.subMeshes.length; index++) {
  32035. this.subMeshes[index].refreshBoundingInfo();
  32036. }
  32037. }
  32038. this._updateBoundingInfo();
  32039. return this;
  32040. };
  32041. Mesh.prototype._getPositionData = function (applySkeleton) {
  32042. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32043. if (data && applySkeleton && this.skeleton) {
  32044. data = BABYLON.Tools.Slice(data);
  32045. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32046. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32047. if (matricesWeightsData && matricesIndicesData) {
  32048. var needExtras = this.numBoneInfluencers > 4;
  32049. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32050. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32051. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32052. var tempVector = BABYLON.Tmp.Vector3[0];
  32053. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32054. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32055. var matWeightIdx = 0;
  32056. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32057. finalMatrix.reset();
  32058. var inf;
  32059. var weight;
  32060. for (inf = 0; inf < 4; inf++) {
  32061. weight = matricesWeightsData[matWeightIdx + inf];
  32062. if (weight <= 0)
  32063. break;
  32064. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32065. finalMatrix.addToSelf(tempMatrix);
  32066. }
  32067. if (needExtras) {
  32068. for (inf = 0; inf < 4; inf++) {
  32069. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32070. if (weight <= 0)
  32071. break;
  32072. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32073. finalMatrix.addToSelf(tempMatrix);
  32074. }
  32075. }
  32076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32077. tempVector.toArray(data, index);
  32078. }
  32079. }
  32080. }
  32081. return data;
  32082. };
  32083. Mesh.prototype._createGlobalSubMesh = function (force) {
  32084. var totalVertices = this.getTotalVertices();
  32085. if (!totalVertices || !this.getIndices()) {
  32086. return null;
  32087. }
  32088. // Check if we need to recreate the submeshes
  32089. if (this.subMeshes && this.subMeshes.length > 0) {
  32090. var ib = this.getIndices();
  32091. if (!ib) {
  32092. return null;
  32093. }
  32094. var totalIndices = ib.length;
  32095. var needToRecreate = false;
  32096. if (force) {
  32097. needToRecreate = true;
  32098. }
  32099. else {
  32100. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32101. var submesh = _a[_i];
  32102. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32103. needToRecreate = true;
  32104. break;
  32105. }
  32106. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32107. needToRecreate = true;
  32108. break;
  32109. }
  32110. }
  32111. }
  32112. if (!needToRecreate) {
  32113. return this.subMeshes[0];
  32114. }
  32115. }
  32116. this.releaseSubMeshes();
  32117. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32118. };
  32119. Mesh.prototype.subdivide = function (count) {
  32120. if (count < 1) {
  32121. return;
  32122. }
  32123. var totalIndices = this.getTotalIndices();
  32124. var subdivisionSize = (totalIndices / count) | 0;
  32125. var offset = 0;
  32126. // Ensure that subdivisionSize is a multiple of 3
  32127. while (subdivisionSize % 3 !== 0) {
  32128. subdivisionSize++;
  32129. }
  32130. this.releaseSubMeshes();
  32131. for (var index = 0; index < count; index++) {
  32132. if (offset >= totalIndices) {
  32133. break;
  32134. }
  32135. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32136. offset += subdivisionSize;
  32137. }
  32138. this.synchronizeInstances();
  32139. };
  32140. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32141. if (updatable === void 0) { updatable = false; }
  32142. if (!this._geometry) {
  32143. var vertexData = new BABYLON.VertexData();
  32144. vertexData.set(data, kind);
  32145. var scene = this.getScene();
  32146. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32147. }
  32148. else {
  32149. this._geometry.setVerticesData(kind, data, updatable, stride);
  32150. }
  32151. return this;
  32152. };
  32153. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32154. if (updatable === void 0) { updatable = true; }
  32155. var vb = this.getVertexBuffer(kind);
  32156. if (!vb || vb.isUpdatable() === updatable) {
  32157. return;
  32158. }
  32159. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32160. };
  32161. /**
  32162. * Sets the mesh VertexBuffer.
  32163. * Returns the Mesh.
  32164. */
  32165. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32166. if (!this._geometry) {
  32167. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32168. }
  32169. this._geometry.setVerticesBuffer(buffer);
  32170. return this;
  32171. };
  32172. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32173. if (!this._geometry) {
  32174. return this;
  32175. }
  32176. if (!makeItUnique) {
  32177. this._geometry.updateVerticesData(kind, data, updateExtends);
  32178. }
  32179. else {
  32180. this.makeGeometryUnique();
  32181. this.updateVerticesData(kind, data, updateExtends, false);
  32182. }
  32183. return this;
  32184. };
  32185. /**
  32186. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32187. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32188. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32189. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32190. * Returns the Mesh.
  32191. */
  32192. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32193. if (computeNormals === void 0) { computeNormals = true; }
  32194. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32195. if (!positions) {
  32196. return this;
  32197. }
  32198. positionFunction(positions);
  32199. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32200. if (computeNormals) {
  32201. var indices = this.getIndices();
  32202. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32203. if (!normals) {
  32204. return this;
  32205. }
  32206. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32207. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32208. }
  32209. return this;
  32210. };
  32211. /**
  32212. * Creates a un-shared specific occurence of the geometry for the mesh.
  32213. * Returns the Mesh.
  32214. */
  32215. Mesh.prototype.makeGeometryUnique = function () {
  32216. if (!this._geometry) {
  32217. return this;
  32218. }
  32219. var oldGeometry = this._geometry;
  32220. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32221. oldGeometry.releaseForMesh(this, true);
  32222. geometry.applyToMesh(this);
  32223. return this;
  32224. };
  32225. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32226. if (totalVertices === void 0) { totalVertices = null; }
  32227. if (updatable === void 0) { updatable = false; }
  32228. if (!this._geometry) {
  32229. var vertexData = new BABYLON.VertexData();
  32230. vertexData.indices = indices;
  32231. var scene = this.getScene();
  32232. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32233. }
  32234. else {
  32235. this._geometry.setIndices(indices, totalVertices, updatable);
  32236. }
  32237. return this;
  32238. };
  32239. /**
  32240. * Update the current index buffer
  32241. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32242. * Returns the Mesh.
  32243. */
  32244. Mesh.prototype.updateIndices = function (indices, offset) {
  32245. if (!this._geometry) {
  32246. return this;
  32247. }
  32248. this._geometry.updateIndices(indices, offset);
  32249. return this;
  32250. };
  32251. /**
  32252. * Invert the geometry to move from a right handed system to a left handed one.
  32253. * Returns the Mesh.
  32254. */
  32255. Mesh.prototype.toLeftHanded = function () {
  32256. if (!this._geometry) {
  32257. return this;
  32258. }
  32259. this._geometry.toLeftHanded();
  32260. return this;
  32261. };
  32262. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32263. if (!this._geometry) {
  32264. return this;
  32265. }
  32266. var engine = this.getScene().getEngine();
  32267. // Wireframe
  32268. var indexToBind;
  32269. if (this._unIndexed) {
  32270. indexToBind = null;
  32271. }
  32272. else {
  32273. switch (fillMode) {
  32274. case BABYLON.Material.PointFillMode:
  32275. indexToBind = null;
  32276. break;
  32277. case BABYLON.Material.WireFrameFillMode:
  32278. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32279. break;
  32280. default:
  32281. case BABYLON.Material.TriangleFillMode:
  32282. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32283. break;
  32284. }
  32285. }
  32286. // VBOs
  32287. this._geometry._bind(effect, indexToBind);
  32288. return this;
  32289. };
  32290. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32291. if (alternate === void 0) { alternate = false; }
  32292. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32293. return this;
  32294. }
  32295. this.onBeforeDrawObservable.notifyObservers(this);
  32296. var scene = this.getScene();
  32297. var engine = scene.getEngine();
  32298. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32299. // or triangles as points
  32300. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32301. }
  32302. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32303. // Triangles as wireframe
  32304. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32305. }
  32306. else {
  32307. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32308. }
  32309. if (scene._isAlternateRenderingEnabled && !alternate) {
  32310. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32311. if (!effect || !scene.activeCamera) {
  32312. return this;
  32313. }
  32314. scene._switchToAlternateCameraConfiguration(true);
  32315. this._effectiveMaterial.bindView(effect);
  32316. this._effectiveMaterial.bindViewProjection(effect);
  32317. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32318. this._draw(subMesh, fillMode, instancesCount, true);
  32319. engine.setViewport(scene.activeCamera.viewport);
  32320. scene._switchToAlternateCameraConfiguration(false);
  32321. this._effectiveMaterial.bindView(effect);
  32322. this._effectiveMaterial.bindViewProjection(effect);
  32323. }
  32324. return this;
  32325. };
  32326. /**
  32327. * Registers for this mesh a javascript function called just before the rendering process.
  32328. * This function is passed the current mesh.
  32329. * Return the Mesh.
  32330. */
  32331. Mesh.prototype.registerBeforeRender = function (func) {
  32332. this.onBeforeRenderObservable.add(func);
  32333. return this;
  32334. };
  32335. /**
  32336. * Disposes a previously registered javascript function called before the rendering.
  32337. * This function is passed the current mesh.
  32338. * Returns the Mesh.
  32339. */
  32340. Mesh.prototype.unregisterBeforeRender = function (func) {
  32341. this.onBeforeRenderObservable.removeCallback(func);
  32342. return this;
  32343. };
  32344. /**
  32345. * Registers for this mesh a javascript function called just after the rendering is complete.
  32346. * This function is passed the current mesh.
  32347. * Returns the Mesh.
  32348. */
  32349. Mesh.prototype.registerAfterRender = function (func) {
  32350. this.onAfterRenderObservable.add(func);
  32351. return this;
  32352. };
  32353. /**
  32354. * Disposes a previously registered javascript function called after the rendering.
  32355. * This function is passed the current mesh.
  32356. * Return the Mesh.
  32357. */
  32358. Mesh.prototype.unregisterAfterRender = function (func) {
  32359. this.onAfterRenderObservable.removeCallback(func);
  32360. return this;
  32361. };
  32362. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32363. var scene = this.getScene();
  32364. this._batchCache.mustReturn = false;
  32365. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32366. this._batchCache.visibleInstances[subMeshId] = null;
  32367. if (this._visibleInstances) {
  32368. var currentRenderId = scene.getRenderId();
  32369. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32370. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32371. var selfRenderId = this._renderId;
  32372. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32373. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32374. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32375. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32376. }
  32377. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32378. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32379. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32380. this._batchCache.mustReturn = true;
  32381. return this._batchCache;
  32382. }
  32383. if (currentRenderId !== selfRenderId) {
  32384. this._batchCache.renderSelf[subMeshId] = false;
  32385. }
  32386. }
  32387. this._renderIdForInstances[subMeshId] = currentRenderId;
  32388. }
  32389. return this._batchCache;
  32390. };
  32391. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32392. var visibleInstances = batch.visibleInstances[subMesh._id];
  32393. if (!visibleInstances) {
  32394. return this;
  32395. }
  32396. var matricesCount = visibleInstances.length + 1;
  32397. var bufferSize = matricesCount * 16 * 4;
  32398. var currentInstancesBufferSize = this._instancesBufferSize;
  32399. var instancesBuffer = this._instancesBuffer;
  32400. while (this._instancesBufferSize < bufferSize) {
  32401. this._instancesBufferSize *= 2;
  32402. }
  32403. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32404. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32405. }
  32406. var offset = 0;
  32407. var instancesCount = 0;
  32408. var world = this.getWorldMatrix();
  32409. if (batch.renderSelf[subMesh._id]) {
  32410. world.copyToArray(this._instancesData, offset);
  32411. offset += 16;
  32412. instancesCount++;
  32413. }
  32414. if (visibleInstances) {
  32415. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32416. var instance = visibleInstances[instanceIndex];
  32417. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32418. offset += 16;
  32419. instancesCount++;
  32420. }
  32421. }
  32422. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32423. if (instancesBuffer) {
  32424. instancesBuffer.dispose();
  32425. }
  32426. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32427. this._instancesBuffer = instancesBuffer;
  32428. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32429. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32430. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32431. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32432. }
  32433. else {
  32434. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32435. }
  32436. this._bind(subMesh, effect, fillMode);
  32437. this._draw(subMesh, fillMode, instancesCount);
  32438. engine.unbindInstanceAttributes();
  32439. return this;
  32440. };
  32441. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32442. var scene = this.getScene();
  32443. var engine = scene.getEngine();
  32444. if (hardwareInstancedRendering) {
  32445. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32446. }
  32447. else {
  32448. if (batch.renderSelf[subMesh._id]) {
  32449. // Draw
  32450. if (onBeforeDraw) {
  32451. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32452. }
  32453. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32454. }
  32455. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32456. if (visibleInstancesForSubMesh) {
  32457. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32458. var instance = visibleInstancesForSubMesh[instanceIndex];
  32459. // World
  32460. var world = instance.getWorldMatrix();
  32461. if (onBeforeDraw) {
  32462. onBeforeDraw(true, world, effectiveMaterial);
  32463. }
  32464. // Draw
  32465. this._draw(subMesh, fillMode);
  32466. }
  32467. }
  32468. }
  32469. return this;
  32470. };
  32471. /**
  32472. * Triggers the draw call for the mesh.
  32473. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32474. * Returns the Mesh.
  32475. */
  32476. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32477. this._checkOcclusionQuery();
  32478. if (this._isOccluded) {
  32479. return this;
  32480. }
  32481. var scene = this.getScene();
  32482. // Managing instances
  32483. var batch = this._getInstancesRenderList(subMesh._id);
  32484. if (batch.mustReturn) {
  32485. return this;
  32486. }
  32487. // Checking geometry state
  32488. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32489. return this;
  32490. }
  32491. this.onBeforeRenderObservable.notifyObservers(this);
  32492. var engine = scene.getEngine();
  32493. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32494. // Material
  32495. var material = subMesh.getMaterial();
  32496. if (!material) {
  32497. return this;
  32498. }
  32499. this._effectiveMaterial = material;
  32500. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32501. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32502. return this;
  32503. }
  32504. }
  32505. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32506. return this;
  32507. }
  32508. // Alpha mode
  32509. if (enableAlphaMode) {
  32510. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32511. }
  32512. // Outline - step 1
  32513. var savedDepthWrite = engine.getDepthWrite();
  32514. if (this.renderOutline) {
  32515. engine.setDepthWrite(false);
  32516. scene.getOutlineRenderer().render(subMesh, batch);
  32517. engine.setDepthWrite(savedDepthWrite);
  32518. }
  32519. var effect;
  32520. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32521. effect = subMesh.effect;
  32522. }
  32523. else {
  32524. effect = this._effectiveMaterial.getEffect();
  32525. }
  32526. if (!effect) {
  32527. return this;
  32528. }
  32529. var sideOrientation = this.overrideMaterialSideOrientation;
  32530. if (sideOrientation == null) {
  32531. sideOrientation = this._effectiveMaterial.sideOrientation;
  32532. if (this._getWorldMatrixDeterminant() < 0) {
  32533. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32534. }
  32535. }
  32536. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32537. if (this._effectiveMaterial.forceDepthWrite) {
  32538. engine.setDepthWrite(true);
  32539. }
  32540. // Bind
  32541. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32542. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32543. this._bind(subMesh, effect, fillMode);
  32544. }
  32545. var world = this.getWorldMatrix();
  32546. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32547. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32548. }
  32549. else {
  32550. this._effectiveMaterial.bind(world, this);
  32551. }
  32552. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32553. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32554. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32555. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32556. }
  32557. // Draw
  32558. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32559. // Unbind
  32560. this._effectiveMaterial.unbind();
  32561. // Outline - step 2
  32562. if (this.renderOutline && savedDepthWrite) {
  32563. engine.setDepthWrite(true);
  32564. engine.setColorWrite(false);
  32565. scene.getOutlineRenderer().render(subMesh, batch);
  32566. engine.setColorWrite(true);
  32567. }
  32568. // Overlay
  32569. if (this.renderOverlay) {
  32570. var currentMode = engine.getAlphaMode();
  32571. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32572. scene.getOutlineRenderer().render(subMesh, batch, true);
  32573. engine.setAlphaMode(currentMode);
  32574. }
  32575. this.onAfterRenderObservable.notifyObservers(this);
  32576. return this;
  32577. };
  32578. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32579. if (isInstance && effectiveMaterial) {
  32580. effectiveMaterial.bindOnlyWorldMatrix(world);
  32581. }
  32582. };
  32583. /**
  32584. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32585. */
  32586. Mesh.prototype.getEmittedParticleSystems = function () {
  32587. var results = new Array();
  32588. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32589. var particleSystem = this.getScene().particleSystems[index];
  32590. if (particleSystem.emitter === this) {
  32591. results.push(particleSystem);
  32592. }
  32593. }
  32594. return results;
  32595. };
  32596. /**
  32597. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32598. */
  32599. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32600. var results = new Array();
  32601. var descendants = this.getDescendants();
  32602. descendants.push(this);
  32603. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32604. var particleSystem = this.getScene().particleSystems[index];
  32605. var emitter = particleSystem.emitter;
  32606. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32607. results.push(particleSystem);
  32608. }
  32609. }
  32610. return results;
  32611. };
  32612. /**
  32613. * Normalize matrix weights so that all vertices have a total weight set to 1
  32614. */
  32615. Mesh.prototype.cleanMatrixWeights = function () {
  32616. var epsilon = 1e-3;
  32617. var noInfluenceBoneIndex = 0.0;
  32618. if (this.skeleton) {
  32619. noInfluenceBoneIndex = this.skeleton.bones.length;
  32620. }
  32621. else {
  32622. return;
  32623. }
  32624. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32625. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32626. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32627. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32628. var influencers = this.numBoneInfluencers;
  32629. var size = matricesWeights.length;
  32630. for (var i = 0; i < size; i += 4) {
  32631. var weight = 0.0;
  32632. var firstZeroWeight = -1;
  32633. for (var j = 0; j < 4; j++) {
  32634. var w = matricesWeights[i + j];
  32635. weight += w;
  32636. if (w < epsilon && firstZeroWeight < 0) {
  32637. firstZeroWeight = j;
  32638. }
  32639. }
  32640. if (matricesWeightsExtra) {
  32641. for (var j = 0; j < 4; j++) {
  32642. var w = matricesWeightsExtra[i + j];
  32643. weight += w;
  32644. if (w < epsilon && firstZeroWeight < 0) {
  32645. firstZeroWeight = j + 4;
  32646. }
  32647. }
  32648. }
  32649. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32650. firstZeroWeight = influencers - 1;
  32651. }
  32652. if (weight > epsilon) {
  32653. var mweight = 1.0 / weight;
  32654. for (var j = 0; j < 4; j++) {
  32655. matricesWeights[i + j] *= mweight;
  32656. }
  32657. if (matricesWeightsExtra) {
  32658. for (var j = 0; j < 4; j++) {
  32659. matricesWeightsExtra[i + j] *= mweight;
  32660. }
  32661. }
  32662. }
  32663. else {
  32664. if (firstZeroWeight >= 4) {
  32665. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32666. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32667. }
  32668. else {
  32669. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32670. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32671. }
  32672. }
  32673. }
  32674. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32675. if (matricesIndicesExtra) {
  32676. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32677. }
  32678. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32679. if (matricesWeightsExtra) {
  32680. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32681. }
  32682. };
  32683. Mesh.prototype._checkDelayState = function () {
  32684. var scene = this.getScene();
  32685. if (this._geometry) {
  32686. this._geometry.load(scene);
  32687. }
  32688. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32690. this._queueLoad(scene);
  32691. }
  32692. return this;
  32693. };
  32694. Mesh.prototype._queueLoad = function (scene) {
  32695. var _this = this;
  32696. scene._addPendingData(this);
  32697. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32698. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32699. if (data instanceof ArrayBuffer) {
  32700. _this._delayLoadingFunction(data, _this);
  32701. }
  32702. else {
  32703. _this._delayLoadingFunction(JSON.parse(data), _this);
  32704. }
  32705. _this.instances.forEach(function (instance) {
  32706. instance._syncSubMeshes();
  32707. });
  32708. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32709. scene._removePendingData(_this);
  32710. }, function () { }, scene.database, getBinaryData);
  32711. return this;
  32712. };
  32713. /**
  32714. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32715. */
  32716. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32717. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32718. return false;
  32719. }
  32720. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32721. return false;
  32722. }
  32723. this._checkDelayState();
  32724. return true;
  32725. };
  32726. /**
  32727. * Sets the mesh material by the material or multiMaterial `id` property.
  32728. * The material `id` is a string identifying the material or the multiMaterial.
  32729. * This method returns the Mesh.
  32730. */
  32731. Mesh.prototype.setMaterialByID = function (id) {
  32732. var materials = this.getScene().materials;
  32733. var index;
  32734. for (index = materials.length - 1; index > -1; index--) {
  32735. if (materials[index].id === id) {
  32736. this.material = materials[index];
  32737. return this;
  32738. }
  32739. }
  32740. // Multi
  32741. var multiMaterials = this.getScene().multiMaterials;
  32742. for (index = multiMaterials.length - 1; index > -1; index--) {
  32743. if (multiMaterials[index].id === id) {
  32744. this.material = multiMaterials[index];
  32745. return this;
  32746. }
  32747. }
  32748. return this;
  32749. };
  32750. /**
  32751. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32752. */
  32753. Mesh.prototype.getAnimatables = function () {
  32754. var results = new Array();
  32755. if (this.material) {
  32756. results.push(this.material);
  32757. }
  32758. if (this.skeleton) {
  32759. results.push(this.skeleton);
  32760. }
  32761. return results;
  32762. };
  32763. /**
  32764. * Modifies the mesh geometry according to the passed transformation matrix.
  32765. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32766. * The mesh normals are modified accordingly the same transformation.
  32767. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32768. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32769. * Returns the Mesh.
  32770. */
  32771. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32772. // Position
  32773. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32774. return this;
  32775. }
  32776. var submeshes = this.subMeshes.splice(0);
  32777. this._resetPointsArrayCache();
  32778. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32779. var temp = new Array();
  32780. var index;
  32781. for (index = 0; index < data.length; index += 3) {
  32782. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32783. }
  32784. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32785. // Normals
  32786. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32787. return this;
  32788. }
  32789. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32790. temp = [];
  32791. for (index = 0; index < data.length; index += 3) {
  32792. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32793. }
  32794. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32795. // flip faces?
  32796. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32797. this.flipFaces();
  32798. }
  32799. // Restore submeshes
  32800. this.releaseSubMeshes();
  32801. this.subMeshes = submeshes;
  32802. return this;
  32803. };
  32804. /**
  32805. * Modifies the mesh geometry according to its own current World Matrix.
  32806. * The mesh World Matrix is then reset.
  32807. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32808. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32809. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32810. * Returns the Mesh.
  32811. */
  32812. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32813. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32814. this.scaling.copyFromFloats(1, 1, 1);
  32815. this.position.copyFromFloats(0, 0, 0);
  32816. this.rotation.copyFromFloats(0, 0, 0);
  32817. //only if quaternion is already set
  32818. if (this.rotationQuaternion) {
  32819. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32820. }
  32821. this._worldMatrix = BABYLON.Matrix.Identity();
  32822. return this;
  32823. };
  32824. Object.defineProperty(Mesh.prototype, "_positions", {
  32825. // Cache
  32826. get: function () {
  32827. if (this._geometry) {
  32828. return this._geometry._positions;
  32829. }
  32830. return null;
  32831. },
  32832. enumerable: true,
  32833. configurable: true
  32834. });
  32835. Mesh.prototype._resetPointsArrayCache = function () {
  32836. if (this._geometry) {
  32837. this._geometry._resetPointsArrayCache();
  32838. }
  32839. return this;
  32840. };
  32841. Mesh.prototype._generatePointsArray = function () {
  32842. if (this._geometry) {
  32843. return this._geometry._generatePointsArray();
  32844. }
  32845. return false;
  32846. };
  32847. /**
  32848. * Returns a new Mesh object generated from the current mesh properties.
  32849. * This method must not get confused with createInstance().
  32850. * The parameter `name` is a string, the name given to the new mesh.
  32851. * The optional parameter `newParent` can be any Node object (default `null`).
  32852. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32853. * 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.
  32854. */
  32855. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32856. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32857. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32858. };
  32859. /**
  32860. * Releases resources associated with this mesh.
  32861. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32862. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32863. */
  32864. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32865. var _this = this;
  32866. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32867. this.morphTargetManager = null;
  32868. if (this._geometry) {
  32869. this._geometry.releaseForMesh(this, true);
  32870. }
  32871. // Sources
  32872. var meshes = this.getScene().meshes;
  32873. meshes.forEach(function (abstractMesh) {
  32874. var mesh = abstractMesh;
  32875. if (mesh._source && mesh._source === _this) {
  32876. mesh._source = null;
  32877. }
  32878. });
  32879. this._source = null;
  32880. // Instances
  32881. if (this._instancesBuffer) {
  32882. this._instancesBuffer.dispose();
  32883. this._instancesBuffer = null;
  32884. }
  32885. while (this.instances.length) {
  32886. this.instances[0].dispose();
  32887. }
  32888. // Effect layers.
  32889. var effectLayers = this.getScene().effectLayers;
  32890. for (var i = 0; i < effectLayers.length; i++) {
  32891. var effectLayer = effectLayers[i];
  32892. if (effectLayer) {
  32893. effectLayer._disposeMesh(this);
  32894. }
  32895. }
  32896. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32897. };
  32898. /**
  32899. * Modifies the mesh geometry according to a displacement map.
  32900. * 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.
  32901. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32902. * This method returns nothing.
  32903. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32904. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32905. * 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.
  32906. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32907. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32908. *
  32909. * Returns the Mesh.
  32910. */
  32911. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32912. var _this = this;
  32913. var scene = this.getScene();
  32914. var onload = function (img) {
  32915. // Getting height map data
  32916. var canvas = document.createElement("canvas");
  32917. var context = canvas.getContext("2d");
  32918. var heightMapWidth = img.width;
  32919. var heightMapHeight = img.height;
  32920. canvas.width = heightMapWidth;
  32921. canvas.height = heightMapHeight;
  32922. context.drawImage(img, 0, 0);
  32923. // Create VertexData from map data
  32924. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32925. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32926. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32927. //execute success callback, if set
  32928. if (onSuccess) {
  32929. onSuccess(_this);
  32930. }
  32931. };
  32932. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32933. return this;
  32934. };
  32935. /**
  32936. * Modifies the mesh geometry according to a displacementMap buffer.
  32937. * 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.
  32938. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32939. * This method returns nothing.
  32940. * 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.
  32941. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32942. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32943. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32944. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32945. *
  32946. * Returns the Mesh.
  32947. */
  32948. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32950. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32951. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32952. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32953. return this;
  32954. }
  32955. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32956. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32957. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32958. var position = BABYLON.Vector3.Zero();
  32959. var normal = BABYLON.Vector3.Zero();
  32960. var uv = BABYLON.Vector2.Zero();
  32961. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32962. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32963. for (var index = 0; index < positions.length; index += 3) {
  32964. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32965. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32966. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32967. // Compute height
  32968. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32969. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32970. var pos = (u + v * heightMapWidth) * 4;
  32971. var r = buffer[pos] / 255.0;
  32972. var g = buffer[pos + 1] / 255.0;
  32973. var b = buffer[pos + 2] / 255.0;
  32974. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32975. normal.normalize();
  32976. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32977. position = position.add(normal);
  32978. position.toArray(positions, index);
  32979. }
  32980. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32981. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32982. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32983. return this;
  32984. };
  32985. /**
  32986. * Modify the mesh to get a flat shading rendering.
  32987. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32988. * This method returns the Mesh.
  32989. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32990. */
  32991. Mesh.prototype.convertToFlatShadedMesh = function () {
  32992. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32993. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32994. var kinds = this.getVerticesDataKinds();
  32995. var vbs = {};
  32996. var data = {};
  32997. var newdata = {};
  32998. var updatableNormals = false;
  32999. var kindIndex;
  33000. var kind;
  33001. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33002. kind = kinds[kindIndex];
  33003. var vertexBuffer = this.getVertexBuffer(kind);
  33004. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33005. updatableNormals = vertexBuffer.isUpdatable();
  33006. kinds.splice(kindIndex, 1);
  33007. kindIndex--;
  33008. continue;
  33009. }
  33010. vbs[kind] = vertexBuffer;
  33011. data[kind] = vbs[kind].getData();
  33012. newdata[kind] = [];
  33013. }
  33014. // Save previous submeshes
  33015. var previousSubmeshes = this.subMeshes.slice(0);
  33016. var indices = this.getIndices();
  33017. var totalIndices = this.getTotalIndices();
  33018. // Generating unique vertices per face
  33019. var index;
  33020. for (index = 0; index < totalIndices; index++) {
  33021. var vertexIndex = indices[index];
  33022. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33023. kind = kinds[kindIndex];
  33024. var stride = vbs[kind].getStrideSize();
  33025. for (var offset = 0; offset < stride; offset++) {
  33026. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33027. }
  33028. }
  33029. }
  33030. // Updating faces & normal
  33031. var normals = [];
  33032. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33033. for (index = 0; index < totalIndices; index += 3) {
  33034. indices[index] = index;
  33035. indices[index + 1] = index + 1;
  33036. indices[index + 2] = index + 2;
  33037. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33038. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33039. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33040. var p1p2 = p1.subtract(p2);
  33041. var p3p2 = p3.subtract(p2);
  33042. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33043. // Store same normals for every vertex
  33044. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33045. normals.push(normal.x);
  33046. normals.push(normal.y);
  33047. normals.push(normal.z);
  33048. }
  33049. }
  33050. this.setIndices(indices);
  33051. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33052. // Updating vertex buffers
  33053. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33054. kind = kinds[kindIndex];
  33055. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33056. }
  33057. // Updating submeshes
  33058. this.releaseSubMeshes();
  33059. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33060. var previousOne = previousSubmeshes[submeshIndex];
  33061. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33062. }
  33063. this.synchronizeInstances();
  33064. return this;
  33065. };
  33066. /**
  33067. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33068. * In other words, more vertices, no more indices and a single bigger VBO.
  33069. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33070. * Returns the Mesh.
  33071. */
  33072. Mesh.prototype.convertToUnIndexedMesh = function () {
  33073. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33074. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33075. var kinds = this.getVerticesDataKinds();
  33076. var vbs = {};
  33077. var data = {};
  33078. var newdata = {};
  33079. var kindIndex;
  33080. var kind;
  33081. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33082. kind = kinds[kindIndex];
  33083. var vertexBuffer = this.getVertexBuffer(kind);
  33084. vbs[kind] = vertexBuffer;
  33085. data[kind] = vbs[kind].getData();
  33086. newdata[kind] = [];
  33087. }
  33088. // Save previous submeshes
  33089. var previousSubmeshes = this.subMeshes.slice(0);
  33090. var indices = this.getIndices();
  33091. var totalIndices = this.getTotalIndices();
  33092. // Generating unique vertices per face
  33093. var index;
  33094. for (index = 0; index < totalIndices; index++) {
  33095. var vertexIndex = indices[index];
  33096. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33097. kind = kinds[kindIndex];
  33098. var stride = vbs[kind].getStrideSize();
  33099. for (var offset = 0; offset < stride; offset++) {
  33100. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33101. }
  33102. }
  33103. }
  33104. // Updating indices
  33105. for (index = 0; index < totalIndices; index += 3) {
  33106. indices[index] = index;
  33107. indices[index + 1] = index + 1;
  33108. indices[index + 2] = index + 2;
  33109. }
  33110. this.setIndices(indices);
  33111. // Updating vertex buffers
  33112. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33113. kind = kinds[kindIndex];
  33114. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33115. }
  33116. // Updating submeshes
  33117. this.releaseSubMeshes();
  33118. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33119. var previousOne = previousSubmeshes[submeshIndex];
  33120. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33121. }
  33122. this._unIndexed = true;
  33123. this.synchronizeInstances();
  33124. return this;
  33125. };
  33126. /**
  33127. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33128. * This method returns the Mesh.
  33129. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33130. */
  33131. Mesh.prototype.flipFaces = function (flipNormals) {
  33132. if (flipNormals === void 0) { flipNormals = false; }
  33133. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33134. var i;
  33135. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33136. for (i = 0; i < vertex_data.normals.length; i++) {
  33137. vertex_data.normals[i] *= -1;
  33138. }
  33139. }
  33140. if (vertex_data.indices) {
  33141. var temp;
  33142. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33143. // reassign indices
  33144. temp = vertex_data.indices[i + 1];
  33145. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33146. vertex_data.indices[i + 2] = temp;
  33147. }
  33148. }
  33149. vertex_data.applyToMesh(this);
  33150. return this;
  33151. };
  33152. // Instances
  33153. /**
  33154. * Creates a new InstancedMesh object from the mesh model.
  33155. * An instance shares the same properties and the same material than its model.
  33156. * Only these properties of each instance can then be set individually :
  33157. * - position
  33158. * - rotation
  33159. * - rotationQuaternion
  33160. * - setPivotMatrix
  33161. * - scaling
  33162. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33163. * Warning : this method is not supported for Line mesh and LineSystem
  33164. */
  33165. Mesh.prototype.createInstance = function (name) {
  33166. return new BABYLON.InstancedMesh(name, this);
  33167. };
  33168. /**
  33169. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33170. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33171. * This method returns the Mesh.
  33172. */
  33173. Mesh.prototype.synchronizeInstances = function () {
  33174. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33175. var instance = this.instances[instanceIndex];
  33176. instance._syncSubMeshes();
  33177. }
  33178. return this;
  33179. };
  33180. /**
  33181. * Simplify the mesh according to the given array of settings.
  33182. * Function will return immediately and will simplify async. It returns the Mesh.
  33183. * @param settings a collection of simplification settings.
  33184. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33185. * @param type the type of simplification to run.
  33186. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33187. */
  33188. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33189. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33190. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33191. this.getScene().simplificationQueue.addTask({
  33192. settings: settings,
  33193. parallelProcessing: parallelProcessing,
  33194. mesh: this,
  33195. simplificationType: simplificationType,
  33196. successCallback: successCallback
  33197. });
  33198. return this;
  33199. };
  33200. /**
  33201. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33202. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33203. * This should be used together with the simplification to avoid disappearing triangles.
  33204. * Returns the Mesh.
  33205. * @param successCallback an optional success callback to be called after the optimization finished.
  33206. */
  33207. Mesh.prototype.optimizeIndices = function (successCallback) {
  33208. var _this = this;
  33209. var indices = this.getIndices();
  33210. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33211. if (!positions || !indices) {
  33212. return this;
  33213. }
  33214. var vectorPositions = new Array();
  33215. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33216. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33217. }
  33218. var dupes = new Array();
  33219. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33220. var realPos = vectorPositions.length - 1 - iteration;
  33221. var testedPosition = vectorPositions[realPos];
  33222. for (var j = 0; j < realPos; ++j) {
  33223. var againstPosition = vectorPositions[j];
  33224. if (testedPosition.equals(againstPosition)) {
  33225. dupes[realPos] = j;
  33226. break;
  33227. }
  33228. }
  33229. }, function () {
  33230. for (var i = 0; i < indices.length; ++i) {
  33231. indices[i] = dupes[indices[i]] || indices[i];
  33232. }
  33233. //indices are now reordered
  33234. var originalSubMeshes = _this.subMeshes.slice(0);
  33235. _this.setIndices(indices);
  33236. _this.subMeshes = originalSubMeshes;
  33237. if (successCallback) {
  33238. successCallback(_this);
  33239. }
  33240. });
  33241. return this;
  33242. };
  33243. Mesh.prototype.serialize = function (serializationObject) {
  33244. serializationObject.name = this.name;
  33245. serializationObject.id = this.id;
  33246. serializationObject.type = this.getClassName();
  33247. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33248. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33249. }
  33250. serializationObject.position = this.position.asArray();
  33251. if (this.rotationQuaternion) {
  33252. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33253. }
  33254. else if (this.rotation) {
  33255. serializationObject.rotation = this.rotation.asArray();
  33256. }
  33257. serializationObject.scaling = this.scaling.asArray();
  33258. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33259. serializationObject.isEnabled = this.isEnabled(false);
  33260. serializationObject.isVisible = this.isVisible;
  33261. serializationObject.infiniteDistance = this.infiniteDistance;
  33262. serializationObject.pickable = this.isPickable;
  33263. serializationObject.receiveShadows = this.receiveShadows;
  33264. serializationObject.billboardMode = this.billboardMode;
  33265. serializationObject.visibility = this.visibility;
  33266. serializationObject.checkCollisions = this.checkCollisions;
  33267. serializationObject.isBlocker = this.isBlocker;
  33268. // Parent
  33269. if (this.parent) {
  33270. serializationObject.parentId = this.parent.id;
  33271. }
  33272. // Geometry
  33273. serializationObject.isUnIndexed = this.isUnIndexed;
  33274. var geometry = this._geometry;
  33275. if (geometry) {
  33276. var geometryId = geometry.id;
  33277. serializationObject.geometryId = geometryId;
  33278. // SubMeshes
  33279. serializationObject.subMeshes = [];
  33280. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33281. var subMesh = this.subMeshes[subIndex];
  33282. serializationObject.subMeshes.push({
  33283. materialIndex: subMesh.materialIndex,
  33284. verticesStart: subMesh.verticesStart,
  33285. verticesCount: subMesh.verticesCount,
  33286. indexStart: subMesh.indexStart,
  33287. indexCount: subMesh.indexCount
  33288. });
  33289. }
  33290. }
  33291. // Material
  33292. if (this.material) {
  33293. serializationObject.materialId = this.material.id;
  33294. }
  33295. else {
  33296. this.material = null;
  33297. }
  33298. // Morph targets
  33299. if (this.morphTargetManager) {
  33300. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33301. }
  33302. // Skeleton
  33303. if (this.skeleton) {
  33304. serializationObject.skeletonId = this.skeleton.id;
  33305. }
  33306. // Physics
  33307. //TODO implement correct serialization for physics impostors.
  33308. var impostor = this.getPhysicsImpostor();
  33309. if (impostor) {
  33310. serializationObject.physicsMass = impostor.getParam("mass");
  33311. serializationObject.physicsFriction = impostor.getParam("friction");
  33312. serializationObject.physicsRestitution = impostor.getParam("mass");
  33313. serializationObject.physicsImpostor = impostor.type;
  33314. }
  33315. // Metadata
  33316. if (this.metadata) {
  33317. serializationObject.metadata = this.metadata;
  33318. }
  33319. // Instances
  33320. serializationObject.instances = [];
  33321. for (var index = 0; index < this.instances.length; index++) {
  33322. var instance = this.instances[index];
  33323. var serializationInstance = {
  33324. name: instance.name,
  33325. id: instance.id,
  33326. position: instance.position.asArray(),
  33327. scaling: instance.scaling.asArray()
  33328. };
  33329. if (instance.rotationQuaternion) {
  33330. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33331. }
  33332. else if (instance.rotation) {
  33333. serializationInstance.rotation = instance.rotation.asArray();
  33334. }
  33335. serializationObject.instances.push(serializationInstance);
  33336. // Animations
  33337. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33338. serializationInstance.ranges = instance.serializeAnimationRanges();
  33339. }
  33340. //
  33341. // Animations
  33342. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33343. serializationObject.ranges = this.serializeAnimationRanges();
  33344. // Layer mask
  33345. serializationObject.layerMask = this.layerMask;
  33346. // Alpha
  33347. serializationObject.alphaIndex = this.alphaIndex;
  33348. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33349. // Overlay
  33350. serializationObject.overlayAlpha = this.overlayAlpha;
  33351. serializationObject.overlayColor = this.overlayColor.asArray();
  33352. serializationObject.renderOverlay = this.renderOverlay;
  33353. // Fog
  33354. serializationObject.applyFog = this.applyFog;
  33355. // Action Manager
  33356. if (this.actionManager) {
  33357. serializationObject.actions = this.actionManager.serialize(this.name);
  33358. }
  33359. };
  33360. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33361. if (!this.geometry) {
  33362. return;
  33363. }
  33364. this._markSubMeshesAsAttributesDirty();
  33365. var morphTargetManager = this._morphTargetManager;
  33366. if (morphTargetManager && morphTargetManager.vertexCount) {
  33367. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33368. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33369. this.morphTargetManager = null;
  33370. return;
  33371. }
  33372. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33373. var morphTarget = morphTargetManager.getActiveTarget(index);
  33374. var positions = morphTarget.getPositions();
  33375. if (!positions) {
  33376. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33377. return;
  33378. }
  33379. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33380. var normals = morphTarget.getNormals();
  33381. if (normals) {
  33382. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33383. }
  33384. var tangents = morphTarget.getTangents();
  33385. if (tangents) {
  33386. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33387. }
  33388. }
  33389. }
  33390. else {
  33391. var index = 0;
  33392. // Positions
  33393. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33394. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33395. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33396. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33397. }
  33398. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33399. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33400. }
  33401. index++;
  33402. }
  33403. }
  33404. };
  33405. // Statics
  33406. /**
  33407. * Returns a new Mesh object parsed from the source provided.
  33408. * The parameter `parsedMesh` is the source.
  33409. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33410. */
  33411. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33412. var mesh;
  33413. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33414. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33415. }
  33416. else {
  33417. mesh = new Mesh(parsedMesh.name, scene);
  33418. }
  33419. mesh.id = parsedMesh.id;
  33420. if (BABYLON.Tags) {
  33421. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33422. }
  33423. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33424. if (parsedMesh.metadata !== undefined) {
  33425. mesh.metadata = parsedMesh.metadata;
  33426. }
  33427. if (parsedMesh.rotationQuaternion) {
  33428. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33429. }
  33430. else if (parsedMesh.rotation) {
  33431. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33432. }
  33433. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33434. if (parsedMesh.localMatrix) {
  33435. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33436. }
  33437. else if (parsedMesh.pivotMatrix) {
  33438. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33439. }
  33440. mesh.setEnabled(parsedMesh.isEnabled);
  33441. mesh.isVisible = parsedMesh.isVisible;
  33442. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33443. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33444. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33445. if (parsedMesh.applyFog !== undefined) {
  33446. mesh.applyFog = parsedMesh.applyFog;
  33447. }
  33448. if (parsedMesh.pickable !== undefined) {
  33449. mesh.isPickable = parsedMesh.pickable;
  33450. }
  33451. if (parsedMesh.alphaIndex !== undefined) {
  33452. mesh.alphaIndex = parsedMesh.alphaIndex;
  33453. }
  33454. mesh.receiveShadows = parsedMesh.receiveShadows;
  33455. mesh.billboardMode = parsedMesh.billboardMode;
  33456. if (parsedMesh.visibility !== undefined) {
  33457. mesh.visibility = parsedMesh.visibility;
  33458. }
  33459. mesh.checkCollisions = parsedMesh.checkCollisions;
  33460. if (parsedMesh.isBlocker !== undefined) {
  33461. mesh.isBlocker = parsedMesh.isBlocker;
  33462. }
  33463. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33464. // freezeWorldMatrix
  33465. if (parsedMesh.freezeWorldMatrix) {
  33466. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33467. }
  33468. // Parent
  33469. if (parsedMesh.parentId) {
  33470. mesh._waitingParentId = parsedMesh.parentId;
  33471. }
  33472. // Actions
  33473. if (parsedMesh.actions !== undefined) {
  33474. mesh._waitingActions = parsedMesh.actions;
  33475. }
  33476. // Overlay
  33477. if (parsedMesh.overlayAlpha !== undefined) {
  33478. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33479. }
  33480. if (parsedMesh.overlayColor !== undefined) {
  33481. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33482. }
  33483. if (parsedMesh.renderOverlay !== undefined) {
  33484. mesh.renderOverlay = parsedMesh.renderOverlay;
  33485. }
  33486. // Geometry
  33487. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33488. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33489. if (parsedMesh.delayLoadingFile) {
  33490. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33491. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33492. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33493. if (parsedMesh._binaryInfo) {
  33494. mesh._binaryInfo = parsedMesh._binaryInfo;
  33495. }
  33496. mesh._delayInfo = [];
  33497. if (parsedMesh.hasUVs) {
  33498. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33499. }
  33500. if (parsedMesh.hasUVs2) {
  33501. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33502. }
  33503. if (parsedMesh.hasUVs3) {
  33504. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33505. }
  33506. if (parsedMesh.hasUVs4) {
  33507. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33508. }
  33509. if (parsedMesh.hasUVs5) {
  33510. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33511. }
  33512. if (parsedMesh.hasUVs6) {
  33513. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33514. }
  33515. if (parsedMesh.hasColors) {
  33516. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33517. }
  33518. if (parsedMesh.hasMatricesIndices) {
  33519. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33520. }
  33521. if (parsedMesh.hasMatricesWeights) {
  33522. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33523. }
  33524. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33525. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33526. mesh._checkDelayState();
  33527. }
  33528. }
  33529. else {
  33530. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33531. }
  33532. // Material
  33533. if (parsedMesh.materialId) {
  33534. mesh.setMaterialByID(parsedMesh.materialId);
  33535. }
  33536. else {
  33537. mesh.material = null;
  33538. }
  33539. // Morph targets
  33540. if (parsedMesh.morphTargetManagerId > -1) {
  33541. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33542. }
  33543. // Skeleton
  33544. if (parsedMesh.skeletonId > -1) {
  33545. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33546. if (parsedMesh.numBoneInfluencers) {
  33547. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33548. }
  33549. }
  33550. // Animations
  33551. if (parsedMesh.animations) {
  33552. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33553. var parsedAnimation = parsedMesh.animations[animationIndex];
  33554. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33555. }
  33556. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33557. }
  33558. if (parsedMesh.autoAnimate) {
  33559. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33560. }
  33561. // Layer Mask
  33562. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33563. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33564. }
  33565. else {
  33566. mesh.layerMask = 0x0FFFFFFF;
  33567. }
  33568. // Physics
  33569. if (parsedMesh.physicsImpostor) {
  33570. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33571. mass: parsedMesh.physicsMass,
  33572. friction: parsedMesh.physicsFriction,
  33573. restitution: parsedMesh.physicsRestitution
  33574. }, scene);
  33575. }
  33576. // Instances
  33577. if (parsedMesh.instances) {
  33578. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33579. var parsedInstance = parsedMesh.instances[index];
  33580. var instance = mesh.createInstance(parsedInstance.name);
  33581. if (parsedInstance.id) {
  33582. instance.id = parsedInstance.id;
  33583. }
  33584. if (BABYLON.Tags) {
  33585. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33586. }
  33587. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33588. if (parsedInstance.parentId) {
  33589. instance._waitingParentId = parsedInstance.parentId;
  33590. }
  33591. if (parsedInstance.rotationQuaternion) {
  33592. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33593. }
  33594. else if (parsedInstance.rotation) {
  33595. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33596. }
  33597. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33598. instance.checkCollisions = mesh.checkCollisions;
  33599. if (parsedMesh.animations) {
  33600. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33601. parsedAnimation = parsedMesh.animations[animationIndex];
  33602. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33603. }
  33604. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33605. if (parsedMesh.autoAnimate) {
  33606. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33607. }
  33608. }
  33609. }
  33610. }
  33611. return mesh;
  33612. };
  33613. /**
  33614. * Creates a ribbon mesh.
  33615. * Please consider using the same method from the MeshBuilder class instead.
  33616. * 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.
  33617. *
  33618. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33619. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33620. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33621. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33622. * 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.
  33623. * 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.
  33624. * 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
  33625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33626. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33628. */
  33629. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33630. if (closeArray === void 0) { closeArray = false; }
  33631. if (updatable === void 0) { updatable = false; }
  33632. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33633. pathArray: pathArray,
  33634. closeArray: closeArray,
  33635. closePath: closePath,
  33636. offset: offset,
  33637. updatable: updatable,
  33638. sideOrientation: sideOrientation,
  33639. instance: instance
  33640. }, scene);
  33641. };
  33642. /**
  33643. * Creates a plane polygonal mesh. By default, this is a disc.
  33644. * Please consider using the same method from the MeshBuilder class instead.
  33645. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33646. * 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.
  33647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33648. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33650. */
  33651. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33652. if (scene === void 0) { scene = null; }
  33653. var options = {
  33654. radius: radius,
  33655. tessellation: tessellation,
  33656. sideOrientation: sideOrientation,
  33657. updatable: updatable
  33658. };
  33659. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33660. };
  33661. /**
  33662. * Creates a box mesh.
  33663. * Please consider using the same method from the MeshBuilder class instead.
  33664. * The parameter `size` sets the size (float) of each box side (default 1).
  33665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33666. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33668. */
  33669. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33670. if (scene === void 0) { scene = null; }
  33671. var options = {
  33672. size: size,
  33673. sideOrientation: sideOrientation,
  33674. updatable: updatable
  33675. };
  33676. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33677. };
  33678. /**
  33679. * Creates a sphere mesh.
  33680. * Please consider using the same method from the MeshBuilder class instead.
  33681. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33682. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33684. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33686. */
  33687. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33688. var options = {
  33689. segments: segments,
  33690. diameterX: diameter,
  33691. diameterY: diameter,
  33692. diameterZ: diameter,
  33693. sideOrientation: sideOrientation,
  33694. updatable: updatable
  33695. };
  33696. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33697. };
  33698. /**
  33699. * Creates a cylinder or a cone mesh.
  33700. * Please consider using the same method from the MeshBuilder class instead.
  33701. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33702. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33703. * 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.
  33704. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33705. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33707. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33709. */
  33710. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33711. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33712. if (scene !== undefined) {
  33713. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33714. updatable = scene;
  33715. }
  33716. scene = subdivisions;
  33717. subdivisions = 1;
  33718. }
  33719. var options = {
  33720. height: height,
  33721. diameterTop: diameterTop,
  33722. diameterBottom: diameterBottom,
  33723. tessellation: tessellation,
  33724. subdivisions: subdivisions,
  33725. sideOrientation: sideOrientation,
  33726. updatable: updatable
  33727. };
  33728. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33729. };
  33730. // Torus (Code from SharpDX.org)
  33731. /**
  33732. * Creates a torus mesh.
  33733. * Please consider using the same method from the MeshBuilder class instead.
  33734. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33735. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33736. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33738. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33740. */
  33741. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33742. var options = {
  33743. diameter: diameter,
  33744. thickness: thickness,
  33745. tessellation: tessellation,
  33746. sideOrientation: sideOrientation,
  33747. updatable: updatable
  33748. };
  33749. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33750. };
  33751. /**
  33752. * Creates a torus knot mesh.
  33753. * Please consider using the same method from the MeshBuilder class instead.
  33754. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33755. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33756. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33757. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33759. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33761. */
  33762. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33763. var options = {
  33764. radius: radius,
  33765. tube: tube,
  33766. radialSegments: radialSegments,
  33767. tubularSegments: tubularSegments,
  33768. p: p,
  33769. q: q,
  33770. sideOrientation: sideOrientation,
  33771. updatable: updatable
  33772. };
  33773. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33774. };
  33775. /**
  33776. * Creates a line mesh.
  33777. * Please consider using the same method from the MeshBuilder class instead.
  33778. * 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.
  33779. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33780. * The parameter `points` is an array successive Vector3.
  33781. * 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
  33782. * When updating an instance, remember that only point positions can change, not the number of points.
  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.CreateLines = function (name, points, scene, updatable, instance) {
  33786. if (scene === void 0) { scene = null; }
  33787. if (updatable === void 0) { updatable = false; }
  33788. if (instance === void 0) { instance = null; }
  33789. var options = {
  33790. points: points,
  33791. updatable: updatable,
  33792. instance: instance
  33793. };
  33794. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33795. };
  33796. /**
  33797. * Creates a dashed line mesh.
  33798. * Please consider using the same method from the MeshBuilder class instead.
  33799. * 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.
  33800. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33801. * The parameter `points` is an array successive Vector3.
  33802. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33803. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33804. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33805. * 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
  33806. * When updating an instance, remember that only point positions can change, not the number of points.
  33807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33808. */
  33809. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33810. if (scene === void 0) { scene = null; }
  33811. var options = {
  33812. points: points,
  33813. dashSize: dashSize,
  33814. gapSize: gapSize,
  33815. dashNb: dashNb,
  33816. updatable: updatable,
  33817. instance: instance
  33818. };
  33819. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33820. };
  33821. /**
  33822. * Creates a polygon mesh.
  33823. * Please consider using the same method from the MeshBuilder class instead.
  33824. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33825. * 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.
  33826. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33828. * Remember you can only change the shape positions, not their number when updating a polygon.
  33829. */
  33830. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33831. var options = {
  33832. shape: shape,
  33833. holes: holes,
  33834. updatable: updatable,
  33835. sideOrientation: sideOrientation
  33836. };
  33837. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33838. };
  33839. /**
  33840. * Creates an extruded polygon mesh, with depth in the Y direction.
  33841. * Please consider using the same method from the MeshBuilder class instead.
  33842. */
  33843. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33844. var options = {
  33845. shape: shape,
  33846. holes: holes,
  33847. depth: depth,
  33848. updatable: updatable,
  33849. sideOrientation: sideOrientation
  33850. };
  33851. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33852. };
  33853. /**
  33854. * Creates an extruded shape mesh.
  33855. * 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.
  33856. * Please consider using the same method from the MeshBuilder class instead.
  33857. *
  33858. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33859. * 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
  33860. * extruded along the Z axis.
  33861. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33862. * 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.
  33863. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33864. * 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
  33865. * 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
  33866. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33868. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33870. */
  33871. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33872. if (scene === void 0) { scene = null; }
  33873. var options = {
  33874. shape: shape,
  33875. path: path,
  33876. scale: scale,
  33877. rotation: rotation,
  33878. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33879. sideOrientation: sideOrientation,
  33880. instance: instance,
  33881. updatable: updatable
  33882. };
  33883. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33884. };
  33885. /**
  33886. * Creates an custom extruded shape mesh.
  33887. * 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.
  33888. * Please consider using the same method from the MeshBuilder class instead.
  33889. *
  33890. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33891. * 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
  33892. * extruded along the Z axis.
  33893. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33894. * 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
  33895. * and the distance of this point from the begining of the path :
  33896. * ```javascript
  33897. * var rotationFunction = function(i, distance) {
  33898. * // do things
  33899. * return rotationValue; }
  33900. * ```
  33901. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33902. * 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
  33903. * and the distance of this point from the begining of the path :
  33904. * ```javascript
  33905. * var scaleFunction = function(i, distance) {
  33906. * // do things
  33907. * return scaleValue;}
  33908. * ```
  33909. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33910. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33911. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33912. * 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
  33913. * 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
  33914. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33916. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33918. */
  33919. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33920. var options = {
  33921. shape: shape,
  33922. path: path,
  33923. scaleFunction: scaleFunction,
  33924. rotationFunction: rotationFunction,
  33925. ribbonCloseArray: ribbonCloseArray,
  33926. ribbonClosePath: ribbonClosePath,
  33927. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33928. sideOrientation: sideOrientation,
  33929. instance: instance,
  33930. updatable: updatable
  33931. };
  33932. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33933. };
  33934. /**
  33935. * Creates lathe mesh.
  33936. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33937. * Please consider using the same method from the MeshBuilder class instead.
  33938. * 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
  33939. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33940. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33941. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33943. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33945. */
  33946. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33947. var options = {
  33948. shape: shape,
  33949. radius: radius,
  33950. tessellation: tessellation,
  33951. sideOrientation: sideOrientation,
  33952. updatable: updatable
  33953. };
  33954. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33955. };
  33956. /**
  33957. * Creates a plane mesh.
  33958. * Please consider using the same method from the MeshBuilder class instead.
  33959. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33961. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33963. */
  33964. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33965. var options = {
  33966. size: size,
  33967. width: size,
  33968. height: size,
  33969. sideOrientation: sideOrientation,
  33970. updatable: updatable
  33971. };
  33972. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33973. };
  33974. /**
  33975. * Creates a ground mesh.
  33976. * Please consider using the same method from the MeshBuilder class instead.
  33977. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33978. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33980. */
  33981. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33982. var options = {
  33983. width: width,
  33984. height: height,
  33985. subdivisions: subdivisions,
  33986. updatable: updatable
  33987. };
  33988. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33989. };
  33990. /**
  33991. * Creates a tiled ground mesh.
  33992. * Please consider using the same method from the MeshBuilder class instead.
  33993. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33994. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33995. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33996. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33997. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33998. * numbers of subdivisions on the ground width and height of each tile.
  33999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34000. */
  34001. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34002. var options = {
  34003. xmin: xmin,
  34004. zmin: zmin,
  34005. xmax: xmax,
  34006. zmax: zmax,
  34007. subdivisions: subdivisions,
  34008. precision: precision,
  34009. updatable: updatable
  34010. };
  34011. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34012. };
  34013. /**
  34014. * Creates a ground mesh from a height map.
  34015. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34016. * Please consider using the same method from the MeshBuilder class instead.
  34017. * The parameter `url` sets the URL of the height map image resource.
  34018. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34019. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34020. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34021. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34022. * 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).
  34023. * This function is passed the newly built mesh :
  34024. * ```javascript
  34025. * function(mesh) { // do things
  34026. * return; }
  34027. * ```
  34028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34029. */
  34030. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34031. var options = {
  34032. width: width,
  34033. height: height,
  34034. subdivisions: subdivisions,
  34035. minHeight: minHeight,
  34036. maxHeight: maxHeight,
  34037. updatable: updatable,
  34038. onReady: onReady
  34039. };
  34040. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34041. };
  34042. /**
  34043. * Creates a tube mesh.
  34044. * 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.
  34045. * Please consider using the same method from the MeshBuilder class instead.
  34046. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34047. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34048. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34049. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34050. * 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.
  34051. * It must return a radius value (positive float) :
  34052. * ```javascript
  34053. * var radiusFunction = function(i, distance) {
  34054. * // do things
  34055. * return radius; }
  34056. * ```
  34057. * 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
  34058. * 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
  34059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34060. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34062. */
  34063. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34064. var options = {
  34065. path: path,
  34066. radius: radius,
  34067. tessellation: tessellation,
  34068. radiusFunction: radiusFunction,
  34069. arc: 1,
  34070. cap: cap,
  34071. updatable: updatable,
  34072. sideOrientation: sideOrientation,
  34073. instance: instance
  34074. };
  34075. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34076. };
  34077. /**
  34078. * Creates a polyhedron mesh.
  34079. * Please consider using the same method from the MeshBuilder class instead.
  34080. * 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
  34081. * to choose the wanted type.
  34082. * The parameter `size` (positive float, default 1) sets the polygon size.
  34083. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34084. * 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`.
  34085. * 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
  34086. * 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)`).
  34087. * 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
  34088. * 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.
  34089. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34090. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34092. */
  34093. Mesh.CreatePolyhedron = function (name, options, scene) {
  34094. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34095. };
  34096. /**
  34097. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34098. * Please consider using the same method from the MeshBuilder class instead.
  34099. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34100. * 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`).
  34101. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34102. * 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.
  34103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34104. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34106. */
  34107. Mesh.CreateIcoSphere = function (name, options, scene) {
  34108. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34109. };
  34110. /**
  34111. * Creates a decal mesh.
  34112. * Please consider using the same method from the MeshBuilder class instead.
  34113. * 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.
  34114. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34115. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34116. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34117. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34118. */
  34119. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34120. var options = {
  34121. position: position,
  34122. normal: normal,
  34123. size: size,
  34124. angle: angle
  34125. };
  34126. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34127. };
  34128. // Skeletons
  34129. /**
  34130. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34131. */
  34132. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34133. if (!this._sourcePositions) {
  34134. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34135. if (!source) {
  34136. return this._sourcePositions;
  34137. }
  34138. this._sourcePositions = new Float32Array(source);
  34139. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34140. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34141. }
  34142. }
  34143. return this._sourcePositions;
  34144. };
  34145. /**
  34146. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34147. */
  34148. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34149. if (!this._sourceNormals) {
  34150. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34151. if (!source) {
  34152. return this._sourceNormals;
  34153. }
  34154. this._sourceNormals = new Float32Array(source);
  34155. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34156. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34157. }
  34158. }
  34159. return this._sourceNormals;
  34160. };
  34161. /**
  34162. * Updates the vertex buffer by applying transformation from the bones.
  34163. * Returns the Mesh.
  34164. *
  34165. * @param {skeleton} skeleton to apply
  34166. */
  34167. Mesh.prototype.applySkeleton = function (skeleton) {
  34168. if (!this.geometry) {
  34169. return this;
  34170. }
  34171. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34172. return this;
  34173. }
  34174. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34175. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34176. return this;
  34177. }
  34178. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34179. return this;
  34180. }
  34181. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34182. return this;
  34183. }
  34184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34185. return this;
  34186. }
  34187. if (!this._sourcePositions) {
  34188. var submeshes = this.subMeshes.slice();
  34189. this.setPositionsForCPUSkinning();
  34190. this.subMeshes = submeshes;
  34191. }
  34192. if (!this._sourceNormals) {
  34193. this.setNormalsForCPUSkinning();
  34194. }
  34195. // positionsData checks for not being Float32Array will only pass at most once
  34196. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34197. if (!positionsData) {
  34198. return this;
  34199. }
  34200. if (!(positionsData instanceof Float32Array)) {
  34201. positionsData = new Float32Array(positionsData);
  34202. }
  34203. // normalsData checks for not being Float32Array will only pass at most once
  34204. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34205. if (!normalsData) {
  34206. return this;
  34207. }
  34208. if (!(normalsData instanceof Float32Array)) {
  34209. normalsData = new Float32Array(normalsData);
  34210. }
  34211. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34212. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34213. if (!matricesWeightsData || !matricesIndicesData) {
  34214. return this;
  34215. }
  34216. var needExtras = this.numBoneInfluencers > 4;
  34217. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34218. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34219. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34220. var tempVector3 = BABYLON.Vector3.Zero();
  34221. var finalMatrix = new BABYLON.Matrix();
  34222. var tempMatrix = new BABYLON.Matrix();
  34223. var matWeightIdx = 0;
  34224. var inf;
  34225. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34226. var weight;
  34227. for (inf = 0; inf < 4; inf++) {
  34228. weight = matricesWeightsData[matWeightIdx + inf];
  34229. if (weight > 0) {
  34230. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34231. finalMatrix.addToSelf(tempMatrix);
  34232. }
  34233. else
  34234. break;
  34235. }
  34236. if (needExtras) {
  34237. for (inf = 0; inf < 4; inf++) {
  34238. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34239. if (weight > 0) {
  34240. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34241. finalMatrix.addToSelf(tempMatrix);
  34242. }
  34243. else
  34244. break;
  34245. }
  34246. }
  34247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34248. tempVector3.toArray(positionsData, index);
  34249. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34250. tempVector3.toArray(normalsData, index);
  34251. finalMatrix.reset();
  34252. }
  34253. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34254. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34255. return this;
  34256. };
  34257. // Tools
  34258. /**
  34259. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34260. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34261. */
  34262. Mesh.MinMax = function (meshes) {
  34263. var minVector = null;
  34264. var maxVector = null;
  34265. meshes.forEach(function (mesh, index, array) {
  34266. var boundingInfo = mesh.getBoundingInfo();
  34267. var boundingBox = boundingInfo.boundingBox;
  34268. if (!minVector || !maxVector) {
  34269. minVector = boundingBox.minimumWorld;
  34270. maxVector = boundingBox.maximumWorld;
  34271. }
  34272. else {
  34273. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34274. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34275. }
  34276. });
  34277. if (!minVector || !maxVector) {
  34278. return {
  34279. min: BABYLON.Vector3.Zero(),
  34280. max: BABYLON.Vector3.Zero()
  34281. };
  34282. }
  34283. return {
  34284. min: minVector,
  34285. max: maxVector
  34286. };
  34287. };
  34288. /**
  34289. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34290. */
  34291. Mesh.Center = function (meshesOrMinMaxVector) {
  34292. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34293. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34294. };
  34295. /**
  34296. * Merge the array of meshes into a single mesh for performance reasons.
  34297. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34298. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34299. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34300. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34301. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34302. */
  34303. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34304. if (disposeSource === void 0) { disposeSource = true; }
  34305. var index;
  34306. if (!allow32BitsIndices) {
  34307. var totalVertices = 0;
  34308. // Counting vertices
  34309. for (index = 0; index < meshes.length; index++) {
  34310. if (meshes[index]) {
  34311. totalVertices += meshes[index].getTotalVertices();
  34312. if (totalVertices > 65536) {
  34313. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34314. return null;
  34315. }
  34316. }
  34317. }
  34318. }
  34319. // Merge
  34320. var vertexData = null;
  34321. var otherVertexData;
  34322. var indiceArray = new Array();
  34323. var source = null;
  34324. for (index = 0; index < meshes.length; index++) {
  34325. if (meshes[index]) {
  34326. meshes[index].computeWorldMatrix(true);
  34327. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34328. otherVertexData.transform(meshes[index].getWorldMatrix());
  34329. if (vertexData) {
  34330. vertexData.merge(otherVertexData);
  34331. }
  34332. else {
  34333. vertexData = otherVertexData;
  34334. source = meshes[index];
  34335. }
  34336. if (subdivideWithSubMeshes) {
  34337. indiceArray.push(meshes[index].getTotalIndices());
  34338. }
  34339. }
  34340. }
  34341. source = source;
  34342. if (!meshSubclass) {
  34343. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34344. }
  34345. vertexData.applyToMesh(meshSubclass);
  34346. // Setting properties
  34347. meshSubclass.material = source.material;
  34348. meshSubclass.checkCollisions = source.checkCollisions;
  34349. // Cleaning
  34350. if (disposeSource) {
  34351. for (index = 0; index < meshes.length; index++) {
  34352. if (meshes[index]) {
  34353. meshes[index].dispose();
  34354. }
  34355. }
  34356. }
  34357. // Subdivide
  34358. if (subdivideWithSubMeshes) {
  34359. //-- removal of global submesh
  34360. meshSubclass.releaseSubMeshes();
  34361. index = 0;
  34362. var offset = 0;
  34363. //-- apply subdivision according to index table
  34364. while (index < indiceArray.length) {
  34365. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34366. offset += indiceArray[index];
  34367. index++;
  34368. }
  34369. }
  34370. return meshSubclass;
  34371. };
  34372. // Consts
  34373. Mesh._FRONTSIDE = 0;
  34374. Mesh._BACKSIDE = 1;
  34375. Mesh._DOUBLESIDE = 2;
  34376. Mesh._DEFAULTSIDE = 0;
  34377. Mesh._NO_CAP = 0;
  34378. Mesh._CAP_START = 1;
  34379. Mesh._CAP_END = 2;
  34380. Mesh._CAP_ALL = 3;
  34381. return Mesh;
  34382. }(BABYLON.AbstractMesh));
  34383. BABYLON.Mesh = Mesh;
  34384. })(BABYLON || (BABYLON = {}));
  34385. //# sourceMappingURL=babylon.mesh.js.map
  34386. var BABYLON;
  34387. (function (BABYLON) {
  34388. var BaseSubMesh = /** @class */ (function () {
  34389. function BaseSubMesh() {
  34390. }
  34391. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34392. get: function () {
  34393. return this._materialEffect;
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34399. if (defines === void 0) { defines = null; }
  34400. if (this._materialEffect === effect) {
  34401. if (!effect) {
  34402. this._materialDefines = null;
  34403. }
  34404. return;
  34405. }
  34406. this._materialDefines = defines;
  34407. this._materialEffect = effect;
  34408. };
  34409. return BaseSubMesh;
  34410. }());
  34411. BABYLON.BaseSubMesh = BaseSubMesh;
  34412. var SubMesh = /** @class */ (function (_super) {
  34413. __extends(SubMesh, _super);
  34414. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34415. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34416. var _this = _super.call(this) || this;
  34417. _this.materialIndex = materialIndex;
  34418. _this.verticesStart = verticesStart;
  34419. _this.verticesCount = verticesCount;
  34420. _this.indexStart = indexStart;
  34421. _this.indexCount = indexCount;
  34422. _this._renderId = 0;
  34423. _this._mesh = mesh;
  34424. _this._renderingMesh = renderingMesh || mesh;
  34425. mesh.subMeshes.push(_this);
  34426. _this._trianglePlanes = [];
  34427. _this._id = mesh.subMeshes.length - 1;
  34428. if (createBoundingBox) {
  34429. _this.refreshBoundingInfo();
  34430. mesh.computeWorldMatrix(true);
  34431. }
  34432. return _this;
  34433. }
  34434. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34435. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34436. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34437. };
  34438. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34439. get: function () {
  34440. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34441. },
  34442. enumerable: true,
  34443. configurable: true
  34444. });
  34445. /**
  34446. * Returns the submesh BoudingInfo object.
  34447. */
  34448. SubMesh.prototype.getBoundingInfo = function () {
  34449. if (this.IsGlobal) {
  34450. return this._mesh.getBoundingInfo();
  34451. }
  34452. return this._boundingInfo;
  34453. };
  34454. /**
  34455. * Sets the submesh BoundingInfo.
  34456. * Return the SubMesh.
  34457. */
  34458. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34459. this._boundingInfo = boundingInfo;
  34460. return this;
  34461. };
  34462. /**
  34463. * Returns the mesh of the current submesh.
  34464. */
  34465. SubMesh.prototype.getMesh = function () {
  34466. return this._mesh;
  34467. };
  34468. /**
  34469. * Returns the rendering mesh of the submesh.
  34470. */
  34471. SubMesh.prototype.getRenderingMesh = function () {
  34472. return this._renderingMesh;
  34473. };
  34474. /**
  34475. * Returns the submesh material.
  34476. */
  34477. SubMesh.prototype.getMaterial = function () {
  34478. var rootMaterial = this._renderingMesh.material;
  34479. if (rootMaterial === null || rootMaterial === undefined) {
  34480. return this._mesh.getScene().defaultMaterial;
  34481. }
  34482. else if (rootMaterial.getSubMaterial) {
  34483. var multiMaterial = rootMaterial;
  34484. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34485. if (this._currentMaterial !== effectiveMaterial) {
  34486. this._currentMaterial = effectiveMaterial;
  34487. this._materialDefines = null;
  34488. }
  34489. return effectiveMaterial;
  34490. }
  34491. return rootMaterial;
  34492. };
  34493. // Methods
  34494. /**
  34495. * Sets a new updated BoundingInfo object to the submesh.
  34496. * Returns the SubMesh.
  34497. */
  34498. SubMesh.prototype.refreshBoundingInfo = function () {
  34499. this._lastColliderWorldVertices = null;
  34500. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34501. return this;
  34502. }
  34503. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34504. if (!data) {
  34505. this._boundingInfo = this._mesh.getBoundingInfo();
  34506. return this;
  34507. }
  34508. var indices = this._renderingMesh.getIndices();
  34509. var extend;
  34510. //is this the only submesh?
  34511. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34512. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34513. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34514. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34515. }
  34516. else {
  34517. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34518. }
  34519. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34520. return this;
  34521. };
  34522. SubMesh.prototype._checkCollision = function (collider) {
  34523. var boundingInfo = this.getBoundingInfo();
  34524. return boundingInfo._checkCollision(collider);
  34525. };
  34526. /**
  34527. * Updates the submesh BoundingInfo.
  34528. * Returns the Submesh.
  34529. */
  34530. SubMesh.prototype.updateBoundingInfo = function (world) {
  34531. var boundingInfo = this.getBoundingInfo();
  34532. if (!boundingInfo) {
  34533. this.refreshBoundingInfo();
  34534. boundingInfo = this.getBoundingInfo();
  34535. }
  34536. boundingInfo.update(world);
  34537. return this;
  34538. };
  34539. /**
  34540. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34541. * Boolean returned.
  34542. */
  34543. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34544. var boundingInfo = this.getBoundingInfo();
  34545. if (!boundingInfo) {
  34546. return false;
  34547. }
  34548. return boundingInfo.isInFrustum(frustumPlanes);
  34549. };
  34550. /**
  34551. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34552. * Boolean returned.
  34553. */
  34554. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34555. var boundingInfo = this.getBoundingInfo();
  34556. if (!boundingInfo) {
  34557. return false;
  34558. }
  34559. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34560. };
  34561. /**
  34562. * Renders the submesh.
  34563. * Returns it.
  34564. */
  34565. SubMesh.prototype.render = function (enableAlphaMode) {
  34566. this._renderingMesh.render(this, enableAlphaMode);
  34567. return this;
  34568. };
  34569. /**
  34570. * Returns a new Index Buffer.
  34571. * Type returned : WebGLBuffer.
  34572. */
  34573. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34574. if (!this._linesIndexBuffer) {
  34575. var linesIndices = [];
  34576. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34577. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34578. }
  34579. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34580. this.linesIndexCount = linesIndices.length;
  34581. }
  34582. return this._linesIndexBuffer;
  34583. };
  34584. /**
  34585. * True is the passed Ray intersects the submesh bounding box.
  34586. * Boolean returned.
  34587. */
  34588. SubMesh.prototype.canIntersects = function (ray) {
  34589. var boundingInfo = this.getBoundingInfo();
  34590. if (!boundingInfo) {
  34591. return false;
  34592. }
  34593. return ray.intersectsBox(boundingInfo.boundingBox);
  34594. };
  34595. /**
  34596. * Returns an object IntersectionInfo.
  34597. */
  34598. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34599. var intersectInfo = null;
  34600. var material = this.getMaterial();
  34601. if (!material) {
  34602. return null;
  34603. }
  34604. switch (material.fillMode) {
  34605. case BABYLON.Material.PointListDrawMode:
  34606. case BABYLON.Material.LineListDrawMode:
  34607. case BABYLON.Material.LineLoopDrawMode:
  34608. case BABYLON.Material.LineStripDrawMode:
  34609. case BABYLON.Material.TriangleFanDrawMode:
  34610. case BABYLON.Material.TriangleStripDrawMode:
  34611. return null;
  34612. }
  34613. // LineMesh first as it's also a Mesh...
  34614. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34615. var lineMesh = this._mesh;
  34616. // Line test
  34617. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34618. var p0 = positions[indices[index]];
  34619. var p1 = positions[indices[index + 1]];
  34620. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34621. if (length < 0) {
  34622. continue;
  34623. }
  34624. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34625. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34626. if (fastCheck) {
  34627. break;
  34628. }
  34629. }
  34630. }
  34631. }
  34632. else {
  34633. // Triangles test
  34634. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34635. var p0 = positions[indices[index]];
  34636. var p1 = positions[indices[index + 1]];
  34637. var p2 = positions[indices[index + 2]];
  34638. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34639. if (currentIntersectInfo) {
  34640. if (currentIntersectInfo.distance < 0) {
  34641. continue;
  34642. }
  34643. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34644. intersectInfo = currentIntersectInfo;
  34645. intersectInfo.faceId = index / 3;
  34646. if (fastCheck) {
  34647. break;
  34648. }
  34649. }
  34650. }
  34651. }
  34652. }
  34653. return intersectInfo;
  34654. };
  34655. SubMesh.prototype._rebuild = function () {
  34656. if (this._linesIndexBuffer) {
  34657. this._linesIndexBuffer = null;
  34658. }
  34659. };
  34660. // Clone
  34661. /**
  34662. * Creates a new Submesh from the passed Mesh.
  34663. */
  34664. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34665. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34666. if (!this.IsGlobal) {
  34667. var boundingInfo = this.getBoundingInfo();
  34668. if (!boundingInfo) {
  34669. return result;
  34670. }
  34671. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34672. }
  34673. return result;
  34674. };
  34675. // Dispose
  34676. /**
  34677. * Disposes the Submesh.
  34678. * Returns nothing.
  34679. */
  34680. SubMesh.prototype.dispose = function () {
  34681. if (this._linesIndexBuffer) {
  34682. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34683. this._linesIndexBuffer = null;
  34684. }
  34685. // Remove from mesh
  34686. var index = this._mesh.subMeshes.indexOf(this);
  34687. this._mesh.subMeshes.splice(index, 1);
  34688. };
  34689. // Statics
  34690. /**
  34691. * Creates a new Submesh from the passed parameters :
  34692. * - materialIndex (integer) : the index of the main mesh material.
  34693. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34694. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34695. * - mesh (Mesh) : the main mesh to create the submesh from.
  34696. * - renderingMesh (optional Mesh) : rendering mesh.
  34697. */
  34698. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34699. var minVertexIndex = Number.MAX_VALUE;
  34700. var maxVertexIndex = -Number.MAX_VALUE;
  34701. renderingMesh = (renderingMesh || mesh);
  34702. var indices = renderingMesh.getIndices();
  34703. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34704. var vertexIndex = indices[index];
  34705. if (vertexIndex < minVertexIndex)
  34706. minVertexIndex = vertexIndex;
  34707. if (vertexIndex > maxVertexIndex)
  34708. maxVertexIndex = vertexIndex;
  34709. }
  34710. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34711. };
  34712. return SubMesh;
  34713. }(BaseSubMesh));
  34714. BABYLON.SubMesh = SubMesh;
  34715. })(BABYLON || (BABYLON = {}));
  34716. //# sourceMappingURL=babylon.subMesh.js.map
  34717. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34718. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34719. s = arguments[i];
  34720. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34721. t[p] = s[p];
  34722. }
  34723. return t;
  34724. };
  34725. var BABYLON;
  34726. (function (BABYLON) {
  34727. /**
  34728. * Manages the defines for the Material
  34729. */
  34730. var MaterialDefines = /** @class */ (function () {
  34731. function MaterialDefines() {
  34732. this._isDirty = true;
  34733. /** @hidden */
  34734. this._areLightsDirty = true;
  34735. /** @hidden */
  34736. this._areAttributesDirty = true;
  34737. /** @hidden */
  34738. this._areTexturesDirty = true;
  34739. /** @hidden */
  34740. this._areFresnelDirty = true;
  34741. /** @hidden */
  34742. this._areMiscDirty = true;
  34743. /** @hidden */
  34744. this._areImageProcessingDirty = true;
  34745. /** @hidden */
  34746. this._normals = false;
  34747. /** @hidden */
  34748. this._uvs = false;
  34749. /** @hidden */
  34750. this._needNormals = false;
  34751. /** @hidden */
  34752. this._needUVs = false;
  34753. }
  34754. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34755. /**
  34756. * Specifies if the material needs to be re-calculated
  34757. */
  34758. get: function () {
  34759. return this._isDirty;
  34760. },
  34761. enumerable: true,
  34762. configurable: true
  34763. });
  34764. /**
  34765. * Marks the material to indicate that it has been re-calculated
  34766. */
  34767. MaterialDefines.prototype.markAsProcessed = function () {
  34768. this._isDirty = false;
  34769. this._areAttributesDirty = false;
  34770. this._areTexturesDirty = false;
  34771. this._areFresnelDirty = false;
  34772. this._areLightsDirty = false;
  34773. this._areMiscDirty = false;
  34774. this._areImageProcessingDirty = false;
  34775. };
  34776. /**
  34777. * Marks the material to indicate that it needs to be re-calculated
  34778. */
  34779. MaterialDefines.prototype.markAsUnprocessed = function () {
  34780. this._isDirty = true;
  34781. };
  34782. /**
  34783. * Marks the material to indicate all of its defines need to be re-calculated
  34784. */
  34785. MaterialDefines.prototype.markAllAsDirty = function () {
  34786. this._areTexturesDirty = true;
  34787. this._areAttributesDirty = true;
  34788. this._areLightsDirty = true;
  34789. this._areFresnelDirty = true;
  34790. this._areMiscDirty = true;
  34791. this._areImageProcessingDirty = true;
  34792. this._isDirty = true;
  34793. };
  34794. /**
  34795. * Marks the material to indicate that image processing needs to be re-calculated
  34796. */
  34797. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34798. this._areImageProcessingDirty = true;
  34799. this._isDirty = true;
  34800. };
  34801. /**
  34802. * Marks the material to indicate the lights need to be re-calculated
  34803. */
  34804. MaterialDefines.prototype.markAsLightDirty = function () {
  34805. this._areLightsDirty = true;
  34806. this._isDirty = true;
  34807. };
  34808. /**
  34809. * Marks the attribute state as changed
  34810. */
  34811. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34812. this._areAttributesDirty = true;
  34813. this._isDirty = true;
  34814. };
  34815. /**
  34816. * Marks the texture state as changed
  34817. */
  34818. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34819. this._areTexturesDirty = true;
  34820. this._isDirty = true;
  34821. };
  34822. /**
  34823. * Marks the fresnel state as changed
  34824. */
  34825. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34826. this._areFresnelDirty = true;
  34827. this._isDirty = true;
  34828. };
  34829. /**
  34830. * Marks the misc state as changed
  34831. */
  34832. MaterialDefines.prototype.markAsMiscDirty = function () {
  34833. this._areMiscDirty = true;
  34834. this._isDirty = true;
  34835. };
  34836. /**
  34837. * Rebuilds the material defines
  34838. */
  34839. MaterialDefines.prototype.rebuild = function () {
  34840. if (this._keys) {
  34841. delete this._keys;
  34842. }
  34843. this._keys = [];
  34844. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34845. var key = _a[_i];
  34846. if (key[0] === "_") {
  34847. continue;
  34848. }
  34849. this._keys.push(key);
  34850. }
  34851. };
  34852. /**
  34853. * Specifies if two material defines are equal
  34854. * @param other - A material define instance to compare to
  34855. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34856. */
  34857. MaterialDefines.prototype.isEqual = function (other) {
  34858. if (this._keys.length !== other._keys.length) {
  34859. return false;
  34860. }
  34861. for (var index = 0; index < this._keys.length; index++) {
  34862. var prop = this._keys[index];
  34863. if (this[prop] !== other[prop]) {
  34864. return false;
  34865. }
  34866. }
  34867. return true;
  34868. };
  34869. /**
  34870. * Clones this instance's defines to another instance
  34871. * @param other - material defines to clone values to
  34872. */
  34873. MaterialDefines.prototype.cloneTo = function (other) {
  34874. if (this._keys.length !== other._keys.length) {
  34875. other._keys = this._keys.slice(0);
  34876. }
  34877. for (var index = 0; index < this._keys.length; index++) {
  34878. var prop = this._keys[index];
  34879. other[prop] = this[prop];
  34880. }
  34881. };
  34882. /**
  34883. * Resets the material define values
  34884. */
  34885. MaterialDefines.prototype.reset = function () {
  34886. for (var index = 0; index < this._keys.length; index++) {
  34887. var prop = this._keys[index];
  34888. var type = typeof this[prop];
  34889. switch (type) {
  34890. case "number":
  34891. this[prop] = 0;
  34892. break;
  34893. case "string":
  34894. this[prop] = "";
  34895. break;
  34896. default:
  34897. this[prop] = false;
  34898. break;
  34899. }
  34900. }
  34901. };
  34902. /**
  34903. * Converts the material define values to a string
  34904. * @returns - String of material define information
  34905. */
  34906. MaterialDefines.prototype.toString = function () {
  34907. var result = "";
  34908. for (var index = 0; index < this._keys.length; index++) {
  34909. var prop = this._keys[index];
  34910. var value = this[prop];
  34911. var type = typeof value;
  34912. switch (type) {
  34913. case "number":
  34914. case "string":
  34915. result += "#define " + prop + " " + value + "\n";
  34916. break;
  34917. default:
  34918. if (value) {
  34919. result += "#define " + prop + "\n";
  34920. }
  34921. break;
  34922. }
  34923. }
  34924. return result;
  34925. };
  34926. return MaterialDefines;
  34927. }());
  34928. BABYLON.MaterialDefines = MaterialDefines;
  34929. /**
  34930. * Base class for the main features of a material in Babylon.js
  34931. */
  34932. var Material = /** @class */ (function () {
  34933. /**
  34934. * Creates a material instance
  34935. * @param name defines the name of the material
  34936. * @param scene defines the scene to reference
  34937. * @param doNotAdd specifies if the material should be added to the scene
  34938. */
  34939. function Material(name, scene, doNotAdd) {
  34940. /**
  34941. * Specifies if the ready state should be checked on each call
  34942. */
  34943. this.checkReadyOnEveryCall = false;
  34944. /**
  34945. * Specifies if the ready state should be checked once
  34946. */
  34947. this.checkReadyOnlyOnce = false;
  34948. /**
  34949. * The state of the material
  34950. */
  34951. this.state = "";
  34952. /**
  34953. * The alpha value of the material
  34954. */
  34955. this._alpha = 1.0;
  34956. /**
  34957. * Specifies if back face culling is enabled
  34958. */
  34959. this._backFaceCulling = true;
  34960. /**
  34961. * Specifies if the material should be serialized
  34962. */
  34963. this.doNotSerialize = false;
  34964. /**
  34965. * Specifies if the effect should be stored on sub meshes
  34966. */
  34967. this.storeEffectOnSubMeshes = false;
  34968. /**
  34969. * An event triggered when the material is disposed
  34970. */
  34971. this.onDisposeObservable = new BABYLON.Observable();
  34972. /**
  34973. * An event triggered when the material is bound
  34974. */
  34975. this.onBindObservable = new BABYLON.Observable();
  34976. /**
  34977. * An event triggered when the material is unbound
  34978. */
  34979. this.onUnBindObservable = new BABYLON.Observable();
  34980. /**
  34981. * Stores the value of the alpha mode
  34982. */
  34983. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34984. /**
  34985. * Stores the state of the need depth pre-pass value
  34986. */
  34987. this._needDepthPrePass = false;
  34988. /**
  34989. * Specifies if depth writing should be disabled
  34990. */
  34991. this.disableDepthWrite = false;
  34992. /**
  34993. * Specifies if depth writing should be forced
  34994. */
  34995. this.forceDepthWrite = false;
  34996. /**
  34997. * Specifies if there should be a separate pass for culling
  34998. */
  34999. this.separateCullingPass = false;
  35000. /**
  35001. * Stores the state specifing if fog should be enabled
  35002. */
  35003. this._fogEnabled = true;
  35004. /**
  35005. * Stores the size of points
  35006. */
  35007. this.pointSize = 1.0;
  35008. /**
  35009. * Stores the z offset value
  35010. */
  35011. this.zOffset = 0;
  35012. /**
  35013. * Specifies if the material was previously ready
  35014. */
  35015. this._wasPreviouslyReady = false;
  35016. /**
  35017. * Stores the fill mode state
  35018. */
  35019. this._fillMode = Material.TriangleFillMode;
  35020. this.name = name;
  35021. this.id = name || BABYLON.Tools.RandomId();
  35022. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35023. this.uniqueId = this._scene.getUniqueId();
  35024. if (this._scene.useRightHandedSystem) {
  35025. this.sideOrientation = Material.ClockWiseSideOrientation;
  35026. }
  35027. else {
  35028. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35029. }
  35030. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35031. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35032. if (!doNotAdd) {
  35033. this._scene.materials.push(this);
  35034. }
  35035. }
  35036. Object.defineProperty(Material, "TriangleFillMode", {
  35037. /**
  35038. * Returns the triangle fill mode
  35039. */
  35040. get: function () {
  35041. return Material._TriangleFillMode;
  35042. },
  35043. enumerable: true,
  35044. configurable: true
  35045. });
  35046. Object.defineProperty(Material, "WireFrameFillMode", {
  35047. /**
  35048. * Returns the wireframe mode
  35049. */
  35050. get: function () {
  35051. return Material._WireFrameFillMode;
  35052. },
  35053. enumerable: true,
  35054. configurable: true
  35055. });
  35056. Object.defineProperty(Material, "PointFillMode", {
  35057. /**
  35058. * Returns the point fill mode
  35059. */
  35060. get: function () {
  35061. return Material._PointFillMode;
  35062. },
  35063. enumerable: true,
  35064. configurable: true
  35065. });
  35066. Object.defineProperty(Material, "PointListDrawMode", {
  35067. /**
  35068. * Returns the point list draw mode
  35069. */
  35070. get: function () {
  35071. return Material._PointListDrawMode;
  35072. },
  35073. enumerable: true,
  35074. configurable: true
  35075. });
  35076. Object.defineProperty(Material, "LineListDrawMode", {
  35077. /**
  35078. * Returns the line list draw mode
  35079. */
  35080. get: function () {
  35081. return Material._LineListDrawMode;
  35082. },
  35083. enumerable: true,
  35084. configurable: true
  35085. });
  35086. Object.defineProperty(Material, "LineLoopDrawMode", {
  35087. /**
  35088. * Returns the line loop draw mode
  35089. */
  35090. get: function () {
  35091. return Material._LineLoopDrawMode;
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(Material, "LineStripDrawMode", {
  35097. /**
  35098. * Returns the line strip draw mode
  35099. */
  35100. get: function () {
  35101. return Material._LineStripDrawMode;
  35102. },
  35103. enumerable: true,
  35104. configurable: true
  35105. });
  35106. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35107. /**
  35108. * Returns the triangle strip draw mode
  35109. */
  35110. get: function () {
  35111. return Material._TriangleStripDrawMode;
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35117. /**
  35118. * Returns the triangle fan draw mode
  35119. */
  35120. get: function () {
  35121. return Material._TriangleFanDrawMode;
  35122. },
  35123. enumerable: true,
  35124. configurable: true
  35125. });
  35126. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35127. /**
  35128. * Returns the clock-wise side orientation
  35129. */
  35130. get: function () {
  35131. return Material._ClockWiseSideOrientation;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35137. /**
  35138. * Returns the counter clock-wise side orientation
  35139. */
  35140. get: function () {
  35141. return Material._CounterClockWiseSideOrientation;
  35142. },
  35143. enumerable: true,
  35144. configurable: true
  35145. });
  35146. Object.defineProperty(Material, "TextureDirtyFlag", {
  35147. /**
  35148. * Returns the dirty texture flag value
  35149. */
  35150. get: function () {
  35151. return Material._TextureDirtyFlag;
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(Material, "LightDirtyFlag", {
  35157. /**
  35158. * Returns the dirty light flag value
  35159. */
  35160. get: function () {
  35161. return Material._LightDirtyFlag;
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35167. /**
  35168. * Returns the dirty fresnel flag value
  35169. */
  35170. get: function () {
  35171. return Material._FresnelDirtyFlag;
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35177. /**
  35178. * Returns the dirty attributes flag value
  35179. */
  35180. get: function () {
  35181. return Material._AttributesDirtyFlag;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. Object.defineProperty(Material, "MiscDirtyFlag", {
  35187. /**
  35188. * Returns the dirty misc flag value
  35189. */
  35190. get: function () {
  35191. return Material._MiscDirtyFlag;
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(Material.prototype, "alpha", {
  35197. /**
  35198. * Gets the alpha value of the material
  35199. */
  35200. get: function () {
  35201. return this._alpha;
  35202. },
  35203. /**
  35204. * Sets the alpha value of the material
  35205. */
  35206. set: function (value) {
  35207. if (this._alpha === value) {
  35208. return;
  35209. }
  35210. this._alpha = value;
  35211. this.markAsDirty(Material.MiscDirtyFlag);
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35217. /**
  35218. * Gets the back-face culling state
  35219. */
  35220. get: function () {
  35221. return this._backFaceCulling;
  35222. },
  35223. /**
  35224. * Sets the back-face culling state
  35225. */
  35226. set: function (value) {
  35227. if (this._backFaceCulling === value) {
  35228. return;
  35229. }
  35230. this._backFaceCulling = value;
  35231. this.markAsDirty(Material.TextureDirtyFlag);
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(Material.prototype, "onDispose", {
  35237. /**
  35238. * Called during a dispose event
  35239. */
  35240. set: function (callback) {
  35241. if (this._onDisposeObserver) {
  35242. this.onDisposeObservable.remove(this._onDisposeObserver);
  35243. }
  35244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(Material.prototype, "onBind", {
  35250. /**
  35251. * Called during a bind event
  35252. */
  35253. set: function (callback) {
  35254. if (this._onBindObserver) {
  35255. this.onBindObservable.remove(this._onBindObserver);
  35256. }
  35257. this._onBindObserver = this.onBindObservable.add(callback);
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(Material.prototype, "alphaMode", {
  35263. /**
  35264. * Gets the value of the alpha mode
  35265. */
  35266. get: function () {
  35267. return this._alphaMode;
  35268. },
  35269. /**
  35270. * Sets the value of the alpha mode.
  35271. *
  35272. * | Value | Type | Description |
  35273. * | --- | --- | --- |
  35274. * | 0 | ALPHA_DISABLE | |
  35275. * | 1 | ALPHA_ADD | |
  35276. * | 2 | ALPHA_COMBINE | |
  35277. * | 3 | ALPHA_SUBTRACT | |
  35278. * | 4 | ALPHA_MULTIPLY | |
  35279. * | 5 | ALPHA_MAXIMIZED | |
  35280. * | 6 | ALPHA_ONEONE | |
  35281. * | 7 | ALPHA_PREMULTIPLIED | |
  35282. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35283. * | 9 | ALPHA_INTERPOLATE | |
  35284. * | 10 | ALPHA_SCREENMODE | |
  35285. *
  35286. */
  35287. set: function (value) {
  35288. if (this._alphaMode === value) {
  35289. return;
  35290. }
  35291. this._alphaMode = value;
  35292. this.markAsDirty(Material.TextureDirtyFlag);
  35293. },
  35294. enumerable: true,
  35295. configurable: true
  35296. });
  35297. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35298. /**
  35299. * Gets the depth pre-pass value
  35300. */
  35301. get: function () {
  35302. return this._needDepthPrePass;
  35303. },
  35304. /**
  35305. * Sets the need depth pre-pass value
  35306. */
  35307. set: function (value) {
  35308. if (this._needDepthPrePass === value) {
  35309. return;
  35310. }
  35311. this._needDepthPrePass = value;
  35312. if (this._needDepthPrePass) {
  35313. this.checkReadyOnEveryCall = true;
  35314. }
  35315. },
  35316. enumerable: true,
  35317. configurable: true
  35318. });
  35319. Object.defineProperty(Material.prototype, "fogEnabled", {
  35320. /**
  35321. * Gets the value of the fog enabled state
  35322. */
  35323. get: function () {
  35324. return this._fogEnabled;
  35325. },
  35326. /**
  35327. * Sets the state for enabling fog
  35328. */
  35329. set: function (value) {
  35330. if (this._fogEnabled === value) {
  35331. return;
  35332. }
  35333. this._fogEnabled = value;
  35334. this.markAsDirty(Material.MiscDirtyFlag);
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. Object.defineProperty(Material.prototype, "wireframe", {
  35340. /**
  35341. * Gets a value specifying if wireframe mode is enabled
  35342. */
  35343. get: function () {
  35344. switch (this._fillMode) {
  35345. case Material.WireFrameFillMode:
  35346. case Material.LineListDrawMode:
  35347. case Material.LineLoopDrawMode:
  35348. case Material.LineStripDrawMode:
  35349. return true;
  35350. }
  35351. return this._scene.forceWireframe;
  35352. },
  35353. /**
  35354. * Sets the state of wireframe mode
  35355. */
  35356. set: function (value) {
  35357. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35358. },
  35359. enumerable: true,
  35360. configurable: true
  35361. });
  35362. Object.defineProperty(Material.prototype, "pointsCloud", {
  35363. /**
  35364. * Gets the value specifying if point clouds are enabled
  35365. */
  35366. get: function () {
  35367. switch (this._fillMode) {
  35368. case Material.PointFillMode:
  35369. case Material.PointListDrawMode:
  35370. return true;
  35371. }
  35372. return this._scene.forcePointsCloud;
  35373. },
  35374. /**
  35375. * Sets the state of point cloud mode
  35376. */
  35377. set: function (value) {
  35378. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35379. },
  35380. enumerable: true,
  35381. configurable: true
  35382. });
  35383. Object.defineProperty(Material.prototype, "fillMode", {
  35384. /**
  35385. * Gets the material fill mode
  35386. */
  35387. get: function () {
  35388. return this._fillMode;
  35389. },
  35390. /**
  35391. * Sets the material fill mode
  35392. */
  35393. set: function (value) {
  35394. if (this._fillMode === value) {
  35395. return;
  35396. }
  35397. this._fillMode = value;
  35398. this.markAsDirty(Material.MiscDirtyFlag);
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. /**
  35404. * Returns a string representation of the current material
  35405. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35406. * @returns a string with material information
  35407. */
  35408. Material.prototype.toString = function (fullDetails) {
  35409. var ret = "Name: " + this.name;
  35410. if (fullDetails) {
  35411. }
  35412. return ret;
  35413. };
  35414. /**
  35415. * Gets the class name of the material
  35416. * @returns a string with the class name of the material
  35417. */
  35418. Material.prototype.getClassName = function () {
  35419. return "Material";
  35420. };
  35421. Object.defineProperty(Material.prototype, "isFrozen", {
  35422. /**
  35423. * Specifies if updates for the material been locked
  35424. */
  35425. get: function () {
  35426. return this.checkReadyOnlyOnce;
  35427. },
  35428. enumerable: true,
  35429. configurable: true
  35430. });
  35431. /**
  35432. * Locks updates for the material
  35433. */
  35434. Material.prototype.freeze = function () {
  35435. this.checkReadyOnlyOnce = true;
  35436. };
  35437. /**
  35438. * Unlocks updates for the material
  35439. */
  35440. Material.prototype.unfreeze = function () {
  35441. this.checkReadyOnlyOnce = false;
  35442. };
  35443. /**
  35444. * Specifies if the material is ready to be used
  35445. * @param mesh defines the mesh to check
  35446. * @param useInstances specifies if instances should be used
  35447. * @returns a boolean indicating if the material is ready to be used
  35448. */
  35449. Material.prototype.isReady = function (mesh, useInstances) {
  35450. return true;
  35451. };
  35452. /**
  35453. * Specifies that the submesh is ready to be used
  35454. * @param mesh defines the mesh to check
  35455. * @param subMesh defines which submesh to check
  35456. * @param useInstances specifies that instances should be used
  35457. * @returns a boolean indicating that the submesh is ready or not
  35458. */
  35459. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35460. return false;
  35461. };
  35462. /**
  35463. * Returns the material effect
  35464. * @returns the effect associated with the material
  35465. */
  35466. Material.prototype.getEffect = function () {
  35467. return this._effect;
  35468. };
  35469. /**
  35470. * Returns the current scene
  35471. * @returns a Scene
  35472. */
  35473. Material.prototype.getScene = function () {
  35474. return this._scene;
  35475. };
  35476. /**
  35477. * Specifies if the material will require alpha blending
  35478. * @returns a boolean specifying if alpha blending is needed
  35479. */
  35480. Material.prototype.needAlphaBlending = function () {
  35481. return (this.alpha < 1.0);
  35482. };
  35483. /**
  35484. * Specifies if the mesh will require alpha blending
  35485. * @param mesh defines the mesh to check
  35486. * @returns a boolean specifying if alpha blending is needed for the mesh
  35487. */
  35488. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35489. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35490. };
  35491. /**
  35492. * Specifies if this material should be rendered in alpha test mode
  35493. * @returns a boolean specifying if an alpha test is needed.
  35494. */
  35495. Material.prototype.needAlphaTesting = function () {
  35496. return false;
  35497. };
  35498. /**
  35499. * Gets the texture used for the alpha test
  35500. * @returns the texture to use for alpha testing
  35501. */
  35502. Material.prototype.getAlphaTestTexture = function () {
  35503. return null;
  35504. };
  35505. /**
  35506. * Marks the material to indicate that it needs to be re-calculated
  35507. */
  35508. Material.prototype.markDirty = function () {
  35509. this._wasPreviouslyReady = false;
  35510. };
  35511. /** @hidden */
  35512. Material.prototype._preBind = function (effect, overrideOrientation) {
  35513. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35514. var engine = this._scene.getEngine();
  35515. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35516. var reverse = orientation === Material.ClockWiseSideOrientation;
  35517. engine.enableEffect(effect ? effect : this._effect);
  35518. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35519. return reverse;
  35520. };
  35521. /**
  35522. * Binds the material to the mesh
  35523. * @param world defines the world transformation matrix
  35524. * @param mesh defines the mesh to bind the material to
  35525. */
  35526. Material.prototype.bind = function (world, mesh) {
  35527. };
  35528. /**
  35529. * Binds the submesh to the material
  35530. * @param world defines the world transformation matrix
  35531. * @param mesh defines the mesh containing the submesh
  35532. * @param subMesh defines the submesh to bind the material to
  35533. */
  35534. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35535. };
  35536. /**
  35537. * Binds the world matrix to the material
  35538. * @param world defines the world transformation matrix
  35539. */
  35540. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35541. };
  35542. /**
  35543. * Binds the scene's uniform buffer to the effect.
  35544. * @param effect defines the effect to bind to the scene uniform buffer
  35545. * @param sceneUbo defines the uniform buffer storing scene data
  35546. */
  35547. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35548. sceneUbo.bindToEffect(effect, "Scene");
  35549. };
  35550. /**
  35551. * Binds the view matrix to the effect
  35552. * @param effect defines the effect to bind the view matrix to
  35553. */
  35554. Material.prototype.bindView = function (effect) {
  35555. if (!this._useUBO) {
  35556. effect.setMatrix("view", this.getScene().getViewMatrix());
  35557. }
  35558. else {
  35559. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35560. }
  35561. };
  35562. /**
  35563. * Binds the view projection matrix to the effect
  35564. * @param effect defines the effect to bind the view projection matrix to
  35565. */
  35566. Material.prototype.bindViewProjection = function (effect) {
  35567. if (!this._useUBO) {
  35568. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35569. }
  35570. else {
  35571. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35572. }
  35573. };
  35574. /**
  35575. * Specifies if material alpha testing should be turned on for the mesh
  35576. * @param mesh defines the mesh to check
  35577. */
  35578. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35579. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35580. };
  35581. /**
  35582. * Processes to execute after binding the material to a mesh
  35583. * @param mesh defines the rendered mesh
  35584. */
  35585. Material.prototype._afterBind = function (mesh) {
  35586. this._scene._cachedMaterial = this;
  35587. if (mesh) {
  35588. this._scene._cachedVisibility = mesh.visibility;
  35589. }
  35590. else {
  35591. this._scene._cachedVisibility = 1;
  35592. }
  35593. if (mesh) {
  35594. this.onBindObservable.notifyObservers(mesh);
  35595. }
  35596. if (this.disableDepthWrite) {
  35597. var engine = this._scene.getEngine();
  35598. this._cachedDepthWriteState = engine.getDepthWrite();
  35599. engine.setDepthWrite(false);
  35600. }
  35601. };
  35602. /**
  35603. * Unbinds the material from the mesh
  35604. */
  35605. Material.prototype.unbind = function () {
  35606. this.onUnBindObservable.notifyObservers(this);
  35607. if (this.disableDepthWrite) {
  35608. var engine = this._scene.getEngine();
  35609. engine.setDepthWrite(this._cachedDepthWriteState);
  35610. }
  35611. };
  35612. /**
  35613. * Gets the active textures from the material
  35614. * @returns an array of textures
  35615. */
  35616. Material.prototype.getActiveTextures = function () {
  35617. return [];
  35618. };
  35619. /**
  35620. * Specifies if the material uses a texture
  35621. * @param texture defines the texture to check against the material
  35622. * @returns a boolean specifying if the material uses the texture
  35623. */
  35624. Material.prototype.hasTexture = function (texture) {
  35625. return false;
  35626. };
  35627. /**
  35628. * Makes a duplicate of the material, and gives it a new name
  35629. * @param name defines the new name for the duplicated material
  35630. * @returns the cloned material
  35631. */
  35632. Material.prototype.clone = function (name) {
  35633. return null;
  35634. };
  35635. /**
  35636. * Gets the meshes bound to the material
  35637. * @returns an array of meshes bound to the material
  35638. */
  35639. Material.prototype.getBindedMeshes = function () {
  35640. var result = new Array();
  35641. for (var index = 0; index < this._scene.meshes.length; index++) {
  35642. var mesh = this._scene.meshes[index];
  35643. if (mesh.material === this) {
  35644. result.push(mesh);
  35645. }
  35646. }
  35647. return result;
  35648. };
  35649. /**
  35650. * Force shader compilation
  35651. * @param mesh defines the mesh associated with this material
  35652. * @param onCompiled defines a function to execute once the material is compiled
  35653. * @param options defines the options to configure the compilation
  35654. */
  35655. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35656. var _this = this;
  35657. var localOptions = __assign({ clipPlane: false }, options);
  35658. var subMesh = new BABYLON.BaseSubMesh();
  35659. var scene = this.getScene();
  35660. var checkReady = function () {
  35661. if (!_this._scene || !_this._scene.getEngine()) {
  35662. return;
  35663. }
  35664. if (subMesh._materialDefines) {
  35665. subMesh._materialDefines._renderId = -1;
  35666. }
  35667. var clipPlaneState = scene.clipPlane;
  35668. if (localOptions.clipPlane) {
  35669. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35670. }
  35671. if (_this.storeEffectOnSubMeshes) {
  35672. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35673. if (onCompiled) {
  35674. onCompiled(_this);
  35675. }
  35676. }
  35677. else {
  35678. setTimeout(checkReady, 16);
  35679. }
  35680. }
  35681. else {
  35682. if (_this.isReady(mesh)) {
  35683. if (onCompiled) {
  35684. onCompiled(_this);
  35685. }
  35686. }
  35687. else {
  35688. setTimeout(checkReady, 16);
  35689. }
  35690. }
  35691. if (localOptions.clipPlane) {
  35692. scene.clipPlane = clipPlaneState;
  35693. }
  35694. };
  35695. checkReady();
  35696. };
  35697. /**
  35698. * Force shader compilation
  35699. * @param mesh defines the mesh that will use this material
  35700. * @param options defines additional options for compiling the shaders
  35701. * @returns a promise that resolves when the compilation completes
  35702. */
  35703. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35704. var _this = this;
  35705. return new Promise(function (resolve) {
  35706. _this.forceCompilation(mesh, function () {
  35707. resolve();
  35708. }, options);
  35709. });
  35710. };
  35711. /**
  35712. * Marks a define in the material to indicate that it needs to be re-computed
  35713. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35714. */
  35715. Material.prototype.markAsDirty = function (flag) {
  35716. if (flag & Material.TextureDirtyFlag) {
  35717. this._markAllSubMeshesAsTexturesDirty();
  35718. }
  35719. if (flag & Material.LightDirtyFlag) {
  35720. this._markAllSubMeshesAsLightsDirty();
  35721. }
  35722. if (flag & Material.FresnelDirtyFlag) {
  35723. this._markAllSubMeshesAsFresnelDirty();
  35724. }
  35725. if (flag & Material.AttributesDirtyFlag) {
  35726. this._markAllSubMeshesAsAttributesDirty();
  35727. }
  35728. if (flag & Material.MiscDirtyFlag) {
  35729. this._markAllSubMeshesAsMiscDirty();
  35730. }
  35731. this.getScene().resetCachedMaterial();
  35732. };
  35733. /**
  35734. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35735. * @param func defines a function which checks material defines against the submeshes
  35736. */
  35737. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35738. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35739. var mesh = _a[_i];
  35740. if (!mesh.subMeshes) {
  35741. continue;
  35742. }
  35743. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35744. var subMesh = _c[_b];
  35745. if (subMesh.getMaterial() !== this) {
  35746. continue;
  35747. }
  35748. if (!subMesh._materialDefines) {
  35749. continue;
  35750. }
  35751. func(subMesh._materialDefines);
  35752. }
  35753. }
  35754. };
  35755. /**
  35756. * Indicates that image processing needs to be re-calculated for all submeshes
  35757. */
  35758. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35759. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35760. };
  35761. /**
  35762. * Indicates that textures need to be re-calculated for all submeshes
  35763. */
  35764. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35765. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35766. };
  35767. /**
  35768. * Indicates that fresnel needs to be re-calculated for all submeshes
  35769. */
  35770. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35771. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35772. };
  35773. /**
  35774. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35775. */
  35776. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35777. this._markAllSubMeshesAsDirty(function (defines) {
  35778. defines.markAsFresnelDirty();
  35779. defines.markAsMiscDirty();
  35780. });
  35781. };
  35782. /**
  35783. * Indicates that lights need to be re-calculated for all submeshes
  35784. */
  35785. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35786. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35787. };
  35788. /**
  35789. * Indicates that attributes need to be re-calculated for all submeshes
  35790. */
  35791. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35792. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35793. };
  35794. /**
  35795. * Indicates that misc needs to be re-calculated for all submeshes
  35796. */
  35797. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35798. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35799. };
  35800. /**
  35801. * Indicates that textures and misc need to be re-calculated for all submeshes
  35802. */
  35803. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35804. this._markAllSubMeshesAsDirty(function (defines) {
  35805. defines.markAsTexturesDirty();
  35806. defines.markAsMiscDirty();
  35807. });
  35808. };
  35809. /**
  35810. * Disposes the material
  35811. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35812. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35813. */
  35814. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35815. // Animations
  35816. this.getScene().stopAnimation(this);
  35817. this.getScene().freeProcessedMaterials();
  35818. // Remove from scene
  35819. var index = this._scene.materials.indexOf(this);
  35820. if (index >= 0) {
  35821. this._scene.materials.splice(index, 1);
  35822. }
  35823. // Remove from meshes
  35824. for (index = 0; index < this._scene.meshes.length; index++) {
  35825. var mesh = this._scene.meshes[index];
  35826. if (mesh.material === this) {
  35827. mesh.material = null;
  35828. if (mesh.geometry) {
  35829. var geometry = (mesh.geometry);
  35830. if (this.storeEffectOnSubMeshes) {
  35831. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35832. var subMesh = _a[_i];
  35833. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35834. if (forceDisposeEffect && subMesh._materialEffect) {
  35835. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35836. }
  35837. }
  35838. }
  35839. else {
  35840. geometry._releaseVertexArrayObject(this._effect);
  35841. }
  35842. }
  35843. }
  35844. }
  35845. this._uniformBuffer.dispose();
  35846. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35847. if (forceDisposeEffect && this._effect) {
  35848. if (!this.storeEffectOnSubMeshes) {
  35849. this._scene.getEngine()._releaseEffect(this._effect);
  35850. }
  35851. this._effect = null;
  35852. }
  35853. // Callback
  35854. this.onDisposeObservable.notifyObservers(this);
  35855. this.onDisposeObservable.clear();
  35856. this.onBindObservable.clear();
  35857. this.onUnBindObservable.clear();
  35858. };
  35859. /**
  35860. * Serializes this material
  35861. * @returns the serialized material object
  35862. */
  35863. Material.prototype.serialize = function () {
  35864. return BABYLON.SerializationHelper.Serialize(this);
  35865. };
  35866. /**
  35867. * Creates a MultiMaterial from parsed MultiMaterial data.
  35868. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35869. * @param scene defines the hosting scene
  35870. * @returns a new MultiMaterial
  35871. */
  35872. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35873. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35874. multiMaterial.id = parsedMultiMaterial.id;
  35875. if (BABYLON.Tags) {
  35876. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35877. }
  35878. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35879. var subMatId = parsedMultiMaterial.materials[matIndex];
  35880. if (subMatId) {
  35881. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35882. }
  35883. else {
  35884. multiMaterial.subMaterials.push(null);
  35885. }
  35886. }
  35887. return multiMaterial;
  35888. };
  35889. /**
  35890. * Creates a material from parsed material data
  35891. * @param parsedMaterial defines parsed material data
  35892. * @param scene defines the hosting scene
  35893. * @param rootUrl defines the root URL to use to load textures
  35894. * @returns a new material
  35895. */
  35896. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35897. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35898. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35899. }
  35900. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35901. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35902. if (!BABYLON.LegacyPBRMaterial) {
  35903. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35904. return;
  35905. }
  35906. }
  35907. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35908. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35909. };
  35910. // Triangle views
  35911. Material._TriangleFillMode = 0;
  35912. Material._WireFrameFillMode = 1;
  35913. Material._PointFillMode = 2;
  35914. // Draw modes
  35915. Material._PointListDrawMode = 3;
  35916. Material._LineListDrawMode = 4;
  35917. Material._LineLoopDrawMode = 5;
  35918. Material._LineStripDrawMode = 6;
  35919. Material._TriangleStripDrawMode = 7;
  35920. Material._TriangleFanDrawMode = 8;
  35921. /**
  35922. * Stores the clock-wise side orientation
  35923. */
  35924. Material._ClockWiseSideOrientation = 0;
  35925. /**
  35926. * Stores the counter clock-wise side orientation
  35927. */
  35928. Material._CounterClockWiseSideOrientation = 1;
  35929. /**
  35930. * The dirty texture flag value
  35931. */
  35932. Material._TextureDirtyFlag = 1;
  35933. /**
  35934. * The dirty light flag value
  35935. */
  35936. Material._LightDirtyFlag = 2;
  35937. /**
  35938. * The dirty fresnel flag value
  35939. */
  35940. Material._FresnelDirtyFlag = 4;
  35941. /**
  35942. * The dirty attribute flag value
  35943. */
  35944. Material._AttributesDirtyFlag = 8;
  35945. /**
  35946. * The dirty misc flag value
  35947. */
  35948. Material._MiscDirtyFlag = 16;
  35949. __decorate([
  35950. BABYLON.serialize()
  35951. ], Material.prototype, "id", void 0);
  35952. __decorate([
  35953. BABYLON.serialize()
  35954. ], Material.prototype, "uniqueId", void 0);
  35955. __decorate([
  35956. BABYLON.serialize()
  35957. ], Material.prototype, "name", void 0);
  35958. __decorate([
  35959. BABYLON.serialize()
  35960. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35961. __decorate([
  35962. BABYLON.serialize()
  35963. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35964. __decorate([
  35965. BABYLON.serialize()
  35966. ], Material.prototype, "state", void 0);
  35967. __decorate([
  35968. BABYLON.serialize("alpha")
  35969. ], Material.prototype, "_alpha", void 0);
  35970. __decorate([
  35971. BABYLON.serialize("backFaceCulling")
  35972. ], Material.prototype, "_backFaceCulling", void 0);
  35973. __decorate([
  35974. BABYLON.serialize()
  35975. ], Material.prototype, "sideOrientation", void 0);
  35976. __decorate([
  35977. BABYLON.serialize("alphaMode")
  35978. ], Material.prototype, "_alphaMode", void 0);
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], Material.prototype, "_needDepthPrePass", void 0);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], Material.prototype, "disableDepthWrite", void 0);
  35985. __decorate([
  35986. BABYLON.serialize()
  35987. ], Material.prototype, "forceDepthWrite", void 0);
  35988. __decorate([
  35989. BABYLON.serialize()
  35990. ], Material.prototype, "separateCullingPass", void 0);
  35991. __decorate([
  35992. BABYLON.serialize("fogEnabled")
  35993. ], Material.prototype, "_fogEnabled", void 0);
  35994. __decorate([
  35995. BABYLON.serialize()
  35996. ], Material.prototype, "pointSize", void 0);
  35997. __decorate([
  35998. BABYLON.serialize()
  35999. ], Material.prototype, "zOffset", void 0);
  36000. __decorate([
  36001. BABYLON.serialize()
  36002. ], Material.prototype, "wireframe", null);
  36003. __decorate([
  36004. BABYLON.serialize()
  36005. ], Material.prototype, "pointsCloud", null);
  36006. __decorate([
  36007. BABYLON.serialize()
  36008. ], Material.prototype, "fillMode", null);
  36009. return Material;
  36010. }());
  36011. BABYLON.Material = Material;
  36012. })(BABYLON || (BABYLON = {}));
  36013. //# sourceMappingURL=babylon.material.js.map
  36014. var BABYLON;
  36015. (function (BABYLON) {
  36016. var UniformBuffer = /** @class */ (function () {
  36017. /**
  36018. * Uniform buffer objects.
  36019. *
  36020. * Handles blocks of uniform on the GPU.
  36021. *
  36022. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36023. *
  36024. * For more information, please refer to :
  36025. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36026. */
  36027. function UniformBuffer(engine, data, dynamic) {
  36028. this._engine = engine;
  36029. this._noUBO = !engine.supportsUniformBuffers;
  36030. this._dynamic = dynamic;
  36031. this._data = data || [];
  36032. this._uniformLocations = {};
  36033. this._uniformSizes = {};
  36034. this._uniformLocationPointer = 0;
  36035. this._needSync = false;
  36036. if (this._noUBO) {
  36037. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36038. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36039. this.updateFloat = this._updateFloatForEffect;
  36040. this.updateFloat2 = this._updateFloat2ForEffect;
  36041. this.updateFloat3 = this._updateFloat3ForEffect;
  36042. this.updateFloat4 = this._updateFloat4ForEffect;
  36043. this.updateMatrix = this._updateMatrixForEffect;
  36044. this.updateVector3 = this._updateVector3ForEffect;
  36045. this.updateVector4 = this._updateVector4ForEffect;
  36046. this.updateColor3 = this._updateColor3ForEffect;
  36047. this.updateColor4 = this._updateColor4ForEffect;
  36048. }
  36049. else {
  36050. this._engine._uniformBuffers.push(this);
  36051. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36052. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36053. this.updateFloat = this._updateFloatForUniform;
  36054. this.updateFloat2 = this._updateFloat2ForUniform;
  36055. this.updateFloat3 = this._updateFloat3ForUniform;
  36056. this.updateFloat4 = this._updateFloat4ForUniform;
  36057. this.updateMatrix = this._updateMatrixForUniform;
  36058. this.updateVector3 = this._updateVector3ForUniform;
  36059. this.updateVector4 = this._updateVector4ForUniform;
  36060. this.updateColor3 = this._updateColor3ForUniform;
  36061. this.updateColor4 = this._updateColor4ForUniform;
  36062. }
  36063. }
  36064. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36065. // Properties
  36066. /**
  36067. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36068. * or just falling back on setUniformXXX calls.
  36069. */
  36070. get: function () {
  36071. return !this._noUBO;
  36072. },
  36073. enumerable: true,
  36074. configurable: true
  36075. });
  36076. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36077. /**
  36078. * Indicates if the WebGL underlying uniform buffer is in sync
  36079. * with the javascript cache data.
  36080. */
  36081. get: function () {
  36082. return !this._needSync;
  36083. },
  36084. enumerable: true,
  36085. configurable: true
  36086. });
  36087. /**
  36088. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36089. * Also, a dynamic UniformBuffer will disable cache verification and always
  36090. * update the underlying WebGL uniform buffer to the GPU.
  36091. */
  36092. UniformBuffer.prototype.isDynamic = function () {
  36093. return this._dynamic !== undefined;
  36094. };
  36095. /**
  36096. * The data cache on JS side.
  36097. */
  36098. UniformBuffer.prototype.getData = function () {
  36099. return this._bufferData;
  36100. };
  36101. /**
  36102. * The underlying WebGL Uniform buffer.
  36103. */
  36104. UniformBuffer.prototype.getBuffer = function () {
  36105. return this._buffer;
  36106. };
  36107. /**
  36108. * std140 layout specifies how to align data within an UBO structure.
  36109. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36110. * for specs.
  36111. */
  36112. UniformBuffer.prototype._fillAlignment = function (size) {
  36113. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36114. // and 4x4 matrices
  36115. // TODO : change if other types are used
  36116. var alignment;
  36117. if (size <= 2) {
  36118. alignment = size;
  36119. }
  36120. else {
  36121. alignment = 4;
  36122. }
  36123. if ((this._uniformLocationPointer % alignment) !== 0) {
  36124. var oldPointer = this._uniformLocationPointer;
  36125. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36126. var diff = this._uniformLocationPointer - oldPointer;
  36127. for (var i = 0; i < diff; i++) {
  36128. this._data.push(0);
  36129. }
  36130. }
  36131. };
  36132. /**
  36133. * Adds an uniform in the buffer.
  36134. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36135. * for the layout to be correct !
  36136. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36137. * @param {number|number[]} size Data size, or data directly.
  36138. */
  36139. UniformBuffer.prototype.addUniform = function (name, size) {
  36140. if (this._noUBO) {
  36141. return;
  36142. }
  36143. if (this._uniformLocations[name] !== undefined) {
  36144. // Already existing uniform
  36145. return;
  36146. }
  36147. // This function must be called in the order of the shader layout !
  36148. // size can be the size of the uniform, or data directly
  36149. var data;
  36150. if (size instanceof Array) {
  36151. data = size;
  36152. size = data.length;
  36153. }
  36154. else {
  36155. size = size;
  36156. data = [];
  36157. // Fill with zeros
  36158. for (var i = 0; i < size; i++) {
  36159. data.push(0);
  36160. }
  36161. }
  36162. this._fillAlignment(size);
  36163. this._uniformSizes[name] = size;
  36164. this._uniformLocations[name] = this._uniformLocationPointer;
  36165. this._uniformLocationPointer += size;
  36166. for (var i = 0; i < size; i++) {
  36167. this._data.push(data[i]);
  36168. }
  36169. this._needSync = true;
  36170. };
  36171. /**
  36172. * Wrapper for addUniform.
  36173. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36174. * @param {Matrix} mat A 4x4 matrix.
  36175. */
  36176. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36177. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36178. };
  36179. /**
  36180. * Wrapper for addUniform.
  36181. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36182. * @param {number} x
  36183. * @param {number} y
  36184. */
  36185. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36186. var temp = [x, y];
  36187. this.addUniform(name, temp);
  36188. };
  36189. /**
  36190. * Wrapper for addUniform.
  36191. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36192. * @param {number} x
  36193. * @param {number} y
  36194. * @param {number} z
  36195. */
  36196. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36197. var temp = [x, y, z];
  36198. this.addUniform(name, temp);
  36199. };
  36200. /**
  36201. * Wrapper for addUniform.
  36202. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36203. * @param {Color3} color
  36204. */
  36205. UniformBuffer.prototype.addColor3 = function (name, color) {
  36206. var temp = new Array();
  36207. color.toArray(temp);
  36208. this.addUniform(name, temp);
  36209. };
  36210. /**
  36211. * Wrapper for addUniform.
  36212. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36213. * @param {Color3} color
  36214. * @param {number} alpha
  36215. */
  36216. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36217. var temp = new Array();
  36218. color.toArray(temp);
  36219. temp.push(alpha);
  36220. this.addUniform(name, temp);
  36221. };
  36222. /**
  36223. * Wrapper for addUniform.
  36224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36225. * @param {Vector3} vector
  36226. */
  36227. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36228. var temp = new Array();
  36229. vector.toArray(temp);
  36230. this.addUniform(name, temp);
  36231. };
  36232. /**
  36233. * Wrapper for addUniform.
  36234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36235. */
  36236. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36237. this.addUniform(name, 12);
  36238. };
  36239. /**
  36240. * Wrapper for addUniform.
  36241. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36242. */
  36243. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36244. this.addUniform(name, 8);
  36245. };
  36246. /**
  36247. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36248. */
  36249. UniformBuffer.prototype.create = function () {
  36250. if (this._noUBO) {
  36251. return;
  36252. }
  36253. if (this._buffer) {
  36254. return; // nothing to do
  36255. }
  36256. // See spec, alignment must be filled as a vec4
  36257. this._fillAlignment(4);
  36258. this._bufferData = new Float32Array(this._data);
  36259. this._rebuild();
  36260. this._needSync = true;
  36261. };
  36262. UniformBuffer.prototype._rebuild = function () {
  36263. if (this._noUBO) {
  36264. return;
  36265. }
  36266. if (this._dynamic) {
  36267. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36268. }
  36269. else {
  36270. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36271. }
  36272. };
  36273. /**
  36274. * Updates the WebGL Uniform Buffer on the GPU.
  36275. * If the `dynamic` flag is set to true, no cache comparison is done.
  36276. * Otherwise, the buffer will be updated only if the cache differs.
  36277. */
  36278. UniformBuffer.prototype.update = function () {
  36279. if (!this._buffer) {
  36280. this.create();
  36281. return;
  36282. }
  36283. if (!this._dynamic && !this._needSync) {
  36284. return;
  36285. }
  36286. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36287. this._needSync = false;
  36288. };
  36289. /**
  36290. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36291. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36292. * @param {number[]|Float32Array} data Flattened data
  36293. * @param {number} size Size of the data.
  36294. */
  36295. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36296. var location = this._uniformLocations[uniformName];
  36297. if (location === undefined) {
  36298. if (this._buffer) {
  36299. // Cannot add an uniform if the buffer is already created
  36300. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36301. return;
  36302. }
  36303. this.addUniform(uniformName, size);
  36304. location = this._uniformLocations[uniformName];
  36305. }
  36306. if (!this._buffer) {
  36307. this.create();
  36308. }
  36309. if (!this._dynamic) {
  36310. // Cache for static uniform buffers
  36311. var changed = false;
  36312. for (var i = 0; i < size; i++) {
  36313. if (this._bufferData[location + i] !== data[i]) {
  36314. changed = true;
  36315. this._bufferData[location + i] = data[i];
  36316. }
  36317. }
  36318. this._needSync = this._needSync || changed;
  36319. }
  36320. else {
  36321. // No cache for dynamic
  36322. for (var i = 0; i < size; i++) {
  36323. this._bufferData[location + i] = data[i];
  36324. }
  36325. }
  36326. };
  36327. // Update methods
  36328. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36329. // To match std140, matrix must be realigned
  36330. for (var i = 0; i < 3; i++) {
  36331. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36332. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36333. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36334. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36335. }
  36336. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36337. };
  36338. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36339. this._currentEffect.setMatrix3x3(name, matrix);
  36340. };
  36341. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36342. this._currentEffect.setMatrix2x2(name, matrix);
  36343. };
  36344. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36345. // To match std140, matrix must be realigned
  36346. for (var i = 0; i < 2; i++) {
  36347. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36348. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36349. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36350. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36351. }
  36352. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36353. };
  36354. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36355. this._currentEffect.setFloat(name, x);
  36356. };
  36357. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36358. UniformBuffer._tempBuffer[0] = x;
  36359. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36360. };
  36361. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36362. if (suffix === void 0) { suffix = ""; }
  36363. this._currentEffect.setFloat2(name + suffix, x, y);
  36364. };
  36365. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36366. if (suffix === void 0) { suffix = ""; }
  36367. UniformBuffer._tempBuffer[0] = x;
  36368. UniformBuffer._tempBuffer[1] = y;
  36369. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36370. };
  36371. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36372. if (suffix === void 0) { suffix = ""; }
  36373. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36374. };
  36375. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36376. if (suffix === void 0) { suffix = ""; }
  36377. UniformBuffer._tempBuffer[0] = x;
  36378. UniformBuffer._tempBuffer[1] = y;
  36379. UniformBuffer._tempBuffer[2] = z;
  36380. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36381. };
  36382. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36383. if (suffix === void 0) { suffix = ""; }
  36384. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36385. };
  36386. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36387. if (suffix === void 0) { suffix = ""; }
  36388. UniformBuffer._tempBuffer[0] = x;
  36389. UniformBuffer._tempBuffer[1] = y;
  36390. UniformBuffer._tempBuffer[2] = z;
  36391. UniformBuffer._tempBuffer[3] = w;
  36392. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36393. };
  36394. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36395. this._currentEffect.setMatrix(name, mat);
  36396. };
  36397. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36398. this.updateUniform(name, mat.toArray(), 16);
  36399. };
  36400. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36401. this._currentEffect.setVector3(name, vector);
  36402. };
  36403. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36404. vector.toArray(UniformBuffer._tempBuffer);
  36405. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36406. };
  36407. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36408. this._currentEffect.setVector4(name, vector);
  36409. };
  36410. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36411. vector.toArray(UniformBuffer._tempBuffer);
  36412. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36413. };
  36414. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36415. if (suffix === void 0) { suffix = ""; }
  36416. this._currentEffect.setColor3(name + suffix, color);
  36417. };
  36418. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36419. if (suffix === void 0) { suffix = ""; }
  36420. color.toArray(UniformBuffer._tempBuffer);
  36421. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36422. };
  36423. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36424. if (suffix === void 0) { suffix = ""; }
  36425. this._currentEffect.setColor4(name + suffix, color, alpha);
  36426. };
  36427. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36428. if (suffix === void 0) { suffix = ""; }
  36429. color.toArray(UniformBuffer._tempBuffer);
  36430. UniformBuffer._tempBuffer[3] = alpha;
  36431. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36432. };
  36433. /**
  36434. * Sets a sampler uniform on the effect.
  36435. * @param {string} name Name of the sampler.
  36436. * @param {Texture} texture
  36437. */
  36438. UniformBuffer.prototype.setTexture = function (name, texture) {
  36439. this._currentEffect.setTexture(name, texture);
  36440. };
  36441. /**
  36442. * Directly updates the value of the uniform in the cache AND on the GPU.
  36443. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36444. * @param {number[]|Float32Array} data Flattened data
  36445. */
  36446. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36447. this.updateUniform(uniformName, data, data.length);
  36448. this.update();
  36449. };
  36450. /**
  36451. * Binds this uniform buffer to an effect.
  36452. * @param {Effect} effect
  36453. * @param {string} name Name of the uniform block in the shader.
  36454. */
  36455. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36456. this._currentEffect = effect;
  36457. if (this._noUBO || !this._buffer) {
  36458. return;
  36459. }
  36460. effect.bindUniformBuffer(this._buffer, name);
  36461. };
  36462. /**
  36463. * Disposes the uniform buffer.
  36464. */
  36465. UniformBuffer.prototype.dispose = function () {
  36466. if (this._noUBO) {
  36467. return;
  36468. }
  36469. var index = this._engine._uniformBuffers.indexOf(this);
  36470. if (index !== -1) {
  36471. this._engine._uniformBuffers.splice(index, 1);
  36472. }
  36473. if (!this._buffer) {
  36474. return;
  36475. }
  36476. if (this._engine._releaseBuffer(this._buffer)) {
  36477. this._buffer = null;
  36478. }
  36479. };
  36480. // Pool for avoiding memory leaks
  36481. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36482. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36483. return UniformBuffer;
  36484. }());
  36485. BABYLON.UniformBuffer = UniformBuffer;
  36486. })(BABYLON || (BABYLON = {}));
  36487. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36488. var BABYLON;
  36489. (function (BABYLON) {
  36490. /**
  36491. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36492. */
  36493. var VertexData = /** @class */ (function () {
  36494. function VertexData() {
  36495. }
  36496. /**
  36497. * Uses the passed data array to set the set the values for the specified kind of data
  36498. * @param data a linear array of floating numbers
  36499. * @param kind the type of data that is being set, eg positions, colors etc
  36500. */
  36501. VertexData.prototype.set = function (data, kind) {
  36502. switch (kind) {
  36503. case BABYLON.VertexBuffer.PositionKind:
  36504. this.positions = data;
  36505. break;
  36506. case BABYLON.VertexBuffer.NormalKind:
  36507. this.normals = data;
  36508. break;
  36509. case BABYLON.VertexBuffer.TangentKind:
  36510. this.tangents = data;
  36511. break;
  36512. case BABYLON.VertexBuffer.UVKind:
  36513. this.uvs = data;
  36514. break;
  36515. case BABYLON.VertexBuffer.UV2Kind:
  36516. this.uvs2 = data;
  36517. break;
  36518. case BABYLON.VertexBuffer.UV3Kind:
  36519. this.uvs3 = data;
  36520. break;
  36521. case BABYLON.VertexBuffer.UV4Kind:
  36522. this.uvs4 = data;
  36523. break;
  36524. case BABYLON.VertexBuffer.UV5Kind:
  36525. this.uvs5 = data;
  36526. break;
  36527. case BABYLON.VertexBuffer.UV6Kind:
  36528. this.uvs6 = data;
  36529. break;
  36530. case BABYLON.VertexBuffer.ColorKind:
  36531. this.colors = data;
  36532. break;
  36533. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36534. this.matricesIndices = data;
  36535. break;
  36536. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36537. this.matricesWeights = data;
  36538. break;
  36539. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36540. this.matricesIndicesExtra = data;
  36541. break;
  36542. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36543. this.matricesWeightsExtra = data;
  36544. break;
  36545. }
  36546. };
  36547. /**
  36548. * Associates the vertexData to the passed Mesh.
  36549. * Sets it as updatable or not (default `false`)
  36550. * @param mesh the mesh the vertexData is applied to
  36551. * @param updatable when used and having the value true allows new data to update the vertexData
  36552. * @returns the VertexData
  36553. */
  36554. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36555. this._applyTo(mesh, updatable);
  36556. return this;
  36557. };
  36558. /**
  36559. * Associates the vertexData to the passed Geometry.
  36560. * Sets it as updatable or not (default `false`)
  36561. * @param geometry the geometry the vertexData is applied to
  36562. * @param updatable when used and having the value true allows new data to update the vertexData
  36563. * @returns VertexData
  36564. */
  36565. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36566. this._applyTo(geometry, updatable);
  36567. return this;
  36568. };
  36569. /**
  36570. * Updates the associated mesh
  36571. * @param mesh the mesh to be updated
  36572. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36573. * @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
  36574. * @returns VertexData
  36575. */
  36576. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36577. this._update(mesh);
  36578. return this;
  36579. };
  36580. /**
  36581. * Updates the associated geometry
  36582. * @param geometry the geometry to be updated
  36583. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36584. * @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
  36585. * @returns VertexData.
  36586. */
  36587. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36588. this._update(geometry);
  36589. return this;
  36590. };
  36591. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36592. if (updatable === void 0) { updatable = false; }
  36593. if (this.positions) {
  36594. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36595. }
  36596. if (this.normals) {
  36597. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36598. }
  36599. if (this.tangents) {
  36600. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36601. }
  36602. if (this.uvs) {
  36603. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36604. }
  36605. if (this.uvs2) {
  36606. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36607. }
  36608. if (this.uvs3) {
  36609. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36610. }
  36611. if (this.uvs4) {
  36612. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36613. }
  36614. if (this.uvs5) {
  36615. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36616. }
  36617. if (this.uvs6) {
  36618. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36619. }
  36620. if (this.colors) {
  36621. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36622. }
  36623. if (this.matricesIndices) {
  36624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36625. }
  36626. if (this.matricesWeights) {
  36627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36628. }
  36629. if (this.matricesIndicesExtra) {
  36630. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36631. }
  36632. if (this.matricesWeightsExtra) {
  36633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36634. }
  36635. if (this.indices) {
  36636. meshOrGeometry.setIndices(this.indices, null, updatable);
  36637. }
  36638. else {
  36639. meshOrGeometry.setIndices([], null);
  36640. }
  36641. return this;
  36642. };
  36643. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36644. if (this.positions) {
  36645. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36646. }
  36647. if (this.normals) {
  36648. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36649. }
  36650. if (this.tangents) {
  36651. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36652. }
  36653. if (this.uvs) {
  36654. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36655. }
  36656. if (this.uvs2) {
  36657. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36658. }
  36659. if (this.uvs3) {
  36660. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36661. }
  36662. if (this.uvs4) {
  36663. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36664. }
  36665. if (this.uvs5) {
  36666. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36667. }
  36668. if (this.uvs6) {
  36669. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36670. }
  36671. if (this.colors) {
  36672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36673. }
  36674. if (this.matricesIndices) {
  36675. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36676. }
  36677. if (this.matricesWeights) {
  36678. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36679. }
  36680. if (this.matricesIndicesExtra) {
  36681. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36682. }
  36683. if (this.matricesWeightsExtra) {
  36684. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36685. }
  36686. if (this.indices) {
  36687. meshOrGeometry.setIndices(this.indices, null);
  36688. }
  36689. return this;
  36690. };
  36691. /**
  36692. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36693. * @param matrix the transforming matrix
  36694. * @returns the VertexData
  36695. */
  36696. VertexData.prototype.transform = function (matrix) {
  36697. var transformed = BABYLON.Vector3.Zero();
  36698. var index;
  36699. if (this.positions) {
  36700. var position = BABYLON.Vector3.Zero();
  36701. for (index = 0; index < this.positions.length; index += 3) {
  36702. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36703. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36704. this.positions[index] = transformed.x;
  36705. this.positions[index + 1] = transformed.y;
  36706. this.positions[index + 2] = transformed.z;
  36707. }
  36708. }
  36709. if (this.normals) {
  36710. var normal = BABYLON.Vector3.Zero();
  36711. for (index = 0; index < this.normals.length; index += 3) {
  36712. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36713. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36714. this.normals[index] = transformed.x;
  36715. this.normals[index + 1] = transformed.y;
  36716. this.normals[index + 2] = transformed.z;
  36717. }
  36718. }
  36719. if (this.tangents) {
  36720. var tangent = BABYLON.Vector4.Zero();
  36721. var tangentTransformed = BABYLON.Vector4.Zero();
  36722. for (index = 0; index < this.tangents.length; index += 4) {
  36723. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36724. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36725. this.tangents[index] = tangentTransformed.x;
  36726. this.tangents[index + 1] = tangentTransformed.y;
  36727. this.tangents[index + 2] = tangentTransformed.z;
  36728. this.tangents[index + 3] = tangentTransformed.w;
  36729. }
  36730. }
  36731. return this;
  36732. };
  36733. /**
  36734. * Merges the passed VertexData into the current one
  36735. * @param other the VertexData to be merged into the current one
  36736. * @returns the modified VertexData
  36737. */
  36738. VertexData.prototype.merge = function (other) {
  36739. this._validate();
  36740. other._validate();
  36741. if (!this.normals !== !other.normals ||
  36742. !this.tangents !== !other.tangents ||
  36743. !this.uvs !== !other.uvs ||
  36744. !this.uvs2 !== !other.uvs2 ||
  36745. !this.uvs3 !== !other.uvs3 ||
  36746. !this.uvs4 !== !other.uvs4 ||
  36747. !this.uvs5 !== !other.uvs5 ||
  36748. !this.uvs6 !== !other.uvs6 ||
  36749. !this.colors !== !other.colors ||
  36750. !this.matricesIndices !== !other.matricesIndices ||
  36751. !this.matricesWeights !== !other.matricesWeights ||
  36752. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36753. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36754. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36755. }
  36756. if (other.indices) {
  36757. if (!this.indices) {
  36758. this.indices = [];
  36759. }
  36760. var offset = this.positions ? this.positions.length / 3 : 0;
  36761. for (var index = 0; index < other.indices.length; index++) {
  36762. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36763. this.indices.push(other.indices[index] + offset);
  36764. }
  36765. }
  36766. this.positions = this._mergeElement(this.positions, other.positions);
  36767. this.normals = this._mergeElement(this.normals, other.normals);
  36768. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36769. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36770. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36771. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36772. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36773. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36774. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36775. this.colors = this._mergeElement(this.colors, other.colors);
  36776. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36777. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36778. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36779. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36780. return this;
  36781. };
  36782. VertexData.prototype._mergeElement = function (source, other) {
  36783. if (!source) {
  36784. return other;
  36785. }
  36786. if (!other) {
  36787. return source;
  36788. }
  36789. var len = other.length + source.length;
  36790. var isSrcTypedArray = source instanceof Float32Array;
  36791. var isOthTypedArray = other instanceof Float32Array;
  36792. // use non-loop method when the source is Float32Array
  36793. if (isSrcTypedArray) {
  36794. var ret32 = new Float32Array(len);
  36795. ret32.set(source);
  36796. ret32.set(other, source.length);
  36797. return ret32;
  36798. // source is number[], when other is also use concat
  36799. }
  36800. else if (!isOthTypedArray) {
  36801. return source.concat(other);
  36802. // source is a number[], but other is a Float32Array, loop required
  36803. }
  36804. else {
  36805. var ret = source.slice(0); // copy source to a separate array
  36806. for (var i = 0, len = other.length; i < len; i++) {
  36807. ret.push(other[i]);
  36808. }
  36809. return ret;
  36810. }
  36811. };
  36812. VertexData.prototype._validate = function () {
  36813. if (!this.positions) {
  36814. throw new Error("Positions are required");
  36815. }
  36816. var getElementCount = function (kind, values) {
  36817. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36818. if ((values.length % stride) !== 0) {
  36819. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36820. }
  36821. return values.length / stride;
  36822. };
  36823. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36824. var validateElementCount = function (kind, values) {
  36825. var elementCount = getElementCount(kind, values);
  36826. if (elementCount !== positionsElementCount) {
  36827. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36828. }
  36829. };
  36830. if (this.normals)
  36831. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36832. if (this.tangents)
  36833. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36834. if (this.uvs)
  36835. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36836. if (this.uvs2)
  36837. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36838. if (this.uvs3)
  36839. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36840. if (this.uvs4)
  36841. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36842. if (this.uvs5)
  36843. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36844. if (this.uvs6)
  36845. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36846. if (this.colors)
  36847. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36848. if (this.matricesIndices)
  36849. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36850. if (this.matricesWeights)
  36851. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36852. if (this.matricesIndicesExtra)
  36853. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36854. if (this.matricesWeightsExtra)
  36855. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36856. };
  36857. /**
  36858. * Serializes the VertexData
  36859. * @returns a serialized object
  36860. */
  36861. VertexData.prototype.serialize = function () {
  36862. var serializationObject = this.serialize();
  36863. if (this.positions) {
  36864. serializationObject.positions = this.positions;
  36865. }
  36866. if (this.normals) {
  36867. serializationObject.normals = this.normals;
  36868. }
  36869. if (this.tangents) {
  36870. serializationObject.tangents = this.tangents;
  36871. }
  36872. if (this.uvs) {
  36873. serializationObject.uvs = this.uvs;
  36874. }
  36875. if (this.uvs2) {
  36876. serializationObject.uvs2 = this.uvs2;
  36877. }
  36878. if (this.uvs3) {
  36879. serializationObject.uvs3 = this.uvs3;
  36880. }
  36881. if (this.uvs4) {
  36882. serializationObject.uvs4 = this.uvs4;
  36883. }
  36884. if (this.uvs5) {
  36885. serializationObject.uvs5 = this.uvs5;
  36886. }
  36887. if (this.uvs6) {
  36888. serializationObject.uvs6 = this.uvs6;
  36889. }
  36890. if (this.colors) {
  36891. serializationObject.colors = this.colors;
  36892. }
  36893. if (this.matricesIndices) {
  36894. serializationObject.matricesIndices = this.matricesIndices;
  36895. serializationObject.matricesIndices._isExpanded = true;
  36896. }
  36897. if (this.matricesWeights) {
  36898. serializationObject.matricesWeights = this.matricesWeights;
  36899. }
  36900. if (this.matricesIndicesExtra) {
  36901. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36902. serializationObject.matricesIndicesExtra._isExpanded = true;
  36903. }
  36904. if (this.matricesWeightsExtra) {
  36905. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36906. }
  36907. serializationObject.indices = this.indices;
  36908. return serializationObject;
  36909. };
  36910. // Statics
  36911. /**
  36912. * Extracts the vertexData from a mesh
  36913. * @param mesh the mesh from which to extract the VertexData
  36914. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36915. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36916. * @returns the object VertexData associated to the passed mesh
  36917. */
  36918. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36919. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36920. };
  36921. /**
  36922. * Extracts the vertexData from the geometry
  36923. * @param geometry the geometry from which to extract the VertexData
  36924. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36925. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36926. * @returns the object VertexData associated to the passed mesh
  36927. */
  36928. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36929. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36930. };
  36931. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36932. var result = new VertexData();
  36933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36934. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36935. }
  36936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36937. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36938. }
  36939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36940. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36941. }
  36942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36943. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36944. }
  36945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36946. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36947. }
  36948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36949. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36950. }
  36951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36952. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36953. }
  36954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36955. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36956. }
  36957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36958. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36959. }
  36960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36961. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36962. }
  36963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36964. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36965. }
  36966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36967. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36968. }
  36969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36970. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36971. }
  36972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36973. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36974. }
  36975. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36976. return result;
  36977. };
  36978. /**
  36979. * Creates the VertexData for a Ribbon
  36980. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36981. * * pathArray array of paths, each of which an array of successive Vector3
  36982. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36983. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36984. * * 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
  36985. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36986. * * 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)
  36987. * * 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)
  36988. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36989. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36990. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36991. * @returns the VertexData of the ribbon
  36992. */
  36993. VertexData.CreateRibbon = function (options) {
  36994. var pathArray = options.pathArray;
  36995. var closeArray = options.closeArray || false;
  36996. var closePath = options.closePath || false;
  36997. var invertUV = options.invertUV || false;
  36998. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36999. var offset = options.offset || defaultOffset;
  37000. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37001. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37002. var customUV = options.uvs;
  37003. var customColors = options.colors;
  37004. var positions = [];
  37005. var indices = [];
  37006. var normals = [];
  37007. var uvs = [];
  37008. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37009. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37010. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37011. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37012. var minlg; // minimal length among all paths from pathArray
  37013. var lg = []; // array of path lengths : nb of vertex per path
  37014. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37015. var p; // path iterator
  37016. var i; // point iterator
  37017. var j; // point iterator
  37018. // if single path in pathArray
  37019. if (pathArray.length < 2) {
  37020. var ar1 = [];
  37021. var ar2 = [];
  37022. for (i = 0; i < pathArray[0].length - offset; i++) {
  37023. ar1.push(pathArray[0][i]);
  37024. ar2.push(pathArray[0][i + offset]);
  37025. }
  37026. pathArray = [ar1, ar2];
  37027. }
  37028. // positions and horizontal distances (u)
  37029. var idc = 0;
  37030. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37031. var path;
  37032. var l;
  37033. minlg = pathArray[0].length;
  37034. var vectlg;
  37035. var dist;
  37036. for (p = 0; p < pathArray.length; p++) {
  37037. uTotalDistance[p] = 0;
  37038. us[p] = [0];
  37039. path = pathArray[p];
  37040. l = path.length;
  37041. minlg = (minlg < l) ? minlg : l;
  37042. j = 0;
  37043. while (j < l) {
  37044. positions.push(path[j].x, path[j].y, path[j].z);
  37045. if (j > 0) {
  37046. vectlg = path[j].subtract(path[j - 1]).length();
  37047. dist = vectlg + uTotalDistance[p];
  37048. us[p].push(dist);
  37049. uTotalDistance[p] = dist;
  37050. }
  37051. j++;
  37052. }
  37053. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37054. j--;
  37055. positions.push(path[0].x, path[0].y, path[0].z);
  37056. vectlg = path[j].subtract(path[0]).length();
  37057. dist = vectlg + uTotalDistance[p];
  37058. us[p].push(dist);
  37059. uTotalDistance[p] = dist;
  37060. }
  37061. lg[p] = l + closePathCorr;
  37062. idx[p] = idc;
  37063. idc += (l + closePathCorr);
  37064. }
  37065. // vertical distances (v)
  37066. var path1;
  37067. var path2;
  37068. var vertex1 = null;
  37069. var vertex2 = null;
  37070. for (i = 0; i < minlg + closePathCorr; i++) {
  37071. vTotalDistance[i] = 0;
  37072. vs[i] = [0];
  37073. for (p = 0; p < pathArray.length - 1; p++) {
  37074. path1 = pathArray[p];
  37075. path2 = pathArray[p + 1];
  37076. if (i === minlg) { // closePath
  37077. vertex1 = path1[0];
  37078. vertex2 = path2[0];
  37079. }
  37080. else {
  37081. vertex1 = path1[i];
  37082. vertex2 = path2[i];
  37083. }
  37084. vectlg = vertex2.subtract(vertex1).length();
  37085. dist = vectlg + vTotalDistance[i];
  37086. vs[i].push(dist);
  37087. vTotalDistance[i] = dist;
  37088. }
  37089. if (closeArray && vertex2 && vertex1) {
  37090. path1 = pathArray[p];
  37091. path2 = pathArray[0];
  37092. if (i === minlg) { // closePath
  37093. vertex2 = path2[0];
  37094. }
  37095. vectlg = vertex2.subtract(vertex1).length();
  37096. dist = vectlg + vTotalDistance[i];
  37097. vTotalDistance[i] = dist;
  37098. }
  37099. }
  37100. // uvs
  37101. var u;
  37102. var v;
  37103. if (customUV) {
  37104. for (p = 0; p < customUV.length; p++) {
  37105. uvs.push(customUV[p].x, customUV[p].y);
  37106. }
  37107. }
  37108. else {
  37109. for (p = 0; p < pathArray.length; p++) {
  37110. for (i = 0; i < minlg + closePathCorr; i++) {
  37111. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37112. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37113. if (invertUV) {
  37114. uvs.push(v, u);
  37115. }
  37116. else {
  37117. uvs.push(u, v);
  37118. }
  37119. }
  37120. }
  37121. }
  37122. // indices
  37123. p = 0; // path index
  37124. var pi = 0; // positions array index
  37125. var l1 = lg[p] - 1; // path1 length
  37126. var l2 = lg[p + 1] - 1; // path2 length
  37127. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37128. var shft = idx[1] - idx[0]; // shift
  37129. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37130. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37131. // 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
  37132. indices.push(pi, pi + shft, pi + 1);
  37133. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37134. pi += 1;
  37135. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37136. p++;
  37137. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37138. shft = idx[0] - idx[p];
  37139. l1 = lg[p] - 1;
  37140. l2 = lg[0] - 1;
  37141. }
  37142. else {
  37143. shft = idx[p + 1] - idx[p];
  37144. l1 = lg[p] - 1;
  37145. l2 = lg[p + 1] - 1;
  37146. }
  37147. pi = idx[p];
  37148. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37149. }
  37150. }
  37151. // normals
  37152. VertexData.ComputeNormals(positions, indices, normals);
  37153. if (closePath) { // update both the first and last vertex normals to their average value
  37154. var indexFirst = 0;
  37155. var indexLast = 0;
  37156. for (p = 0; p < pathArray.length; p++) {
  37157. indexFirst = idx[p] * 3;
  37158. if (p + 1 < pathArray.length) {
  37159. indexLast = (idx[p + 1] - 1) * 3;
  37160. }
  37161. else {
  37162. indexLast = normals.length - 3;
  37163. }
  37164. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37165. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37166. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37167. normals[indexLast] = normals[indexFirst];
  37168. normals[indexLast + 1] = normals[indexFirst + 1];
  37169. normals[indexLast + 2] = normals[indexFirst + 2];
  37170. }
  37171. }
  37172. // sides
  37173. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37174. // Colors
  37175. var colors = null;
  37176. if (customColors) {
  37177. colors = new Float32Array(customColors.length * 4);
  37178. for (var c = 0; c < customColors.length; c++) {
  37179. colors[c * 4] = customColors[c].r;
  37180. colors[c * 4 + 1] = customColors[c].g;
  37181. colors[c * 4 + 2] = customColors[c].b;
  37182. colors[c * 4 + 3] = customColors[c].a;
  37183. }
  37184. }
  37185. // Result
  37186. var vertexData = new VertexData();
  37187. var positions32 = new Float32Array(positions);
  37188. var normals32 = new Float32Array(normals);
  37189. var uvs32 = new Float32Array(uvs);
  37190. vertexData.indices = indices;
  37191. vertexData.positions = positions32;
  37192. vertexData.normals = normals32;
  37193. vertexData.uvs = uvs32;
  37194. if (colors) {
  37195. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37196. }
  37197. if (closePath) {
  37198. vertexData._idx = idx;
  37199. }
  37200. return vertexData;
  37201. };
  37202. /**
  37203. * Creates the VertexData for a box
  37204. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37205. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37206. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37207. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37208. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37209. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37210. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37211. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37212. * * 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)
  37213. * * 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)
  37214. * @returns the VertexData of the box
  37215. */
  37216. VertexData.CreateBox = function (options) {
  37217. var normalsSource = [
  37218. new BABYLON.Vector3(0, 0, 1),
  37219. new BABYLON.Vector3(0, 0, -1),
  37220. new BABYLON.Vector3(1, 0, 0),
  37221. new BABYLON.Vector3(-1, 0, 0),
  37222. new BABYLON.Vector3(0, 1, 0),
  37223. new BABYLON.Vector3(0, -1, 0)
  37224. ];
  37225. var indices = [];
  37226. var positions = [];
  37227. var normals = [];
  37228. var uvs = [];
  37229. var width = options.width || options.size || 1;
  37230. var height = options.height || options.size || 1;
  37231. var depth = options.depth || options.size || 1;
  37232. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37233. var faceUV = options.faceUV || new Array(6);
  37234. var faceColors = options.faceColors;
  37235. var colors = [];
  37236. // default face colors and UV if undefined
  37237. for (var f = 0; f < 6; f++) {
  37238. if (faceUV[f] === undefined) {
  37239. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37240. }
  37241. if (faceColors && faceColors[f] === undefined) {
  37242. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37243. }
  37244. }
  37245. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37246. // Create each face in turn.
  37247. for (var index = 0; index < normalsSource.length; index++) {
  37248. var normal = normalsSource[index];
  37249. // Get two vectors perpendicular to the face normal and to each other.
  37250. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37251. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37252. // Six indices (two triangles) per face.
  37253. var verticesLength = positions.length / 3;
  37254. indices.push(verticesLength);
  37255. indices.push(verticesLength + 1);
  37256. indices.push(verticesLength + 2);
  37257. indices.push(verticesLength);
  37258. indices.push(verticesLength + 2);
  37259. indices.push(verticesLength + 3);
  37260. // Four vertices per face.
  37261. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37262. positions.push(vertex.x, vertex.y, vertex.z);
  37263. normals.push(normal.x, normal.y, normal.z);
  37264. uvs.push(faceUV[index].z, faceUV[index].w);
  37265. if (faceColors) {
  37266. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37267. }
  37268. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37269. positions.push(vertex.x, vertex.y, vertex.z);
  37270. normals.push(normal.x, normal.y, normal.z);
  37271. uvs.push(faceUV[index].x, faceUV[index].w);
  37272. if (faceColors) {
  37273. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37274. }
  37275. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37276. positions.push(vertex.x, vertex.y, vertex.z);
  37277. normals.push(normal.x, normal.y, normal.z);
  37278. uvs.push(faceUV[index].x, faceUV[index].y);
  37279. if (faceColors) {
  37280. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37281. }
  37282. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37283. positions.push(vertex.x, vertex.y, vertex.z);
  37284. normals.push(normal.x, normal.y, normal.z);
  37285. uvs.push(faceUV[index].z, faceUV[index].y);
  37286. if (faceColors) {
  37287. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37288. }
  37289. }
  37290. // sides
  37291. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37292. // Result
  37293. var vertexData = new VertexData();
  37294. vertexData.indices = indices;
  37295. vertexData.positions = positions;
  37296. vertexData.normals = normals;
  37297. vertexData.uvs = uvs;
  37298. if (faceColors) {
  37299. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37300. vertexData.colors = totalColors;
  37301. }
  37302. return vertexData;
  37303. };
  37304. /**
  37305. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37306. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37307. * * segments sets the number of horizontal strips optional, default 32
  37308. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37309. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37310. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37311. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37312. * * 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
  37313. * * 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
  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 ellipsoid
  37318. */
  37319. VertexData.CreateSphere = function (options) {
  37320. var segments = options.segments || 32;
  37321. var diameterX = options.diameterX || options.diameter || 1;
  37322. var diameterY = options.diameterY || options.diameter || 1;
  37323. var diameterZ = options.diameterZ || options.diameter || 1;
  37324. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37325. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37327. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37328. var totalZRotationSteps = 2 + segments;
  37329. var totalYRotationSteps = 2 * totalZRotationSteps;
  37330. var indices = [];
  37331. var positions = [];
  37332. var normals = [];
  37333. var uvs = [];
  37334. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37335. var normalizedZ = zRotationStep / totalZRotationSteps;
  37336. var angleZ = normalizedZ * Math.PI * slice;
  37337. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37338. var normalizedY = yRotationStep / totalYRotationSteps;
  37339. var angleY = normalizedY * Math.PI * 2 * arc;
  37340. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37341. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37342. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37343. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37344. var vertex = complete.multiply(radius);
  37345. var normal = complete.divide(radius).normalize();
  37346. positions.push(vertex.x, vertex.y, vertex.z);
  37347. normals.push(normal.x, normal.y, normal.z);
  37348. uvs.push(normalizedY, normalizedZ);
  37349. }
  37350. if (zRotationStep > 0) {
  37351. var verticesCount = positions.length / 3;
  37352. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37353. indices.push((firstIndex));
  37354. indices.push((firstIndex + 1));
  37355. indices.push(firstIndex + totalYRotationSteps + 1);
  37356. indices.push((firstIndex + totalYRotationSteps + 1));
  37357. indices.push((firstIndex + 1));
  37358. indices.push((firstIndex + totalYRotationSteps + 2));
  37359. }
  37360. }
  37361. }
  37362. // Sides
  37363. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37364. // Result
  37365. var vertexData = new VertexData();
  37366. vertexData.indices = indices;
  37367. vertexData.positions = positions;
  37368. vertexData.normals = normals;
  37369. vertexData.uvs = uvs;
  37370. return vertexData;
  37371. };
  37372. /**
  37373. * Creates the VertexData for a cylinder, cone or prism
  37374. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37375. * * height sets the height (y direction) of the cylinder, optional, default 2
  37376. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37377. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37378. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37379. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37380. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37381. * * 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
  37382. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37383. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37384. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37385. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37386. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37387. * * 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)
  37388. * * 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)
  37389. * @returns the VertexData of the cylinder, cone or prism
  37390. */
  37391. VertexData.CreateCylinder = function (options) {
  37392. var height = options.height || 2;
  37393. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37394. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37395. var tessellation = options.tessellation || 24;
  37396. var subdivisions = options.subdivisions || 1;
  37397. var hasRings = options.hasRings ? true : false;
  37398. var enclose = options.enclose ? true : false;
  37399. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37400. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37401. var faceUV = options.faceUV || new Array(3);
  37402. var faceColors = options.faceColors;
  37403. // default face colors and UV if undefined
  37404. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37405. var ringNb = (hasRings) ? subdivisions : 1;
  37406. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37407. var f;
  37408. for (f = 0; f < surfaceNb; f++) {
  37409. if (faceColors && faceColors[f] === undefined) {
  37410. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37411. }
  37412. }
  37413. for (f = 0; f < surfaceNb; f++) {
  37414. if (faceUV && faceUV[f] === undefined) {
  37415. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37416. }
  37417. }
  37418. var indices = new Array();
  37419. var positions = new Array();
  37420. var normals = new Array();
  37421. var uvs = new Array();
  37422. var colors = new Array();
  37423. var angle_step = Math.PI * 2 * arc / tessellation;
  37424. var angle;
  37425. var h;
  37426. var radius;
  37427. var tan = (diameterBottom - diameterTop) / 2 / height;
  37428. var ringVertex = BABYLON.Vector3.Zero();
  37429. var ringNormal = BABYLON.Vector3.Zero();
  37430. var ringFirstVertex = BABYLON.Vector3.Zero();
  37431. var ringFirstNormal = BABYLON.Vector3.Zero();
  37432. var quadNormal = BABYLON.Vector3.Zero();
  37433. var Y = BABYLON.Axis.Y;
  37434. // positions, normals, uvs
  37435. var i;
  37436. var j;
  37437. var r;
  37438. var ringIdx = 1;
  37439. var s = 1; // surface index
  37440. var cs = 0;
  37441. var v = 0;
  37442. for (i = 0; i <= subdivisions; i++) {
  37443. h = i / subdivisions;
  37444. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37445. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37446. for (r = 0; r < ringIdx; r++) {
  37447. if (hasRings) {
  37448. s += r;
  37449. }
  37450. if (enclose) {
  37451. s += 2 * r;
  37452. }
  37453. for (j = 0; j <= tessellation; j++) {
  37454. angle = j * angle_step;
  37455. // position
  37456. ringVertex.x = Math.cos(-angle) * radius;
  37457. ringVertex.y = -height / 2 + h * height;
  37458. ringVertex.z = Math.sin(-angle) * radius;
  37459. // normal
  37460. if (diameterTop === 0 && i === subdivisions) {
  37461. // if no top cap, reuse former normals
  37462. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37463. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37464. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37465. }
  37466. else {
  37467. ringNormal.x = ringVertex.x;
  37468. ringNormal.z = ringVertex.z;
  37469. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37470. ringNormal.normalize();
  37471. }
  37472. // keep first ring vertex values for enclose
  37473. if (j === 0) {
  37474. ringFirstVertex.copyFrom(ringVertex);
  37475. ringFirstNormal.copyFrom(ringNormal);
  37476. }
  37477. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37478. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37479. if (hasRings) {
  37480. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37481. }
  37482. else {
  37483. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37484. }
  37485. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37486. if (faceColors) {
  37487. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37488. }
  37489. }
  37490. // if enclose, add four vertices and their dedicated normals
  37491. if (arc !== 1 && enclose) {
  37492. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37493. positions.push(0, ringVertex.y, 0);
  37494. positions.push(0, ringVertex.y, 0);
  37495. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37496. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37497. quadNormal.normalize();
  37498. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37499. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37500. quadNormal.normalize();
  37501. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37502. if (hasRings) {
  37503. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37504. }
  37505. else {
  37506. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37507. }
  37508. uvs.push(faceUV[s + 1].x, v);
  37509. uvs.push(faceUV[s + 1].z, v);
  37510. if (hasRings) {
  37511. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37512. }
  37513. else {
  37514. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37515. }
  37516. uvs.push(faceUV[s + 2].x, v);
  37517. uvs.push(faceUV[s + 2].z, v);
  37518. if (faceColors) {
  37519. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37520. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37521. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37522. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37523. }
  37524. }
  37525. if (cs !== s) {
  37526. cs = s;
  37527. }
  37528. }
  37529. }
  37530. // indices
  37531. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37532. var s;
  37533. i = 0;
  37534. for (s = 0; s < subdivisions; s++) {
  37535. var i0 = 0;
  37536. var i1 = 0;
  37537. var i2 = 0;
  37538. var i3 = 0;
  37539. for (j = 0; j < tessellation; j++) {
  37540. i0 = i * (e + 1) + j;
  37541. i1 = (i + 1) * (e + 1) + j;
  37542. i2 = i * (e + 1) + (j + 1);
  37543. i3 = (i + 1) * (e + 1) + (j + 1);
  37544. indices.push(i0, i1, i2);
  37545. indices.push(i3, i2, i1);
  37546. }
  37547. if (arc !== 1 && enclose) { // if enclose, add two quads
  37548. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37549. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37550. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37551. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37552. }
  37553. i = (hasRings) ? (i + 2) : (i + 1);
  37554. }
  37555. // Caps
  37556. var createCylinderCap = function (isTop) {
  37557. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37558. if (radius === 0) {
  37559. return;
  37560. }
  37561. // Cap positions, normals & uvs
  37562. var angle;
  37563. var circleVector;
  37564. var i;
  37565. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37566. var c = null;
  37567. if (faceColors) {
  37568. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37569. }
  37570. // cap center
  37571. var vbase = positions.length / 3;
  37572. var offset = isTop ? height / 2 : -height / 2;
  37573. var center = new BABYLON.Vector3(0, offset, 0);
  37574. positions.push(center.x, center.y, center.z);
  37575. normals.push(0, isTop ? 1 : -1, 0);
  37576. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37577. if (c) {
  37578. colors.push(c.r, c.g, c.b, c.a);
  37579. }
  37580. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37581. for (i = 0; i <= tessellation; i++) {
  37582. angle = Math.PI * 2 * i * arc / tessellation;
  37583. var cos = Math.cos(-angle);
  37584. var sin = Math.sin(-angle);
  37585. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37586. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37587. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37588. normals.push(0, isTop ? 1 : -1, 0);
  37589. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37590. if (c) {
  37591. colors.push(c.r, c.g, c.b, c.a);
  37592. }
  37593. }
  37594. // Cap indices
  37595. for (i = 0; i < tessellation; i++) {
  37596. if (!isTop) {
  37597. indices.push(vbase);
  37598. indices.push(vbase + (i + 1));
  37599. indices.push(vbase + (i + 2));
  37600. }
  37601. else {
  37602. indices.push(vbase);
  37603. indices.push(vbase + (i + 2));
  37604. indices.push(vbase + (i + 1));
  37605. }
  37606. }
  37607. };
  37608. // add caps to geometry
  37609. createCylinderCap(false);
  37610. createCylinderCap(true);
  37611. // Sides
  37612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37613. var vertexData = new VertexData();
  37614. vertexData.indices = indices;
  37615. vertexData.positions = positions;
  37616. vertexData.normals = normals;
  37617. vertexData.uvs = uvs;
  37618. if (faceColors) {
  37619. vertexData.colors = colors;
  37620. }
  37621. return vertexData;
  37622. };
  37623. /**
  37624. * Creates the VertexData for a torus
  37625. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37626. * * diameter the diameter of the torus, optional default 1
  37627. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37628. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37629. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37630. * * 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)
  37631. * * 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)
  37632. * @returns the VertexData of the torus
  37633. */
  37634. VertexData.CreateTorus = function (options) {
  37635. var indices = [];
  37636. var positions = [];
  37637. var normals = [];
  37638. var uvs = [];
  37639. var diameter = options.diameter || 1;
  37640. var thickness = options.thickness || 0.5;
  37641. var tessellation = options.tessellation || 16;
  37642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37643. var stride = tessellation + 1;
  37644. for (var i = 0; i <= tessellation; i++) {
  37645. var u = i / tessellation;
  37646. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37647. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37648. for (var j = 0; j <= tessellation; j++) {
  37649. var v = 1 - j / tessellation;
  37650. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37651. var dx = Math.cos(innerAngle);
  37652. var dy = Math.sin(innerAngle);
  37653. // Create a vertex.
  37654. var normal = new BABYLON.Vector3(dx, dy, 0);
  37655. var position = normal.scale(thickness / 2);
  37656. var textureCoordinate = new BABYLON.Vector2(u, v);
  37657. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37658. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37659. positions.push(position.x, position.y, position.z);
  37660. normals.push(normal.x, normal.y, normal.z);
  37661. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37662. // And create indices for two triangles.
  37663. var nextI = (i + 1) % stride;
  37664. var nextJ = (j + 1) % stride;
  37665. indices.push(i * stride + j);
  37666. indices.push(i * stride + nextJ);
  37667. indices.push(nextI * stride + j);
  37668. indices.push(i * stride + nextJ);
  37669. indices.push(nextI * stride + nextJ);
  37670. indices.push(nextI * stride + j);
  37671. }
  37672. }
  37673. // Sides
  37674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37675. // Result
  37676. var vertexData = new VertexData();
  37677. vertexData.indices = indices;
  37678. vertexData.positions = positions;
  37679. vertexData.normals = normals;
  37680. vertexData.uvs = uvs;
  37681. return vertexData;
  37682. };
  37683. /**
  37684. * Creates the VertexData of the LineSystem
  37685. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37686. * - lines an array of lines, each line being an array of successive Vector3
  37687. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37688. * @returns the VertexData of the LineSystem
  37689. */
  37690. VertexData.CreateLineSystem = function (options) {
  37691. var indices = [];
  37692. var positions = [];
  37693. var lines = options.lines;
  37694. var colors = options.colors;
  37695. var vertexColors = [];
  37696. var idx = 0;
  37697. for (var l = 0; l < lines.length; l++) {
  37698. var points = lines[l];
  37699. for (var index = 0; index < points.length; index++) {
  37700. positions.push(points[index].x, points[index].y, points[index].z);
  37701. if (colors) {
  37702. var color = colors[l];
  37703. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37704. }
  37705. if (index > 0) {
  37706. indices.push(idx - 1);
  37707. indices.push(idx);
  37708. }
  37709. idx++;
  37710. }
  37711. }
  37712. var vertexData = new VertexData();
  37713. vertexData.indices = indices;
  37714. vertexData.positions = positions;
  37715. if (colors) {
  37716. vertexData.colors = vertexColors;
  37717. }
  37718. return vertexData;
  37719. };
  37720. /**
  37721. * Create the VertexData for a DashedLines
  37722. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37723. * - points an array successive Vector3
  37724. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37725. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37726. * - dashNb the intended total number of dashes, optional, default 200
  37727. * @returns the VertexData for the DashedLines
  37728. */
  37729. VertexData.CreateDashedLines = function (options) {
  37730. var dashSize = options.dashSize || 3;
  37731. var gapSize = options.gapSize || 1;
  37732. var dashNb = options.dashNb || 200;
  37733. var points = options.points;
  37734. var positions = new Array();
  37735. var indices = new Array();
  37736. var curvect = BABYLON.Vector3.Zero();
  37737. var lg = 0;
  37738. var nb = 0;
  37739. var shft = 0;
  37740. var dashshft = 0;
  37741. var curshft = 0;
  37742. var idx = 0;
  37743. var i = 0;
  37744. for (i = 0; i < points.length - 1; i++) {
  37745. points[i + 1].subtractToRef(points[i], curvect);
  37746. lg += curvect.length();
  37747. }
  37748. shft = lg / dashNb;
  37749. dashshft = dashSize * shft / (dashSize + gapSize);
  37750. for (i = 0; i < points.length - 1; i++) {
  37751. points[i + 1].subtractToRef(points[i], curvect);
  37752. nb = Math.floor(curvect.length() / shft);
  37753. curvect.normalize();
  37754. for (var j = 0; j < nb; j++) {
  37755. curshft = shft * j;
  37756. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37757. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37758. indices.push(idx, idx + 1);
  37759. idx += 2;
  37760. }
  37761. }
  37762. // Result
  37763. var vertexData = new VertexData();
  37764. vertexData.positions = positions;
  37765. vertexData.indices = indices;
  37766. return vertexData;
  37767. };
  37768. /**
  37769. * Creates the VertexData for a Ground
  37770. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37771. * - width the width (x direction) of the ground, optional, default 1
  37772. * - height the height (z direction) of the ground, optional, default 1
  37773. * - subdivisions the number of subdivisions per side, optional, default 1
  37774. * @returns the VertexData of the Ground
  37775. */
  37776. VertexData.CreateGround = function (options) {
  37777. var indices = [];
  37778. var positions = [];
  37779. var normals = [];
  37780. var uvs = [];
  37781. var row, col;
  37782. var width = options.width || 1;
  37783. var height = options.height || 1;
  37784. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37785. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37786. for (row = 0; row <= subdivisionsY; row++) {
  37787. for (col = 0; col <= subdivisionsX; col++) {
  37788. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37789. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37790. positions.push(position.x, position.y, position.z);
  37791. normals.push(normal.x, normal.y, normal.z);
  37792. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37793. }
  37794. }
  37795. for (row = 0; row < subdivisionsY; row++) {
  37796. for (col = 0; col < subdivisionsX; col++) {
  37797. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37798. indices.push(col + 1 + row * (subdivisionsX + 1));
  37799. indices.push(col + row * (subdivisionsX + 1));
  37800. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37801. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37802. indices.push(col + row * (subdivisionsX + 1));
  37803. }
  37804. }
  37805. // Result
  37806. var vertexData = new VertexData();
  37807. vertexData.indices = indices;
  37808. vertexData.positions = positions;
  37809. vertexData.normals = normals;
  37810. vertexData.uvs = uvs;
  37811. return vertexData;
  37812. };
  37813. /**
  37814. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37815. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37816. * * xmin the ground minimum X coordinate, optional, default -1
  37817. * * zmin the ground minimum Z coordinate, optional, default -1
  37818. * * xmax the ground maximum X coordinate, optional, default 1
  37819. * * zmax the ground maximum Z coordinate, optional, default 1
  37820. * * 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}
  37821. * * 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}
  37822. * @returns the VertexData of the TiledGround
  37823. */
  37824. VertexData.CreateTiledGround = function (options) {
  37825. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37826. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37827. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37828. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37829. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37830. var precision = options.precision || { w: 1, h: 1 };
  37831. var indices = new Array();
  37832. var positions = new Array();
  37833. var normals = new Array();
  37834. var uvs = new Array();
  37835. var row, col, tileRow, tileCol;
  37836. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37837. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37838. precision.w = (precision.w < 1) ? 1 : precision.w;
  37839. precision.h = (precision.h < 1) ? 1 : precision.h;
  37840. var tileSize = {
  37841. 'w': (xmax - xmin) / subdivisions.w,
  37842. 'h': (zmax - zmin) / subdivisions.h
  37843. };
  37844. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37845. // Indices
  37846. var base = positions.length / 3;
  37847. var rowLength = precision.w + 1;
  37848. for (row = 0; row < precision.h; row++) {
  37849. for (col = 0; col < precision.w; col++) {
  37850. var square = [
  37851. base + col + row * rowLength,
  37852. base + (col + 1) + row * rowLength,
  37853. base + (col + 1) + (row + 1) * rowLength,
  37854. base + col + (row + 1) * rowLength
  37855. ];
  37856. indices.push(square[1]);
  37857. indices.push(square[2]);
  37858. indices.push(square[3]);
  37859. indices.push(square[0]);
  37860. indices.push(square[1]);
  37861. indices.push(square[3]);
  37862. }
  37863. }
  37864. // Position, normals and uvs
  37865. var position = BABYLON.Vector3.Zero();
  37866. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37867. for (row = 0; row <= precision.h; row++) {
  37868. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37869. for (col = 0; col <= precision.w; col++) {
  37870. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37871. position.y = 0;
  37872. positions.push(position.x, position.y, position.z);
  37873. normals.push(normal.x, normal.y, normal.z);
  37874. uvs.push(col / precision.w, row / precision.h);
  37875. }
  37876. }
  37877. }
  37878. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37879. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37880. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37881. }
  37882. }
  37883. // Result
  37884. var vertexData = new VertexData();
  37885. vertexData.indices = indices;
  37886. vertexData.positions = positions;
  37887. vertexData.normals = normals;
  37888. vertexData.uvs = uvs;
  37889. return vertexData;
  37890. };
  37891. /**
  37892. * Creates the VertexData of the Ground designed from a heightmap
  37893. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37894. * * width the width (x direction) of the ground
  37895. * * height the height (z direction) of the ground
  37896. * * subdivisions the number of subdivisions per side
  37897. * * minHeight the minimum altitude on the ground, optional, default 0
  37898. * * maxHeight the maximum altitude on the ground, optional default 1
  37899. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37900. * * buffer the array holding the image color data
  37901. * * bufferWidth the width of image
  37902. * * bufferHeight the height of image
  37903. * @returns the VertexData of the Ground designed from a heightmap
  37904. */
  37905. VertexData.CreateGroundFromHeightMap = function (options) {
  37906. var indices = [];
  37907. var positions = [];
  37908. var normals = [];
  37909. var uvs = [];
  37910. var row, col;
  37911. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37912. // Vertices
  37913. for (row = 0; row <= options.subdivisions; row++) {
  37914. for (col = 0; col <= options.subdivisions; col++) {
  37915. 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));
  37916. // Compute height
  37917. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37918. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37919. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37920. var r = options.buffer[pos] / 255.0;
  37921. var g = options.buffer[pos + 1] / 255.0;
  37922. var b = options.buffer[pos + 2] / 255.0;
  37923. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37924. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37925. // Add vertex
  37926. positions.push(position.x, position.y, position.z);
  37927. normals.push(0, 0, 0);
  37928. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37929. }
  37930. }
  37931. // Indices
  37932. for (row = 0; row < options.subdivisions; row++) {
  37933. for (col = 0; col < options.subdivisions; col++) {
  37934. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37935. indices.push(col + 1 + row * (options.subdivisions + 1));
  37936. indices.push(col + row * (options.subdivisions + 1));
  37937. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37938. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37939. indices.push(col + row * (options.subdivisions + 1));
  37940. }
  37941. }
  37942. // Normals
  37943. VertexData.ComputeNormals(positions, indices, normals);
  37944. // Result
  37945. var vertexData = new VertexData();
  37946. vertexData.indices = indices;
  37947. vertexData.positions = positions;
  37948. vertexData.normals = normals;
  37949. vertexData.uvs = uvs;
  37950. return vertexData;
  37951. };
  37952. /**
  37953. * Creates the VertexData for a Plane
  37954. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37955. * * size sets the width and height of the plane to the value of size, optional default 1
  37956. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37957. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37958. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37959. * * 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)
  37960. * * 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)
  37961. * @returns the VertexData of the box
  37962. */
  37963. VertexData.CreatePlane = function (options) {
  37964. var indices = [];
  37965. var positions = [];
  37966. var normals = [];
  37967. var uvs = [];
  37968. var width = options.width || options.size || 1;
  37969. var height = options.height || options.size || 1;
  37970. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37971. // Vertices
  37972. var halfWidth = width / 2.0;
  37973. var halfHeight = height / 2.0;
  37974. positions.push(-halfWidth, -halfHeight, 0);
  37975. normals.push(0, 0, -1.0);
  37976. uvs.push(0.0, 0.0);
  37977. positions.push(halfWidth, -halfHeight, 0);
  37978. normals.push(0, 0, -1.0);
  37979. uvs.push(1.0, 0.0);
  37980. positions.push(halfWidth, halfHeight, 0);
  37981. normals.push(0, 0, -1.0);
  37982. uvs.push(1.0, 1.0);
  37983. positions.push(-halfWidth, halfHeight, 0);
  37984. normals.push(0, 0, -1.0);
  37985. uvs.push(0.0, 1.0);
  37986. // Indices
  37987. indices.push(0);
  37988. indices.push(1);
  37989. indices.push(2);
  37990. indices.push(0);
  37991. indices.push(2);
  37992. indices.push(3);
  37993. // Sides
  37994. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37995. // Result
  37996. var vertexData = new VertexData();
  37997. vertexData.indices = indices;
  37998. vertexData.positions = positions;
  37999. vertexData.normals = normals;
  38000. vertexData.uvs = uvs;
  38001. return vertexData;
  38002. };
  38003. /**
  38004. * Creates the VertexData of the Disc or regular Polygon
  38005. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38006. * * radius the radius of the disc, optional default 0.5
  38007. * * tessellation the number of polygon sides, optional, default 64
  38008. * * 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
  38009. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38010. * * 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)
  38011. * * 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)
  38012. * @returns the VertexData of the box
  38013. */
  38014. VertexData.CreateDisc = function (options) {
  38015. var positions = new Array();
  38016. var indices = new Array();
  38017. var normals = new Array();
  38018. var uvs = new Array();
  38019. var radius = options.radius || 0.5;
  38020. var tessellation = options.tessellation || 64;
  38021. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38022. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38023. // positions and uvs
  38024. positions.push(0, 0, 0); // disc center first
  38025. uvs.push(0.5, 0.5);
  38026. var theta = Math.PI * 2 * arc;
  38027. var step = theta / tessellation;
  38028. for (var a = 0; a < theta; a += step) {
  38029. var x = Math.cos(a);
  38030. var y = Math.sin(a);
  38031. var u = (x + 1) / 2;
  38032. var v = (1 - y) / 2;
  38033. positions.push(radius * x, radius * y, 0);
  38034. uvs.push(u, v);
  38035. }
  38036. if (arc === 1) {
  38037. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38038. uvs.push(uvs[2], uvs[3]);
  38039. }
  38040. //indices
  38041. var vertexNb = positions.length / 3;
  38042. for (var i = 1; i < vertexNb - 1; i++) {
  38043. indices.push(i + 1, 0, i);
  38044. }
  38045. // result
  38046. VertexData.ComputeNormals(positions, indices, normals);
  38047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38048. var vertexData = new VertexData();
  38049. vertexData.indices = indices;
  38050. vertexData.positions = positions;
  38051. vertexData.normals = normals;
  38052. vertexData.uvs = uvs;
  38053. return vertexData;
  38054. };
  38055. /**
  38056. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38057. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38058. * @param polygon a mesh built from polygonTriangulation.build()
  38059. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38060. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38061. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38062. * @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)
  38063. * @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)
  38064. * @returns the VertexData of the Polygon
  38065. */
  38066. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38067. var faceUV = fUV || new Array(3);
  38068. var faceColors = fColors;
  38069. var colors = [];
  38070. // default face colors and UV if undefined
  38071. for (var f = 0; f < 3; f++) {
  38072. if (faceUV[f] === undefined) {
  38073. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38074. }
  38075. if (faceColors && faceColors[f] === undefined) {
  38076. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38077. }
  38078. }
  38079. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38080. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38081. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38082. var indices = polygon.getIndices();
  38083. // set face colours and textures
  38084. var idx = 0;
  38085. var face = 0;
  38086. for (var index = 0; index < normals.length; index += 3) {
  38087. //Edge Face no. 1
  38088. if (Math.abs(normals[index + 1]) < 0.001) {
  38089. face = 1;
  38090. }
  38091. //Top Face no. 0
  38092. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38093. face = 0;
  38094. }
  38095. //Bottom Face no. 2
  38096. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38097. face = 2;
  38098. }
  38099. idx = index / 3;
  38100. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38101. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38102. if (faceColors) {
  38103. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38104. }
  38105. }
  38106. // sides
  38107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38108. // Result
  38109. var vertexData = new VertexData();
  38110. vertexData.indices = indices;
  38111. vertexData.positions = positions;
  38112. vertexData.normals = normals;
  38113. vertexData.uvs = uvs;
  38114. if (faceColors) {
  38115. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38116. vertexData.colors = totalColors;
  38117. }
  38118. return vertexData;
  38119. };
  38120. /**
  38121. * Creates the VertexData of the IcoSphere
  38122. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38123. * * radius the radius of the IcoSphere, optional default 1
  38124. * * radiusX allows stretching in the x direction, optional, default radius
  38125. * * radiusY allows stretching in the y direction, optional, default radius
  38126. * * radiusZ allows stretching in the z direction, optional, default radius
  38127. * * flat when true creates a flat shaded mesh, optional, default true
  38128. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38129. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38130. * * 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)
  38131. * * 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)
  38132. * @returns the VertexData of the IcoSphere
  38133. */
  38134. VertexData.CreateIcoSphere = function (options) {
  38135. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38136. var radius = options.radius || 1;
  38137. var flat = (options.flat === undefined) ? true : options.flat;
  38138. var subdivisions = options.subdivisions || 4;
  38139. var radiusX = options.radiusX || radius;
  38140. var radiusY = options.radiusY || radius;
  38141. var radiusZ = options.radiusZ || radius;
  38142. var t = (1 + Math.sqrt(5)) / 2;
  38143. // 12 vertex x,y,z
  38144. var ico_vertices = [
  38145. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38146. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38147. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38148. ];
  38149. // index of 3 vertex makes a face of icopshere
  38150. var ico_indices = [
  38151. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38152. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38153. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38154. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38155. ];
  38156. // vertex for uv have aliased position, not for UV
  38157. var vertices_unalias_id = [
  38158. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38159. // vertex alias
  38160. 0,
  38161. 2,
  38162. 3,
  38163. 3,
  38164. 3,
  38165. 4,
  38166. 7,
  38167. 8,
  38168. 9,
  38169. 9,
  38170. 10,
  38171. 11 // 23: B + 12
  38172. ];
  38173. // uv as integer step (not pixels !)
  38174. var ico_vertexuv = [
  38175. 5, 1, 3, 1, 6, 4, 0, 0,
  38176. 5, 3, 4, 2, 2, 2, 4, 0,
  38177. 2, 0, 1, 1, 6, 0, 6, 2,
  38178. // vertex alias (for same vertex on different faces)
  38179. 0, 4,
  38180. 3, 3,
  38181. 4, 4,
  38182. 3, 1,
  38183. 4, 2,
  38184. 4, 4,
  38185. 0, 2,
  38186. 1, 1,
  38187. 2, 2,
  38188. 3, 3,
  38189. 1, 3,
  38190. 2, 4 // 23: B + 12
  38191. ];
  38192. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38193. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38194. // First island of uv mapping
  38195. // v = 4h 3+ 2
  38196. // v = 3h 9+ 4
  38197. // v = 2h 9+ 5 B
  38198. // v = 1h 9 1 0
  38199. // v = 0h 3 8 7 A
  38200. // u = 0 1 2 3 4 5 6 *a
  38201. // Second island of uv mapping
  38202. // v = 4h 0+ B+ 4+
  38203. // v = 3h A+ 2+
  38204. // v = 2h 7+ 6 3+
  38205. // v = 1h 8+ 3+
  38206. // v = 0h
  38207. // u = 0 1 2 3 4 5 6 *a
  38208. // Face layout on texture UV mapping
  38209. // ============
  38210. // \ 4 /\ 16 / ======
  38211. // \ / \ / /\ 11 /
  38212. // \/ 7 \/ / \ /
  38213. // ======= / 10 \/
  38214. // /\ 17 /\ =======
  38215. // / \ / \ \ 15 /\
  38216. // / 8 \/ 12 \ \ / \
  38217. // ============ \/ 6 \
  38218. // \ 18 /\ ============
  38219. // \ / \ \ 5 /\ 0 /
  38220. // \/ 13 \ \ / \ /
  38221. // ======= \/ 1 \/
  38222. // =============
  38223. // /\ 19 /\ 2 /\
  38224. // / \ / \ / \
  38225. // / 14 \/ 9 \/ 3 \
  38226. // ===================
  38227. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38228. var ustep = 138 / 1024;
  38229. var vstep = 239 / 1024;
  38230. var uoffset = 60 / 1024;
  38231. var voffset = 26 / 1024;
  38232. // Second island should have margin, not to touch the first island
  38233. // avoid any borderline artefact in pixel rounding
  38234. var island_u_offset = -40 / 1024;
  38235. var island_v_offset = +20 / 1024;
  38236. // face is either island 0 or 1 :
  38237. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38238. var island = [
  38239. 0, 0, 0, 0, 1,
  38240. 0, 0, 1, 1, 0,
  38241. 0, 0, 1, 1, 0,
  38242. 0, 1, 1, 1, 0 // 15 - 19
  38243. ];
  38244. var indices = new Array();
  38245. var positions = new Array();
  38246. var normals = new Array();
  38247. var uvs = new Array();
  38248. var current_indice = 0;
  38249. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38250. var face_vertex_pos = new Array(3);
  38251. var face_vertex_uv = new Array(3);
  38252. var v012;
  38253. for (v012 = 0; v012 < 3; v012++) {
  38254. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38255. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38256. }
  38257. // create all with normals
  38258. for (var face = 0; face < 20; face++) {
  38259. // 3 vertex per face
  38260. for (v012 = 0; v012 < 3; v012++) {
  38261. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38262. var v_id = ico_indices[3 * face + v012];
  38263. // vertex have 3D position (x,y,z)
  38264. 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]);
  38265. // Normalize to get normal, then scale to radius
  38266. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38267. // uv Coordinates from vertex ID
  38268. 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);
  38269. }
  38270. // Subdivide the face (interpolate pos, norm, uv)
  38271. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38272. // - norm is linear interpolation of vertex corner normal
  38273. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38274. // - uv is linear interpolation
  38275. //
  38276. // Topology is as below for sub-divide by 2
  38277. // vertex shown as v0,v1,v2
  38278. // interp index is i1 to progress in range [v0,v1[
  38279. // interp index is i2 to progress in range [v0,v2[
  38280. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38281. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38282. //
  38283. //
  38284. // i2 v2
  38285. // ^ ^
  38286. // / / \
  38287. // / / \
  38288. // / / \
  38289. // / / (0,1) \
  38290. // / #---------\
  38291. // / / \ (0,0)'/ \
  38292. // / / \ / \
  38293. // / / \ / \
  38294. // / / (0,0) \ / (1,0) \
  38295. // / #---------#---------\
  38296. // v0 v1
  38297. //
  38298. // --------------------> i1
  38299. //
  38300. // interp of (i1,i2):
  38301. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38302. // along i1 : lerp(x0,x1, i1/(S-i2))
  38303. //
  38304. // centroid of triangle is needed to get help normal computation
  38305. // (c1,c2) are used for centroid location
  38306. var interp_vertex = function (i1, i2, c1, c2) {
  38307. // vertex is interpolated from
  38308. // - face_vertex_pos[0..2]
  38309. // - face_vertex_uv[0..2]
  38310. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38311. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38312. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38313. pos_interp.normalize();
  38314. var vertex_normal;
  38315. if (flat) {
  38316. // in flat mode, recalculate normal as face centroid normal
  38317. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38318. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38319. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38320. }
  38321. else {
  38322. // in smooth mode, recalculate normal from each single vertex position
  38323. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38324. }
  38325. // Vertex normal need correction due to X,Y,Z radius scaling
  38326. vertex_normal.x /= radiusX;
  38327. vertex_normal.y /= radiusY;
  38328. vertex_normal.z /= radiusZ;
  38329. vertex_normal.normalize();
  38330. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38331. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38332. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38333. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38334. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38335. uvs.push(uv_interp.x, uv_interp.y);
  38336. // push each vertex has member of a face
  38337. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38338. indices.push(current_indice);
  38339. current_indice++;
  38340. };
  38341. for (var i2 = 0; i2 < subdivisions; i2++) {
  38342. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38343. // face : (i1,i2) for /\ :
  38344. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38345. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38346. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38347. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38348. if (i1 + i2 + 1 < subdivisions) {
  38349. // face : (i1,i2)' for \/ :
  38350. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38351. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38352. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38353. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38354. }
  38355. }
  38356. }
  38357. }
  38358. // Sides
  38359. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38360. // Result
  38361. var vertexData = new VertexData();
  38362. vertexData.indices = indices;
  38363. vertexData.positions = positions;
  38364. vertexData.normals = normals;
  38365. vertexData.uvs = uvs;
  38366. return vertexData;
  38367. };
  38368. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38369. /**
  38370. * Creates the VertexData for a Polyhedron
  38371. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38372. * * type provided types are:
  38373. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38374. * * 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)
  38375. * * size the size of the IcoSphere, optional default 1
  38376. * * sizeX allows stretching in the x direction, optional, default size
  38377. * * sizeY allows stretching in the y direction, optional, default size
  38378. * * sizeZ allows stretching in the z direction, optional, default size
  38379. * * 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
  38380. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38381. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38382. * * flat when true creates a flat shaded mesh, optional, default true
  38383. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38384. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38385. * * 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)
  38386. * * 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)
  38387. * @returns the VertexData of the Polyhedron
  38388. */
  38389. VertexData.CreatePolyhedron = function (options) {
  38390. // provided polyhedron types :
  38391. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38392. // 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)
  38393. var polyhedra = [];
  38394. 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]] };
  38395. 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]] };
  38396. polyhedra[2] = {
  38397. 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]],
  38398. 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]]
  38399. };
  38400. polyhedra[3] = {
  38401. 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]],
  38402. 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]]
  38403. };
  38404. polyhedra[4] = {
  38405. 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]],
  38406. 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]]
  38407. };
  38408. 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]] };
  38409. 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]] };
  38410. 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]] };
  38411. 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]] };
  38412. 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]] };
  38413. 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]] };
  38414. 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]] };
  38415. 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]] };
  38416. 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]] };
  38417. polyhedra[14] = {
  38418. 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]],
  38419. 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]]
  38420. };
  38421. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38422. var size = options.size;
  38423. var sizeX = options.sizeX || size || 1;
  38424. var sizeY = options.sizeY || size || 1;
  38425. var sizeZ = options.sizeZ || size || 1;
  38426. var data = options.custom || polyhedra[type];
  38427. var nbfaces = data.face.length;
  38428. var faceUV = options.faceUV || new Array(nbfaces);
  38429. var faceColors = options.faceColors;
  38430. var flat = (options.flat === undefined) ? true : options.flat;
  38431. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38432. var positions = new Array();
  38433. var indices = new Array();
  38434. var normals = new Array();
  38435. var uvs = new Array();
  38436. var colors = new Array();
  38437. var index = 0;
  38438. var faceIdx = 0; // face cursor in the array "indexes"
  38439. var indexes = new Array();
  38440. var i = 0;
  38441. var f = 0;
  38442. var u, v, ang, x, y, tmp;
  38443. // default face colors and UV if undefined
  38444. if (flat) {
  38445. for (f = 0; f < nbfaces; f++) {
  38446. if (faceColors && faceColors[f] === undefined) {
  38447. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38448. }
  38449. if (faceUV && faceUV[f] === undefined) {
  38450. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38451. }
  38452. }
  38453. }
  38454. if (!flat) {
  38455. for (i = 0; i < data.vertex.length; i++) {
  38456. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38457. uvs.push(0, 0);
  38458. }
  38459. for (f = 0; f < nbfaces; f++) {
  38460. for (i = 0; i < data.face[f].length - 2; i++) {
  38461. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38462. }
  38463. }
  38464. }
  38465. else {
  38466. for (f = 0; f < nbfaces; f++) {
  38467. var fl = data.face[f].length; // number of vertices of the current face
  38468. ang = 2 * Math.PI / fl;
  38469. x = 0.5 * Math.tan(ang / 2);
  38470. y = 0.5;
  38471. // positions, uvs, colors
  38472. for (i = 0; i < fl; i++) {
  38473. // positions
  38474. 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);
  38475. indexes.push(index);
  38476. index++;
  38477. // uvs
  38478. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38479. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38480. uvs.push(u, v);
  38481. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38482. y = x * Math.sin(ang) + y * Math.cos(ang);
  38483. x = tmp;
  38484. // colors
  38485. if (faceColors) {
  38486. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38487. }
  38488. }
  38489. // indices from indexes
  38490. for (i = 0; i < fl - 2; i++) {
  38491. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38492. }
  38493. faceIdx += fl;
  38494. }
  38495. }
  38496. VertexData.ComputeNormals(positions, indices, normals);
  38497. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38498. var vertexData = new VertexData();
  38499. vertexData.positions = positions;
  38500. vertexData.indices = indices;
  38501. vertexData.normals = normals;
  38502. vertexData.uvs = uvs;
  38503. if (faceColors && flat) {
  38504. vertexData.colors = colors;
  38505. }
  38506. return vertexData;
  38507. };
  38508. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38509. /**
  38510. * Creates the VertexData for a TorusKnot
  38511. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38512. * * radius the radius of the torus knot, optional, default 2
  38513. * * tube the thickness of the tube, optional, default 0.5
  38514. * * radialSegments the number of sides on each tube segments, optional, default 32
  38515. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38516. * * p the number of windings around the z axis, optional, default 2
  38517. * * q the number of windings around the x axis, optional, default 3
  38518. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38519. * * 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)
  38520. * * 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)
  38521. * @returns the VertexData of the Torus Knot
  38522. */
  38523. VertexData.CreateTorusKnot = function (options) {
  38524. var indices = new Array();
  38525. var positions = new Array();
  38526. var normals = new Array();
  38527. var uvs = new Array();
  38528. var radius = options.radius || 2;
  38529. var tube = options.tube || 0.5;
  38530. var radialSegments = options.radialSegments || 32;
  38531. var tubularSegments = options.tubularSegments || 32;
  38532. var p = options.p || 2;
  38533. var q = options.q || 3;
  38534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38535. // Helper
  38536. var getPos = function (angle) {
  38537. var cu = Math.cos(angle);
  38538. var su = Math.sin(angle);
  38539. var quOverP = q / p * angle;
  38540. var cs = Math.cos(quOverP);
  38541. var tx = radius * (2 + cs) * 0.5 * cu;
  38542. var ty = radius * (2 + cs) * su * 0.5;
  38543. var tz = radius * Math.sin(quOverP) * 0.5;
  38544. return new BABYLON.Vector3(tx, ty, tz);
  38545. };
  38546. // Vertices
  38547. var i;
  38548. var j;
  38549. for (i = 0; i <= radialSegments; i++) {
  38550. var modI = i % radialSegments;
  38551. var u = modI / radialSegments * 2 * p * Math.PI;
  38552. var p1 = getPos(u);
  38553. var p2 = getPos(u + 0.01);
  38554. var tang = p2.subtract(p1);
  38555. var n = p2.add(p1);
  38556. var bitan = BABYLON.Vector3.Cross(tang, n);
  38557. n = BABYLON.Vector3.Cross(bitan, tang);
  38558. bitan.normalize();
  38559. n.normalize();
  38560. for (j = 0; j < tubularSegments; j++) {
  38561. var modJ = j % tubularSegments;
  38562. var v = modJ / tubularSegments * 2 * Math.PI;
  38563. var cx = -tube * Math.cos(v);
  38564. var cy = tube * Math.sin(v);
  38565. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38566. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38567. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38568. uvs.push(i / radialSegments);
  38569. uvs.push(j / tubularSegments);
  38570. }
  38571. }
  38572. for (i = 0; i < radialSegments; i++) {
  38573. for (j = 0; j < tubularSegments; j++) {
  38574. var jNext = (j + 1) % tubularSegments;
  38575. var a = i * tubularSegments + j;
  38576. var b = (i + 1) * tubularSegments + j;
  38577. var c = (i + 1) * tubularSegments + jNext;
  38578. var d = i * tubularSegments + jNext;
  38579. indices.push(d);
  38580. indices.push(b);
  38581. indices.push(a);
  38582. indices.push(d);
  38583. indices.push(c);
  38584. indices.push(b);
  38585. }
  38586. }
  38587. // Normals
  38588. VertexData.ComputeNormals(positions, indices, normals);
  38589. // Sides
  38590. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38591. // Result
  38592. var vertexData = new VertexData();
  38593. vertexData.indices = indices;
  38594. vertexData.positions = positions;
  38595. vertexData.normals = normals;
  38596. vertexData.uvs = uvs;
  38597. return vertexData;
  38598. };
  38599. // Tools
  38600. /**
  38601. * Compute normals for given positions and indices
  38602. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38603. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38604. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38605. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38606. * * facetNormals : optional array of facet normals (vector3)
  38607. * * facetPositions : optional array of facet positions (vector3)
  38608. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38609. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38610. * * bInfo : optional bounding info, required for facetPartitioning computation
  38611. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38612. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38613. * * useRightHandedSystem: optional boolean to for right handed system computation
  38614. * * depthSort : optional boolean to enable the facet depth sort computation
  38615. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38616. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38617. */
  38618. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38619. // temporary scalar variables
  38620. var index = 0; // facet index
  38621. var p1p2x = 0.0; // p1p2 vector x coordinate
  38622. var p1p2y = 0.0; // p1p2 vector y coordinate
  38623. var p1p2z = 0.0; // p1p2 vector z coordinate
  38624. var p3p2x = 0.0; // p3p2 vector x coordinate
  38625. var p3p2y = 0.0; // p3p2 vector y coordinate
  38626. var p3p2z = 0.0; // p3p2 vector z coordinate
  38627. var faceNormalx = 0.0; // facet normal x coordinate
  38628. var faceNormaly = 0.0; // facet normal y coordinate
  38629. var faceNormalz = 0.0; // facet normal z coordinate
  38630. var length = 0.0; // facet normal length before normalization
  38631. var v1x = 0; // vector1 x index in the positions array
  38632. var v1y = 0; // vector1 y index in the positions array
  38633. var v1z = 0; // vector1 z index in the positions array
  38634. var v2x = 0; // vector2 x index in the positions array
  38635. var v2y = 0; // vector2 y index in the positions array
  38636. var v2z = 0; // vector2 z index in the positions array
  38637. var v3x = 0; // vector3 x index in the positions array
  38638. var v3y = 0; // vector3 y index in the positions array
  38639. var v3z = 0; // vector3 z index in the positions array
  38640. var computeFacetNormals = false;
  38641. var computeFacetPositions = false;
  38642. var computeFacetPartitioning = false;
  38643. var computeDepthSort = false;
  38644. var faceNormalSign = 1;
  38645. var ratio = 0;
  38646. var distanceTo = null;
  38647. if (options) {
  38648. computeFacetNormals = (options.facetNormals) ? true : false;
  38649. computeFacetPositions = (options.facetPositions) ? true : false;
  38650. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38651. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38652. ratio = options.ratio || 0;
  38653. computeDepthSort = (options.depthSort) ? true : false;
  38654. distanceTo = (options.distanceTo);
  38655. if (computeDepthSort) {
  38656. if (distanceTo === undefined) {
  38657. distanceTo = BABYLON.Vector3.Zero();
  38658. }
  38659. var depthSortedFacets = options.depthSortedFacets;
  38660. }
  38661. }
  38662. // facetPartitioning reinit if needed
  38663. var xSubRatio = 0;
  38664. var ySubRatio = 0;
  38665. var zSubRatio = 0;
  38666. var subSq = 0;
  38667. if (computeFacetPartitioning && options && options.bbSize) {
  38668. var ox = 0; // X partitioning index for facet position
  38669. var oy = 0; // Y partinioning index for facet position
  38670. var oz = 0; // Z partinioning index for facet position
  38671. var b1x = 0; // X partitioning index for facet v1 vertex
  38672. var b1y = 0; // Y partitioning index for facet v1 vertex
  38673. var b1z = 0; // z partitioning index for facet v1 vertex
  38674. var b2x = 0; // X partitioning index for facet v2 vertex
  38675. var b2y = 0; // Y partitioning index for facet v2 vertex
  38676. var b2z = 0; // Z partitioning index for facet v2 vertex
  38677. var b3x = 0; // X partitioning index for facet v3 vertex
  38678. var b3y = 0; // Y partitioning index for facet v3 vertex
  38679. var b3z = 0; // Z partitioning index for facet v3 vertex
  38680. var block_idx_o = 0; // facet barycenter block index
  38681. var block_idx_v1 = 0; // v1 vertex block index
  38682. var block_idx_v2 = 0; // v2 vertex block index
  38683. var block_idx_v3 = 0; // v3 vertex block index
  38684. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38685. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38686. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38687. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38688. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38689. subSq = options.subDiv.max * options.subDiv.max;
  38690. options.facetPartitioning.length = 0;
  38691. }
  38692. // reset the normals
  38693. for (index = 0; index < positions.length; index++) {
  38694. normals[index] = 0.0;
  38695. }
  38696. // Loop : 1 indice triplet = 1 facet
  38697. var nbFaces = (indices.length / 3) | 0;
  38698. for (index = 0; index < nbFaces; index++) {
  38699. // get the indexes of the coordinates of each vertex of the facet
  38700. v1x = indices[index * 3] * 3;
  38701. v1y = v1x + 1;
  38702. v1z = v1x + 2;
  38703. v2x = indices[index * 3 + 1] * 3;
  38704. v2y = v2x + 1;
  38705. v2z = v2x + 2;
  38706. v3x = indices[index * 3 + 2] * 3;
  38707. v3y = v3x + 1;
  38708. v3z = v3x + 2;
  38709. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38710. p1p2y = positions[v1y] - positions[v2y];
  38711. p1p2z = positions[v1z] - positions[v2z];
  38712. p3p2x = positions[v3x] - positions[v2x];
  38713. p3p2y = positions[v3y] - positions[v2y];
  38714. p3p2z = positions[v3z] - positions[v2z];
  38715. // compute the face normal with the cross product
  38716. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38717. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38718. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38719. // normalize this normal and store it in the array facetData
  38720. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38721. length = (length === 0) ? 1.0 : length;
  38722. faceNormalx /= length;
  38723. faceNormaly /= length;
  38724. faceNormalz /= length;
  38725. if (computeFacetNormals && options) {
  38726. options.facetNormals[index].x = faceNormalx;
  38727. options.facetNormals[index].y = faceNormaly;
  38728. options.facetNormals[index].z = faceNormalz;
  38729. }
  38730. if (computeFacetPositions && options) {
  38731. // compute and the facet barycenter coordinates in the array facetPositions
  38732. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38733. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38734. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38735. }
  38736. if (computeFacetPartitioning && options) {
  38737. // store the facet indexes in arrays in the main facetPartitioning array :
  38738. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38739. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38740. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38741. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38742. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38743. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38744. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38745. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38746. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38747. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38748. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38749. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38750. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38751. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38752. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38753. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38754. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38755. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38756. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38757. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38758. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38759. // push each facet index in each block containing the vertex
  38760. options.facetPartitioning[block_idx_v1].push(index);
  38761. if (block_idx_v2 != block_idx_v1) {
  38762. options.facetPartitioning[block_idx_v2].push(index);
  38763. }
  38764. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38765. options.facetPartitioning[block_idx_v3].push(index);
  38766. }
  38767. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38768. options.facetPartitioning[block_idx_o].push(index);
  38769. }
  38770. }
  38771. if (computeDepthSort && options && options.facetPositions) {
  38772. var dsf = depthSortedFacets[index];
  38773. dsf.ind = index * 3;
  38774. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38775. }
  38776. // compute the normals anyway
  38777. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38778. normals[v1y] += faceNormaly;
  38779. normals[v1z] += faceNormalz;
  38780. normals[v2x] += faceNormalx;
  38781. normals[v2y] += faceNormaly;
  38782. normals[v2z] += faceNormalz;
  38783. normals[v3x] += faceNormalx;
  38784. normals[v3y] += faceNormaly;
  38785. normals[v3z] += faceNormalz;
  38786. }
  38787. // last normalization of each normal
  38788. for (index = 0; index < normals.length / 3; index++) {
  38789. faceNormalx = normals[index * 3];
  38790. faceNormaly = normals[index * 3 + 1];
  38791. faceNormalz = normals[index * 3 + 2];
  38792. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38793. length = (length === 0) ? 1.0 : length;
  38794. faceNormalx /= length;
  38795. faceNormaly /= length;
  38796. faceNormalz /= length;
  38797. normals[index * 3] = faceNormalx;
  38798. normals[index * 3 + 1] = faceNormaly;
  38799. normals[index * 3 + 2] = faceNormalz;
  38800. }
  38801. };
  38802. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38803. var li = indices.length;
  38804. var ln = normals.length;
  38805. var i;
  38806. var n;
  38807. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38808. switch (sideOrientation) {
  38809. case BABYLON.Mesh.FRONTSIDE:
  38810. // nothing changed
  38811. break;
  38812. case BABYLON.Mesh.BACKSIDE:
  38813. var tmp;
  38814. // indices
  38815. for (i = 0; i < li; i += 3) {
  38816. tmp = indices[i];
  38817. indices[i] = indices[i + 2];
  38818. indices[i + 2] = tmp;
  38819. }
  38820. // normals
  38821. for (n = 0; n < ln; n++) {
  38822. normals[n] = -normals[n];
  38823. }
  38824. break;
  38825. case BABYLON.Mesh.DOUBLESIDE:
  38826. // positions
  38827. var lp = positions.length;
  38828. var l = lp / 3;
  38829. for (var p = 0; p < lp; p++) {
  38830. positions[lp + p] = positions[p];
  38831. }
  38832. // indices
  38833. for (i = 0; i < li; i += 3) {
  38834. indices[i + li] = indices[i + 2] + l;
  38835. indices[i + 1 + li] = indices[i + 1] + l;
  38836. indices[i + 2 + li] = indices[i] + l;
  38837. }
  38838. // normals
  38839. for (n = 0; n < ln; n++) {
  38840. normals[ln + n] = -normals[n];
  38841. }
  38842. // uvs
  38843. var lu = uvs.length;
  38844. var u = 0;
  38845. for (u = 0; u < lu; u++) {
  38846. uvs[u + lu] = uvs[u];
  38847. }
  38848. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38849. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38850. u = 0;
  38851. for (i = 0; i < lu / 2; i++) {
  38852. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38853. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38854. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38855. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38856. u += 2;
  38857. }
  38858. break;
  38859. }
  38860. };
  38861. /**
  38862. * Applies VertexData created from the imported parameters to the geometry
  38863. * @param parsedVertexData the parsed data from an imported file
  38864. * @param geometry the geometry to apply the VertexData to
  38865. */
  38866. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38867. var vertexData = new VertexData();
  38868. // positions
  38869. var positions = parsedVertexData.positions;
  38870. if (positions) {
  38871. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38872. }
  38873. // normals
  38874. var normals = parsedVertexData.normals;
  38875. if (normals) {
  38876. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38877. }
  38878. // tangents
  38879. var tangents = parsedVertexData.tangents;
  38880. if (tangents) {
  38881. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38882. }
  38883. // uvs
  38884. var uvs = parsedVertexData.uvs;
  38885. if (uvs) {
  38886. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38887. }
  38888. // uv2s
  38889. var uv2s = parsedVertexData.uv2s;
  38890. if (uv2s) {
  38891. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38892. }
  38893. // uv3s
  38894. var uv3s = parsedVertexData.uv3s;
  38895. if (uv3s) {
  38896. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38897. }
  38898. // uv4s
  38899. var uv4s = parsedVertexData.uv4s;
  38900. if (uv4s) {
  38901. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38902. }
  38903. // uv5s
  38904. var uv5s = parsedVertexData.uv5s;
  38905. if (uv5s) {
  38906. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38907. }
  38908. // uv6s
  38909. var uv6s = parsedVertexData.uv6s;
  38910. if (uv6s) {
  38911. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38912. }
  38913. // colors
  38914. var colors = parsedVertexData.colors;
  38915. if (colors) {
  38916. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38917. }
  38918. // matricesIndices
  38919. var matricesIndices = parsedVertexData.matricesIndices;
  38920. if (matricesIndices) {
  38921. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38922. }
  38923. // matricesWeights
  38924. var matricesWeights = parsedVertexData.matricesWeights;
  38925. if (matricesWeights) {
  38926. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38927. }
  38928. // indices
  38929. var indices = parsedVertexData.indices;
  38930. if (indices) {
  38931. vertexData.indices = indices;
  38932. }
  38933. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38934. };
  38935. return VertexData;
  38936. }());
  38937. BABYLON.VertexData = VertexData;
  38938. })(BABYLON || (BABYLON = {}));
  38939. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38940. var BABYLON;
  38941. (function (BABYLON) {
  38942. /**
  38943. * Class used to store geometry data (vertex buffers + index buffer)
  38944. */
  38945. var Geometry = /** @class */ (function () {
  38946. /**
  38947. * Creates a new geometry
  38948. * @param id defines the unique ID
  38949. * @param scene defines the hosting scene
  38950. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38951. * @param updatable defines if geometry must be updatable (false by default)
  38952. * @param mesh defines the mesh that will be associated with the geometry
  38953. */
  38954. function Geometry(id, scene, vertexData, updatable, mesh) {
  38955. if (updatable === void 0) { updatable = false; }
  38956. if (mesh === void 0) { mesh = null; }
  38957. /**
  38958. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38959. */
  38960. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38961. this._totalVertices = 0;
  38962. this._isDisposed = false;
  38963. this._indexBufferIsUpdatable = false;
  38964. this.id = id;
  38965. this._engine = scene.getEngine();
  38966. this._meshes = [];
  38967. this._scene = scene;
  38968. //Init vertex buffer cache
  38969. this._vertexBuffers = {};
  38970. this._indices = [];
  38971. this._updatable = updatable;
  38972. // vertexData
  38973. if (vertexData) {
  38974. this.setAllVerticesData(vertexData, updatable);
  38975. }
  38976. else {
  38977. this._totalVertices = 0;
  38978. this._indices = [];
  38979. }
  38980. if (this._engine.getCaps().vertexArrayObject) {
  38981. this._vertexArrayObjects = {};
  38982. }
  38983. // applyToMesh
  38984. if (mesh) {
  38985. if (mesh.getClassName() === "LinesMesh") {
  38986. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38987. this._updateExtend();
  38988. }
  38989. this.applyToMesh(mesh);
  38990. mesh.computeWorldMatrix(true);
  38991. }
  38992. }
  38993. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38994. /**
  38995. * 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
  38996. */
  38997. get: function () {
  38998. return this._boundingBias;
  38999. },
  39000. /**
  39001. * 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
  39002. */
  39003. set: function (value) {
  39004. if (this._boundingBias && this._boundingBias.equals(value)) {
  39005. return;
  39006. }
  39007. this._boundingBias = value.clone();
  39008. this._updateBoundingInfo(true, null);
  39009. },
  39010. enumerable: true,
  39011. configurable: true
  39012. });
  39013. /**
  39014. * Static function used to attach a new empty geometry to a mesh
  39015. * @param mesh defines the mesh to attach the geometry to
  39016. * @returns the new {BABYLON.Geometry}
  39017. */
  39018. Geometry.CreateGeometryForMesh = function (mesh) {
  39019. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39020. geometry.applyToMesh(mesh);
  39021. return geometry;
  39022. };
  39023. Object.defineProperty(Geometry.prototype, "extend", {
  39024. /**
  39025. * Gets the current extend of the geometry
  39026. */
  39027. get: function () {
  39028. return this._extend;
  39029. },
  39030. enumerable: true,
  39031. configurable: true
  39032. });
  39033. /**
  39034. * Gets the hosting scene
  39035. * @returns the hosting {BABYLON.Scene}
  39036. */
  39037. Geometry.prototype.getScene = function () {
  39038. return this._scene;
  39039. };
  39040. /**
  39041. * Gets the hosting engine
  39042. * @returns the hosting {BABYLON.Engine}
  39043. */
  39044. Geometry.prototype.getEngine = function () {
  39045. return this._engine;
  39046. };
  39047. /**
  39048. * Defines if the geometry is ready to use
  39049. * @returns true if the geometry is ready to be used
  39050. */
  39051. Geometry.prototype.isReady = function () {
  39052. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39053. };
  39054. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39055. /**
  39056. * Gets a value indicating that the geometry should not be serialized
  39057. */
  39058. get: function () {
  39059. for (var index = 0; index < this._meshes.length; index++) {
  39060. if (!this._meshes[index].doNotSerialize) {
  39061. return false;
  39062. }
  39063. }
  39064. return true;
  39065. },
  39066. enumerable: true,
  39067. configurable: true
  39068. });
  39069. /** @hidden */
  39070. Geometry.prototype._rebuild = function () {
  39071. if (this._vertexArrayObjects) {
  39072. this._vertexArrayObjects = {};
  39073. }
  39074. // Index buffer
  39075. if (this._meshes.length !== 0 && this._indices) {
  39076. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39077. }
  39078. // Vertex buffers
  39079. for (var key in this._vertexBuffers) {
  39080. var vertexBuffer = this._vertexBuffers[key];
  39081. vertexBuffer._rebuild();
  39082. }
  39083. };
  39084. /**
  39085. * Affects all gemetry data in one call
  39086. * @param vertexData defines the geometry data
  39087. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39088. */
  39089. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39090. vertexData.applyToGeometry(this, updatable);
  39091. this.notifyUpdate();
  39092. };
  39093. /**
  39094. * Set specific vertex data
  39095. * @param kind defines the data kind (Position, normal, etc...)
  39096. * @param data defines the vertex data to use
  39097. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39098. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39099. */
  39100. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39101. if (updatable === void 0) { updatable = false; }
  39102. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39103. this.setVerticesBuffer(buffer);
  39104. };
  39105. /**
  39106. * Removes a specific vertex data
  39107. * @param kind defines the data kind (Position, normal, etc...)
  39108. */
  39109. Geometry.prototype.removeVerticesData = function (kind) {
  39110. if (this._vertexBuffers[kind]) {
  39111. this._vertexBuffers[kind].dispose();
  39112. delete this._vertexBuffers[kind];
  39113. }
  39114. };
  39115. /**
  39116. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39117. * @param buffer defines the vertex buffer to use
  39118. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39119. */
  39120. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39121. if (totalVertices === void 0) { totalVertices = null; }
  39122. var kind = buffer.getKind();
  39123. if (this._vertexBuffers[kind]) {
  39124. this._vertexBuffers[kind].dispose();
  39125. }
  39126. this._vertexBuffers[kind] = buffer;
  39127. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39128. var data = buffer.getData();
  39129. if (totalVertices != null) {
  39130. this._totalVertices = totalVertices;
  39131. }
  39132. else {
  39133. if (data != null) {
  39134. this._totalVertices = data.length / (buffer.byteStride / 4);
  39135. }
  39136. }
  39137. this._updateExtend(data);
  39138. this._resetPointsArrayCache();
  39139. var meshes = this._meshes;
  39140. var numOfMeshes = meshes.length;
  39141. for (var index = 0; index < numOfMeshes; index++) {
  39142. var mesh = meshes[index];
  39143. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39144. mesh._createGlobalSubMesh(false);
  39145. mesh.computeWorldMatrix(true);
  39146. }
  39147. }
  39148. this.notifyUpdate(kind);
  39149. if (this._vertexArrayObjects) {
  39150. this._disposeVertexArrayObjects();
  39151. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39152. }
  39153. };
  39154. /**
  39155. * Update a specific vertex buffer
  39156. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39157. * It will do nothing if the buffer is not updatable
  39158. * @param kind defines the data kind (Position, normal, etc...)
  39159. * @param data defines the data to use
  39160. * @param offset defines the offset in the target buffer where to store the data
  39161. * @param useBytes set to true if the offset is in bytes
  39162. */
  39163. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39164. if (useBytes === void 0) { useBytes = false; }
  39165. var vertexBuffer = this.getVertexBuffer(kind);
  39166. if (!vertexBuffer) {
  39167. return;
  39168. }
  39169. vertexBuffer.updateDirectly(data, offset, useBytes);
  39170. this.notifyUpdate(kind);
  39171. };
  39172. /**
  39173. * Update a specific vertex buffer
  39174. * This function will create a new buffer if the current one is not updatable
  39175. * @param kind defines the data kind (Position, normal, etc...)
  39176. * @param data defines the data to use
  39177. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39178. */
  39179. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39180. if (updateExtends === void 0) { updateExtends = false; }
  39181. var vertexBuffer = this.getVertexBuffer(kind);
  39182. if (!vertexBuffer) {
  39183. return;
  39184. }
  39185. vertexBuffer.update(data);
  39186. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39187. this._updateBoundingInfo(updateExtends, data);
  39188. }
  39189. this.notifyUpdate(kind);
  39190. };
  39191. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39192. if (updateExtends) {
  39193. this._updateExtend(data);
  39194. }
  39195. var meshes = this._meshes;
  39196. var numOfMeshes = meshes.length;
  39197. this._resetPointsArrayCache();
  39198. for (var index = 0; index < numOfMeshes; index++) {
  39199. var mesh = meshes[index];
  39200. if (updateExtends) {
  39201. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39202. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39203. var subMesh = mesh.subMeshes[subIndex];
  39204. subMesh.refreshBoundingInfo();
  39205. }
  39206. }
  39207. }
  39208. };
  39209. /** @hidden */
  39210. Geometry.prototype._bind = function (effect, indexToBind) {
  39211. if (!effect) {
  39212. return;
  39213. }
  39214. if (indexToBind === undefined) {
  39215. indexToBind = this._indexBuffer;
  39216. }
  39217. var vbs = this.getVertexBuffers();
  39218. if (!vbs) {
  39219. return;
  39220. }
  39221. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39222. this._engine.bindBuffers(vbs, indexToBind, effect);
  39223. return;
  39224. }
  39225. // Using VAO
  39226. if (!this._vertexArrayObjects[effect.key]) {
  39227. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39228. }
  39229. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39230. };
  39231. /**
  39232. * Gets total number of vertices
  39233. * @returns the total number of vertices
  39234. */
  39235. Geometry.prototype.getTotalVertices = function () {
  39236. if (!this.isReady()) {
  39237. return 0;
  39238. }
  39239. return this._totalVertices;
  39240. };
  39241. /**
  39242. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39243. * @param kind defines the data kind (Position, normal, etc...)
  39244. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39245. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39246. * @returns a float array containing vertex data
  39247. */
  39248. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39249. var vertexBuffer = this.getVertexBuffer(kind);
  39250. if (!vertexBuffer) {
  39251. return null;
  39252. }
  39253. var data = vertexBuffer.getData();
  39254. if (!data) {
  39255. return null;
  39256. }
  39257. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39258. var count = this._totalVertices * vertexBuffer.getSize();
  39259. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39260. var copy_1 = new Array(count);
  39261. vertexBuffer.forEach(count, function (value, index) {
  39262. copy_1[index] = value;
  39263. });
  39264. return copy_1;
  39265. }
  39266. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39267. if (data instanceof Array) {
  39268. var offset = vertexBuffer.byteOffset / 4;
  39269. return BABYLON.Tools.Slice(data, offset, offset + count);
  39270. }
  39271. else if (data instanceof ArrayBuffer) {
  39272. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39273. }
  39274. else {
  39275. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39276. }
  39277. }
  39278. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39279. return BABYLON.Tools.Slice(data);
  39280. }
  39281. return data;
  39282. };
  39283. /**
  39284. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39285. * @param kind defines the data kind (Position, normal, etc...)
  39286. * @returns true if the vertex buffer with the specified kind is updatable
  39287. */
  39288. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39289. var vb = this._vertexBuffers[kind];
  39290. if (!vb) {
  39291. return false;
  39292. }
  39293. return vb.isUpdatable();
  39294. };
  39295. /**
  39296. * Gets a specific vertex buffer
  39297. * @param kind defines the data kind (Position, normal, etc...)
  39298. * @returns a {BABYLON.VertexBuffer}
  39299. */
  39300. Geometry.prototype.getVertexBuffer = function (kind) {
  39301. if (!this.isReady()) {
  39302. return null;
  39303. }
  39304. return this._vertexBuffers[kind];
  39305. };
  39306. /**
  39307. * Returns all vertex buffers
  39308. * @return an object holding all vertex buffers indexed by kind
  39309. */
  39310. Geometry.prototype.getVertexBuffers = function () {
  39311. if (!this.isReady()) {
  39312. return null;
  39313. }
  39314. return this._vertexBuffers;
  39315. };
  39316. /**
  39317. * Gets a boolean indicating if specific vertex buffer is present
  39318. * @param kind defines the data kind (Position, normal, etc...)
  39319. * @returns true if data is present
  39320. */
  39321. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39322. if (!this._vertexBuffers) {
  39323. if (this._delayInfo) {
  39324. return this._delayInfo.indexOf(kind) !== -1;
  39325. }
  39326. return false;
  39327. }
  39328. return this._vertexBuffers[kind] !== undefined;
  39329. };
  39330. /**
  39331. * Gets a list of all attached data kinds (Position, normal, etc...)
  39332. * @returns a list of string containing all kinds
  39333. */
  39334. Geometry.prototype.getVerticesDataKinds = function () {
  39335. var result = [];
  39336. var kind;
  39337. if (!this._vertexBuffers && this._delayInfo) {
  39338. for (kind in this._delayInfo) {
  39339. result.push(kind);
  39340. }
  39341. }
  39342. else {
  39343. for (kind in this._vertexBuffers) {
  39344. result.push(kind);
  39345. }
  39346. }
  39347. return result;
  39348. };
  39349. /**
  39350. * Update index buffer
  39351. * @param indices defines the indices to store in the index buffer
  39352. * @param offset defines the offset in the target buffer where to store the data
  39353. */
  39354. Geometry.prototype.updateIndices = function (indices, offset) {
  39355. if (!this._indexBuffer) {
  39356. return;
  39357. }
  39358. if (!this._indexBufferIsUpdatable) {
  39359. this.setIndices(indices, null, true);
  39360. }
  39361. else {
  39362. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39363. }
  39364. };
  39365. /**
  39366. * Creates a new index buffer
  39367. * @param indices defines the indices to store in the index buffer
  39368. * @param totalVertices defines the total number of vertices (could be null)
  39369. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39370. */
  39371. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39372. if (totalVertices === void 0) { totalVertices = null; }
  39373. if (updatable === void 0) { updatable = false; }
  39374. if (this._indexBuffer) {
  39375. this._engine._releaseBuffer(this._indexBuffer);
  39376. }
  39377. this._disposeVertexArrayObjects();
  39378. this._indices = indices;
  39379. this._indexBufferIsUpdatable = updatable;
  39380. if (this._meshes.length !== 0 && this._indices) {
  39381. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39382. }
  39383. if (totalVertices != undefined) { // including null and undefined
  39384. this._totalVertices = totalVertices;
  39385. }
  39386. var meshes = this._meshes;
  39387. var numOfMeshes = meshes.length;
  39388. for (var index = 0; index < numOfMeshes; index++) {
  39389. meshes[index]._createGlobalSubMesh(true);
  39390. }
  39391. this.notifyUpdate();
  39392. };
  39393. /**
  39394. * Return the total number of indices
  39395. * @returns the total number of indices
  39396. */
  39397. Geometry.prototype.getTotalIndices = function () {
  39398. if (!this.isReady()) {
  39399. return 0;
  39400. }
  39401. return this._indices.length;
  39402. };
  39403. /**
  39404. * Gets the index buffer array
  39405. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39406. * @returns the index buffer array
  39407. */
  39408. Geometry.prototype.getIndices = function (copyWhenShared) {
  39409. if (!this.isReady()) {
  39410. return null;
  39411. }
  39412. var orig = this._indices;
  39413. if (!copyWhenShared || this._meshes.length === 1) {
  39414. return orig;
  39415. }
  39416. else {
  39417. var len = orig.length;
  39418. var copy = [];
  39419. for (var i = 0; i < len; i++) {
  39420. copy.push(orig[i]);
  39421. }
  39422. return copy;
  39423. }
  39424. };
  39425. /**
  39426. * Gets the index buffer
  39427. * @return the index buffer
  39428. */
  39429. Geometry.prototype.getIndexBuffer = function () {
  39430. if (!this.isReady()) {
  39431. return null;
  39432. }
  39433. return this._indexBuffer;
  39434. };
  39435. /** @hidden */
  39436. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39437. if (effect === void 0) { effect = null; }
  39438. if (!effect || !this._vertexArrayObjects) {
  39439. return;
  39440. }
  39441. if (this._vertexArrayObjects[effect.key]) {
  39442. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39443. delete this._vertexArrayObjects[effect.key];
  39444. }
  39445. };
  39446. /**
  39447. * Release the associated resources for a specific mesh
  39448. * @param mesh defines the source mesh
  39449. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39450. */
  39451. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39452. var meshes = this._meshes;
  39453. var index = meshes.indexOf(mesh);
  39454. if (index === -1) {
  39455. return;
  39456. }
  39457. meshes.splice(index, 1);
  39458. mesh._geometry = null;
  39459. if (meshes.length === 0 && shouldDispose) {
  39460. this.dispose();
  39461. }
  39462. };
  39463. /**
  39464. * Apply current geometry to a given mesh
  39465. * @param mesh defines the mesh to apply geometry to
  39466. */
  39467. Geometry.prototype.applyToMesh = function (mesh) {
  39468. if (mesh._geometry === this) {
  39469. return;
  39470. }
  39471. var previousGeometry = mesh._geometry;
  39472. if (previousGeometry) {
  39473. previousGeometry.releaseForMesh(mesh);
  39474. }
  39475. var meshes = this._meshes;
  39476. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39477. mesh._geometry = this;
  39478. this._scene.pushGeometry(this);
  39479. meshes.push(mesh);
  39480. if (this.isReady()) {
  39481. this._applyToMesh(mesh);
  39482. }
  39483. else {
  39484. mesh._boundingInfo = this._boundingInfo;
  39485. }
  39486. };
  39487. Geometry.prototype._updateExtend = function (data) {
  39488. if (data === void 0) { data = null; }
  39489. if (!data) {
  39490. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39491. }
  39492. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39493. };
  39494. Geometry.prototype._applyToMesh = function (mesh) {
  39495. var numOfMeshes = this._meshes.length;
  39496. // vertexBuffers
  39497. for (var kind in this._vertexBuffers) {
  39498. if (numOfMeshes === 1) {
  39499. this._vertexBuffers[kind].create();
  39500. }
  39501. var buffer = this._vertexBuffers[kind].getBuffer();
  39502. if (buffer)
  39503. buffer.references = numOfMeshes;
  39504. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39505. if (!this._extend) {
  39506. this._updateExtend();
  39507. }
  39508. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39509. mesh._createGlobalSubMesh(false);
  39510. //bounding info was just created again, world matrix should be applied again.
  39511. mesh._updateBoundingInfo();
  39512. }
  39513. }
  39514. // indexBuffer
  39515. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39516. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39517. }
  39518. if (this._indexBuffer) {
  39519. this._indexBuffer.references = numOfMeshes;
  39520. }
  39521. };
  39522. Geometry.prototype.notifyUpdate = function (kind) {
  39523. if (this.onGeometryUpdated) {
  39524. this.onGeometryUpdated(this, kind);
  39525. }
  39526. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39527. var mesh = _a[_i];
  39528. mesh._markSubMeshesAsAttributesDirty();
  39529. }
  39530. };
  39531. /**
  39532. * Load the geometry if it was flagged as delay loaded
  39533. * @param scene defines the hosting scene
  39534. * @param onLoaded defines a callback called when the geometry is loaded
  39535. */
  39536. Geometry.prototype.load = function (scene, onLoaded) {
  39537. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39538. return;
  39539. }
  39540. if (this.isReady()) {
  39541. if (onLoaded) {
  39542. onLoaded();
  39543. }
  39544. return;
  39545. }
  39546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39547. this._queueLoad(scene, onLoaded);
  39548. };
  39549. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39550. var _this = this;
  39551. if (!this.delayLoadingFile) {
  39552. return;
  39553. }
  39554. scene._addPendingData(this);
  39555. scene._loadFile(this.delayLoadingFile, function (data) {
  39556. if (!_this._delayLoadingFunction) {
  39557. return;
  39558. }
  39559. _this._delayLoadingFunction(JSON.parse(data), _this);
  39560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39561. _this._delayInfo = [];
  39562. scene._removePendingData(_this);
  39563. var meshes = _this._meshes;
  39564. var numOfMeshes = meshes.length;
  39565. for (var index = 0; index < numOfMeshes; index++) {
  39566. _this._applyToMesh(meshes[index]);
  39567. }
  39568. if (onLoaded) {
  39569. onLoaded();
  39570. }
  39571. }, undefined, true);
  39572. };
  39573. /**
  39574. * Invert the geometry to move from a right handed system to a left handed one.
  39575. */
  39576. Geometry.prototype.toLeftHanded = function () {
  39577. // Flip faces
  39578. var tIndices = this.getIndices(false);
  39579. if (tIndices != null && tIndices.length > 0) {
  39580. for (var i = 0; i < tIndices.length; i += 3) {
  39581. var tTemp = tIndices[i + 0];
  39582. tIndices[i + 0] = tIndices[i + 2];
  39583. tIndices[i + 2] = tTemp;
  39584. }
  39585. this.setIndices(tIndices);
  39586. }
  39587. // Negate position.z
  39588. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39589. if (tPositions != null && tPositions.length > 0) {
  39590. for (var i = 0; i < tPositions.length; i += 3) {
  39591. tPositions[i + 2] = -tPositions[i + 2];
  39592. }
  39593. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39594. }
  39595. // Negate normal.z
  39596. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39597. if (tNormals != null && tNormals.length > 0) {
  39598. for (var i = 0; i < tNormals.length; i += 3) {
  39599. tNormals[i + 2] = -tNormals[i + 2];
  39600. }
  39601. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39602. }
  39603. };
  39604. // Cache
  39605. /** @hidden */
  39606. Geometry.prototype._resetPointsArrayCache = function () {
  39607. this._positions = null;
  39608. };
  39609. /** @hidden */
  39610. Geometry.prototype._generatePointsArray = function () {
  39611. if (this._positions)
  39612. return true;
  39613. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39614. if (!data || data.length === 0) {
  39615. return false;
  39616. }
  39617. this._positions = [];
  39618. for (var index = 0; index < data.length; index += 3) {
  39619. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39620. }
  39621. return true;
  39622. };
  39623. /**
  39624. * Gets a value indicating if the geometry is disposed
  39625. * @returns true if the geometry was disposed
  39626. */
  39627. Geometry.prototype.isDisposed = function () {
  39628. return this._isDisposed;
  39629. };
  39630. Geometry.prototype._disposeVertexArrayObjects = function () {
  39631. if (this._vertexArrayObjects) {
  39632. for (var kind in this._vertexArrayObjects) {
  39633. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39634. }
  39635. this._vertexArrayObjects = {};
  39636. }
  39637. };
  39638. /**
  39639. * Free all associated resources
  39640. */
  39641. Geometry.prototype.dispose = function () {
  39642. var meshes = this._meshes;
  39643. var numOfMeshes = meshes.length;
  39644. var index;
  39645. for (index = 0; index < numOfMeshes; index++) {
  39646. this.releaseForMesh(meshes[index]);
  39647. }
  39648. this._meshes = [];
  39649. this._disposeVertexArrayObjects();
  39650. for (var kind in this._vertexBuffers) {
  39651. this._vertexBuffers[kind].dispose();
  39652. }
  39653. this._vertexBuffers = {};
  39654. this._totalVertices = 0;
  39655. if (this._indexBuffer) {
  39656. this._engine._releaseBuffer(this._indexBuffer);
  39657. }
  39658. this._indexBuffer = null;
  39659. this._indices = [];
  39660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39661. this.delayLoadingFile = null;
  39662. this._delayLoadingFunction = null;
  39663. this._delayInfo = [];
  39664. this._boundingInfo = null;
  39665. this._scene.removeGeometry(this);
  39666. this._isDisposed = true;
  39667. };
  39668. /**
  39669. * Clone the current geometry into a new geometry
  39670. * @param id defines the unique ID of the new geometry
  39671. * @returns a new geometry object
  39672. */
  39673. Geometry.prototype.copy = function (id) {
  39674. var vertexData = new BABYLON.VertexData();
  39675. vertexData.indices = [];
  39676. var indices = this.getIndices();
  39677. if (indices) {
  39678. for (var index = 0; index < indices.length; index++) {
  39679. vertexData.indices.push(indices[index]);
  39680. }
  39681. }
  39682. var updatable = false;
  39683. var stopChecking = false;
  39684. var kind;
  39685. for (kind in this._vertexBuffers) {
  39686. // using slice() to make a copy of the array and not just reference it
  39687. var data = this.getVerticesData(kind);
  39688. if (data instanceof Float32Array) {
  39689. vertexData.set(new Float32Array(data), kind);
  39690. }
  39691. else {
  39692. vertexData.set(data.slice(0), kind);
  39693. }
  39694. if (!stopChecking) {
  39695. var vb = this.getVertexBuffer(kind);
  39696. if (vb) {
  39697. updatable = vb.isUpdatable();
  39698. stopChecking = !updatable;
  39699. }
  39700. }
  39701. }
  39702. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39703. geometry.delayLoadState = this.delayLoadState;
  39704. geometry.delayLoadingFile = this.delayLoadingFile;
  39705. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39706. for (kind in this._delayInfo) {
  39707. geometry._delayInfo = geometry._delayInfo || [];
  39708. geometry._delayInfo.push(kind);
  39709. }
  39710. // Bounding info
  39711. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39712. return geometry;
  39713. };
  39714. /**
  39715. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39716. * @return a JSON representation of the current geometry data (without the vertices data)
  39717. */
  39718. Geometry.prototype.serialize = function () {
  39719. var serializationObject = {};
  39720. serializationObject.id = this.id;
  39721. serializationObject.updatable = this._updatable;
  39722. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39723. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39724. }
  39725. return serializationObject;
  39726. };
  39727. Geometry.prototype.toNumberArray = function (origin) {
  39728. if (Array.isArray(origin)) {
  39729. return origin;
  39730. }
  39731. else {
  39732. return Array.prototype.slice.call(origin);
  39733. }
  39734. };
  39735. /**
  39736. * Serialize all vertices data into a JSON oject
  39737. * @returns a JSON representation of the current geometry data
  39738. */
  39739. Geometry.prototype.serializeVerticeData = function () {
  39740. var serializationObject = this.serialize();
  39741. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39742. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39743. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39744. serializationObject.positions._updatable = true;
  39745. }
  39746. }
  39747. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39748. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39749. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39750. serializationObject.normals._updatable = true;
  39751. }
  39752. }
  39753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39754. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39755. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39756. serializationObject.tangets._updatable = true;
  39757. }
  39758. }
  39759. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39760. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39761. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39762. serializationObject.uvs._updatable = true;
  39763. }
  39764. }
  39765. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39766. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39768. serializationObject.uv2s._updatable = true;
  39769. }
  39770. }
  39771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39772. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39774. serializationObject.uv3s._updatable = true;
  39775. }
  39776. }
  39777. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39778. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39779. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39780. serializationObject.uv4s._updatable = true;
  39781. }
  39782. }
  39783. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39784. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39785. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39786. serializationObject.uv5s._updatable = true;
  39787. }
  39788. }
  39789. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39790. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39791. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39792. serializationObject.uv6s._updatable = true;
  39793. }
  39794. }
  39795. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39796. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39797. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39798. serializationObject.colors._updatable = true;
  39799. }
  39800. }
  39801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39802. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39803. serializationObject.matricesIndices._isExpanded = true;
  39804. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39805. serializationObject.matricesIndices._updatable = true;
  39806. }
  39807. }
  39808. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39809. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39810. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39811. serializationObject.matricesWeights._updatable = true;
  39812. }
  39813. }
  39814. serializationObject.indices = this.toNumberArray(this.getIndices());
  39815. return serializationObject;
  39816. };
  39817. // Statics
  39818. /**
  39819. * Extracts a clone of a mesh geometry
  39820. * @param mesh defines the source mesh
  39821. * @param id defines the unique ID of the new geometry object
  39822. * @returns the new geometry object
  39823. */
  39824. Geometry.ExtractFromMesh = function (mesh, id) {
  39825. var geometry = mesh._geometry;
  39826. if (!geometry) {
  39827. return null;
  39828. }
  39829. return geometry.copy(id);
  39830. };
  39831. /**
  39832. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39833. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39834. * Be aware Math.random() could cause collisions, but:
  39835. * "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"
  39836. * @returns a string containing a new GUID
  39837. */
  39838. Geometry.RandomId = function () {
  39839. return BABYLON.Tools.RandomId();
  39840. };
  39841. /** @hidden */
  39842. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39843. var scene = mesh.getScene();
  39844. // Geometry
  39845. var geometryId = parsedGeometry.geometryId;
  39846. if (geometryId) {
  39847. var geometry = scene.getGeometryByID(geometryId);
  39848. if (geometry) {
  39849. geometry.applyToMesh(mesh);
  39850. }
  39851. }
  39852. else if (parsedGeometry instanceof ArrayBuffer) {
  39853. var binaryInfo = mesh._binaryInfo;
  39854. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39855. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39856. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39857. }
  39858. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39859. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39860. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39861. }
  39862. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39863. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39864. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39865. }
  39866. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39867. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39868. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39869. }
  39870. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39871. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39872. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39873. }
  39874. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39875. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39876. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39877. }
  39878. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39879. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39880. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39881. }
  39882. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39883. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39884. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39885. }
  39886. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39887. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39889. }
  39890. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39891. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39892. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39893. }
  39894. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39895. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39896. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39897. }
  39898. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39899. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39900. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39901. }
  39902. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39903. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39904. mesh.setIndices(indicesData, null);
  39905. }
  39906. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39907. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39908. mesh.subMeshes = [];
  39909. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39910. var materialIndex = subMeshesData[(i * 5) + 0];
  39911. var verticesStart = subMeshesData[(i * 5) + 1];
  39912. var verticesCount = subMeshesData[(i * 5) + 2];
  39913. var indexStart = subMeshesData[(i * 5) + 3];
  39914. var indexCount = subMeshesData[(i * 5) + 4];
  39915. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39916. }
  39917. }
  39918. }
  39919. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39920. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39921. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39922. if (parsedGeometry.tangents) {
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39924. }
  39925. if (parsedGeometry.uvs) {
  39926. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39927. }
  39928. if (parsedGeometry.uvs2) {
  39929. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39930. }
  39931. if (parsedGeometry.uvs3) {
  39932. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39933. }
  39934. if (parsedGeometry.uvs4) {
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39936. }
  39937. if (parsedGeometry.uvs5) {
  39938. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39939. }
  39940. if (parsedGeometry.uvs6) {
  39941. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39942. }
  39943. if (parsedGeometry.colors) {
  39944. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39945. }
  39946. if (parsedGeometry.matricesIndices) {
  39947. if (!parsedGeometry.matricesIndices._isExpanded) {
  39948. var floatIndices = [];
  39949. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39950. var matricesIndex = parsedGeometry.matricesIndices[i];
  39951. floatIndices.push(matricesIndex & 0x000000FF);
  39952. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39953. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39954. floatIndices.push(matricesIndex >> 24);
  39955. }
  39956. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39957. }
  39958. else {
  39959. delete parsedGeometry.matricesIndices._isExpanded;
  39960. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39961. }
  39962. }
  39963. if (parsedGeometry.matricesIndicesExtra) {
  39964. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39965. var floatIndices = [];
  39966. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39967. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39968. floatIndices.push(matricesIndex & 0x000000FF);
  39969. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39970. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39971. floatIndices.push(matricesIndex >> 24);
  39972. }
  39973. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39974. }
  39975. else {
  39976. delete parsedGeometry.matricesIndices._isExpanded;
  39977. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39978. }
  39979. }
  39980. if (parsedGeometry.matricesWeights) {
  39981. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39983. }
  39984. if (parsedGeometry.matricesWeightsExtra) {
  39985. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39986. }
  39987. mesh.setIndices(parsedGeometry.indices, null);
  39988. }
  39989. // SubMeshes
  39990. if (parsedGeometry.subMeshes) {
  39991. mesh.subMeshes = [];
  39992. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39993. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39994. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39995. }
  39996. }
  39997. // Flat shading
  39998. if (mesh._shouldGenerateFlatShading) {
  39999. mesh.convertToFlatShadedMesh();
  40000. delete mesh._shouldGenerateFlatShading;
  40001. }
  40002. // Update
  40003. mesh.computeWorldMatrix(true);
  40004. // Octree
  40005. var sceneOctree = scene.selectionOctree;
  40006. if (sceneOctree !== undefined && sceneOctree !== null) {
  40007. sceneOctree.addMesh(mesh);
  40008. }
  40009. };
  40010. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40011. var epsilon = 1e-3;
  40012. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40013. return;
  40014. }
  40015. var noInfluenceBoneIndex = 0.0;
  40016. if (parsedGeometry.skeletonId > -1) {
  40017. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40018. if (!skeleton) {
  40019. return;
  40020. }
  40021. noInfluenceBoneIndex = skeleton.bones.length;
  40022. }
  40023. else {
  40024. return;
  40025. }
  40026. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40027. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40028. var matricesWeights = parsedGeometry.matricesWeights;
  40029. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40030. var influencers = parsedGeometry.numBoneInfluencer;
  40031. var size = matricesWeights.length;
  40032. for (var i = 0; i < size; i += 4) {
  40033. var weight = 0.0;
  40034. var firstZeroWeight = -1;
  40035. for (var j = 0; j < 4; j++) {
  40036. var w = matricesWeights[i + j];
  40037. weight += w;
  40038. if (w < epsilon && firstZeroWeight < 0) {
  40039. firstZeroWeight = j;
  40040. }
  40041. }
  40042. if (matricesWeightsExtra) {
  40043. for (var j = 0; j < 4; j++) {
  40044. var w = matricesWeightsExtra[i + j];
  40045. weight += w;
  40046. if (w < epsilon && firstZeroWeight < 0) {
  40047. firstZeroWeight = j + 4;
  40048. }
  40049. }
  40050. }
  40051. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40052. firstZeroWeight = influencers - 1;
  40053. }
  40054. if (weight > epsilon) {
  40055. var mweight = 1.0 / weight;
  40056. for (var j = 0; j < 4; j++) {
  40057. matricesWeights[i + j] *= mweight;
  40058. }
  40059. if (matricesWeightsExtra) {
  40060. for (var j = 0; j < 4; j++) {
  40061. matricesWeightsExtra[i + j] *= mweight;
  40062. }
  40063. }
  40064. }
  40065. else {
  40066. if (firstZeroWeight >= 4) {
  40067. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40068. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40069. }
  40070. else {
  40071. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40072. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40073. }
  40074. }
  40075. }
  40076. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40077. if (parsedGeometry.matricesWeightsExtra) {
  40078. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40079. }
  40080. };
  40081. /**
  40082. * Create a new geometry from persisted data (Using .babylon file format)
  40083. * @param parsedVertexData defines the persisted data
  40084. * @param scene defines the hosting scene
  40085. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40086. * @returns the new geometry object
  40087. */
  40088. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40089. if (scene.getGeometryByID(parsedVertexData.id)) {
  40090. return null; // null since geometry could be something else than a box...
  40091. }
  40092. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40093. if (BABYLON.Tags) {
  40094. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40095. }
  40096. if (parsedVertexData.delayLoadingFile) {
  40097. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40098. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40099. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40100. geometry._delayInfo = [];
  40101. if (parsedVertexData.hasUVs) {
  40102. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40103. }
  40104. if (parsedVertexData.hasUVs2) {
  40105. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40106. }
  40107. if (parsedVertexData.hasUVs3) {
  40108. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40109. }
  40110. if (parsedVertexData.hasUVs4) {
  40111. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40112. }
  40113. if (parsedVertexData.hasUVs5) {
  40114. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40115. }
  40116. if (parsedVertexData.hasUVs6) {
  40117. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40118. }
  40119. if (parsedVertexData.hasColors) {
  40120. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40121. }
  40122. if (parsedVertexData.hasMatricesIndices) {
  40123. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40124. }
  40125. if (parsedVertexData.hasMatricesWeights) {
  40126. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40127. }
  40128. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40129. }
  40130. else {
  40131. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40132. }
  40133. scene.pushGeometry(geometry, true);
  40134. return geometry;
  40135. };
  40136. return Geometry;
  40137. }());
  40138. BABYLON.Geometry = Geometry;
  40139. // Primitives
  40140. /// Abstract class
  40141. /**
  40142. * Abstract class used to provide common services for all typed geometries
  40143. * @hidden
  40144. */
  40145. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40146. __extends(_PrimitiveGeometry, _super);
  40147. /**
  40148. * Creates a new typed geometry
  40149. * @param id defines the unique ID of the geometry
  40150. * @param scene defines the hosting scene
  40151. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40152. * @param mesh defines the hosting mesh (can be null)
  40153. */
  40154. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40155. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40156. if (mesh === void 0) { mesh = null; }
  40157. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40158. _this._canBeRegenerated = _canBeRegenerated;
  40159. _this._beingRegenerated = true;
  40160. _this.regenerate();
  40161. _this._beingRegenerated = false;
  40162. return _this;
  40163. }
  40164. /**
  40165. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40166. * @returns true if the geometry can be regenerated
  40167. */
  40168. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40169. return this._canBeRegenerated;
  40170. };
  40171. /**
  40172. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40173. */
  40174. _PrimitiveGeometry.prototype.regenerate = function () {
  40175. if (!this._canBeRegenerated) {
  40176. return;
  40177. }
  40178. this._beingRegenerated = true;
  40179. this.setAllVerticesData(this._regenerateVertexData(), false);
  40180. this._beingRegenerated = false;
  40181. };
  40182. /**
  40183. * Clone the geometry
  40184. * @param id defines the unique ID of the new geometry
  40185. * @returns the new geometry
  40186. */
  40187. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40188. return _super.prototype.copy.call(this, id);
  40189. };
  40190. // overrides
  40191. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40192. if (!this._beingRegenerated) {
  40193. return;
  40194. }
  40195. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40196. };
  40197. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40198. if (!this._beingRegenerated) {
  40199. return;
  40200. }
  40201. _super.prototype.setVerticesData.call(this, kind, data, false);
  40202. };
  40203. // to override
  40204. /** @hidden */
  40205. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40206. throw new Error("Abstract method");
  40207. };
  40208. _PrimitiveGeometry.prototype.copy = function (id) {
  40209. throw new Error("Must be overriden in sub-classes.");
  40210. };
  40211. _PrimitiveGeometry.prototype.serialize = function () {
  40212. var serializationObject = _super.prototype.serialize.call(this);
  40213. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40214. return serializationObject;
  40215. };
  40216. return _PrimitiveGeometry;
  40217. }(Geometry));
  40218. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40219. /**
  40220. * Creates a ribbon geometry
  40221. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40222. */
  40223. var RibbonGeometry = /** @class */ (function (_super) {
  40224. __extends(RibbonGeometry, _super);
  40225. /**
  40226. * Creates a ribbon geometry
  40227. * @param id defines the unique ID of the geometry
  40228. * @param scene defines the hosting scene
  40229. * @param pathArray defines the array of paths to use
  40230. * @param closeArray defines if the last path and the first path must be joined
  40231. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40232. * @param offset defines the offset between points
  40233. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40234. * @param mesh defines the hosting mesh (can be null)
  40235. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40236. */
  40237. function RibbonGeometry(id, scene,
  40238. /**
  40239. * Defines the array of paths to use
  40240. */
  40241. pathArray,
  40242. /**
  40243. * Defines if the last and first points of each path in your pathArray must be joined
  40244. */
  40245. closeArray,
  40246. /**
  40247. * Defines if the last and first points of each path in your pathArray must be joined
  40248. */
  40249. closePath,
  40250. /**
  40251. * Defines the offset between points
  40252. */
  40253. offset, canBeRegenerated, mesh,
  40254. /**
  40255. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40256. */
  40257. side) {
  40258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40260. _this.pathArray = pathArray;
  40261. _this.closeArray = closeArray;
  40262. _this.closePath = closePath;
  40263. _this.offset = offset;
  40264. _this.side = side;
  40265. return _this;
  40266. }
  40267. /** @hidden */
  40268. RibbonGeometry.prototype._regenerateVertexData = function () {
  40269. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40270. };
  40271. RibbonGeometry.prototype.copy = function (id) {
  40272. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40273. };
  40274. return RibbonGeometry;
  40275. }(_PrimitiveGeometry));
  40276. BABYLON.RibbonGeometry = RibbonGeometry;
  40277. /**
  40278. * Creates a box geometry
  40279. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40280. */
  40281. var BoxGeometry = /** @class */ (function (_super) {
  40282. __extends(BoxGeometry, _super);
  40283. /**
  40284. * Creates a box geometry
  40285. * @param id defines the unique ID of the geometry
  40286. * @param scene defines the hosting scene
  40287. * @param size defines the zise of the box (width, height and depth are the same)
  40288. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40289. * @param mesh defines the hosting mesh (can be null)
  40290. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40291. */
  40292. function BoxGeometry(id, scene,
  40293. /**
  40294. * Defines the zise of the box (width, height and depth are the same)
  40295. */
  40296. size, canBeRegenerated, mesh,
  40297. /**
  40298. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40299. */
  40300. side) {
  40301. if (mesh === void 0) { mesh = null; }
  40302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40304. _this.size = size;
  40305. _this.side = side;
  40306. return _this;
  40307. }
  40308. BoxGeometry.prototype._regenerateVertexData = function () {
  40309. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40310. };
  40311. BoxGeometry.prototype.copy = function (id) {
  40312. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40313. };
  40314. BoxGeometry.prototype.serialize = function () {
  40315. var serializationObject = _super.prototype.serialize.call(this);
  40316. serializationObject.size = this.size;
  40317. return serializationObject;
  40318. };
  40319. BoxGeometry.Parse = function (parsedBox, scene) {
  40320. if (scene.getGeometryByID(parsedBox.id)) {
  40321. return null; // null since geometry could be something else than a box...
  40322. }
  40323. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40324. if (BABYLON.Tags) {
  40325. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40326. }
  40327. scene.pushGeometry(box, true);
  40328. return box;
  40329. };
  40330. return BoxGeometry;
  40331. }(_PrimitiveGeometry));
  40332. BABYLON.BoxGeometry = BoxGeometry;
  40333. /**
  40334. * Creates a sphere geometry
  40335. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40336. */
  40337. var SphereGeometry = /** @class */ (function (_super) {
  40338. __extends(SphereGeometry, _super);
  40339. /**
  40340. * Create a new sphere geometry
  40341. * @param id defines the unique ID of the geometry
  40342. * @param scene defines the hosting scene
  40343. * @param segments defines the number of segments to use to create the sphere
  40344. * @param diameter defines the diameter of the sphere
  40345. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40346. * @param mesh defines the hosting mesh (can be null)
  40347. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40348. */
  40349. function SphereGeometry(id, scene,
  40350. /**
  40351. * Defines the number of segments to use to create the sphere
  40352. */
  40353. segments,
  40354. /**
  40355. * Defines the diameter of the sphere
  40356. */
  40357. diameter, canBeRegenerated, mesh,
  40358. /**
  40359. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40360. */
  40361. side) {
  40362. if (mesh === void 0) { mesh = null; }
  40363. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40364. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40365. _this.segments = segments;
  40366. _this.diameter = diameter;
  40367. _this.side = side;
  40368. return _this;
  40369. }
  40370. SphereGeometry.prototype._regenerateVertexData = function () {
  40371. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40372. };
  40373. SphereGeometry.prototype.copy = function (id) {
  40374. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40375. };
  40376. SphereGeometry.prototype.serialize = function () {
  40377. var serializationObject = _super.prototype.serialize.call(this);
  40378. serializationObject.segments = this.segments;
  40379. serializationObject.diameter = this.diameter;
  40380. return serializationObject;
  40381. };
  40382. SphereGeometry.Parse = function (parsedSphere, scene) {
  40383. if (scene.getGeometryByID(parsedSphere.id)) {
  40384. return null; // null since geometry could be something else than a sphere...
  40385. }
  40386. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40387. if (BABYLON.Tags) {
  40388. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40389. }
  40390. scene.pushGeometry(sphere, true);
  40391. return sphere;
  40392. };
  40393. return SphereGeometry;
  40394. }(_PrimitiveGeometry));
  40395. BABYLON.SphereGeometry = SphereGeometry;
  40396. /**
  40397. * Creates a disc geometry
  40398. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40399. */
  40400. var DiscGeometry = /** @class */ (function (_super) {
  40401. __extends(DiscGeometry, _super);
  40402. /**
  40403. * Creates a new disc geometry
  40404. * @param id defines the unique ID of the geometry
  40405. * @param scene defines the hosting scene
  40406. * @param radius defines the radius of the disc
  40407. * @param tessellation defines the tesselation factor to apply to the disc
  40408. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40409. * @param mesh defines the hosting mesh (can be null)
  40410. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40411. */
  40412. function DiscGeometry(id, scene,
  40413. /**
  40414. * Defines the radius of the disc
  40415. */
  40416. radius,
  40417. /**
  40418. * Defines the tesselation factor to apply to the disc
  40419. */
  40420. tessellation, canBeRegenerated, mesh,
  40421. /**
  40422. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40423. */
  40424. side) {
  40425. if (mesh === void 0) { mesh = null; }
  40426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40428. _this.radius = radius;
  40429. _this.tessellation = tessellation;
  40430. _this.side = side;
  40431. return _this;
  40432. }
  40433. DiscGeometry.prototype._regenerateVertexData = function () {
  40434. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40435. };
  40436. DiscGeometry.prototype.copy = function (id) {
  40437. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40438. };
  40439. return DiscGeometry;
  40440. }(_PrimitiveGeometry));
  40441. BABYLON.DiscGeometry = DiscGeometry;
  40442. /**
  40443. * Creates a new cylinder geometry
  40444. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40445. */
  40446. var CylinderGeometry = /** @class */ (function (_super) {
  40447. __extends(CylinderGeometry, _super);
  40448. /**
  40449. * Creates a new cylinder geometry
  40450. * @param id defines the unique ID of the geometry
  40451. * @param scene defines the hosting scene
  40452. * @param height defines the height of the cylinder
  40453. * @param diameterTop defines the diameter of the cylinder's top cap
  40454. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40455. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40456. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40457. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40458. * @param mesh defines the hosting mesh (can be null)
  40459. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40460. */
  40461. function CylinderGeometry(id, scene,
  40462. /**
  40463. * Defines the height of the cylinder
  40464. */
  40465. height,
  40466. /**
  40467. * Defines the diameter of the cylinder's top cap
  40468. */
  40469. diameterTop,
  40470. /**
  40471. * Defines the diameter of the cylinder's bottom cap
  40472. */
  40473. diameterBottom,
  40474. /**
  40475. * Defines the tessellation factor to apply to the cylinder
  40476. */
  40477. tessellation,
  40478. /**
  40479. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40480. */
  40481. subdivisions, canBeRegenerated, mesh,
  40482. /**
  40483. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40484. */
  40485. side) {
  40486. if (subdivisions === void 0) { subdivisions = 1; }
  40487. if (mesh === void 0) { mesh = null; }
  40488. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40490. _this.height = height;
  40491. _this.diameterTop = diameterTop;
  40492. _this.diameterBottom = diameterBottom;
  40493. _this.tessellation = tessellation;
  40494. _this.subdivisions = subdivisions;
  40495. _this.side = side;
  40496. return _this;
  40497. }
  40498. CylinderGeometry.prototype._regenerateVertexData = function () {
  40499. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40500. };
  40501. CylinderGeometry.prototype.copy = function (id) {
  40502. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40503. };
  40504. CylinderGeometry.prototype.serialize = function () {
  40505. var serializationObject = _super.prototype.serialize.call(this);
  40506. serializationObject.height = this.height;
  40507. serializationObject.diameterTop = this.diameterTop;
  40508. serializationObject.diameterBottom = this.diameterBottom;
  40509. serializationObject.tessellation = this.tessellation;
  40510. return serializationObject;
  40511. };
  40512. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40513. if (scene.getGeometryByID(parsedCylinder.id)) {
  40514. return null; // null since geometry could be something else than a cylinder...
  40515. }
  40516. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40517. if (BABYLON.Tags) {
  40518. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40519. }
  40520. scene.pushGeometry(cylinder, true);
  40521. return cylinder;
  40522. };
  40523. return CylinderGeometry;
  40524. }(_PrimitiveGeometry));
  40525. BABYLON.CylinderGeometry = CylinderGeometry;
  40526. /**
  40527. * Creates a new torus geometry
  40528. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40529. */
  40530. var TorusGeometry = /** @class */ (function (_super) {
  40531. __extends(TorusGeometry, _super);
  40532. /**
  40533. * Creates a new torus geometry
  40534. * @param id defines the unique ID of the geometry
  40535. * @param scene defines the hosting scene
  40536. * @param diameter defines the diameter of the torus
  40537. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40538. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40539. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40540. * @param mesh defines the hosting mesh (can be null)
  40541. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40542. */
  40543. function TorusGeometry(id, scene,
  40544. /**
  40545. * Defines the diameter of the torus
  40546. */
  40547. diameter,
  40548. /**
  40549. * Defines the thickness of the torus (ie. internal diameter)
  40550. */
  40551. thickness,
  40552. /**
  40553. * Defines the tesselation factor to apply to the torus
  40554. */
  40555. tessellation, canBeRegenerated, mesh,
  40556. /**
  40557. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40558. */
  40559. side) {
  40560. if (mesh === void 0) { mesh = null; }
  40561. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40562. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40563. _this.diameter = diameter;
  40564. _this.thickness = thickness;
  40565. _this.tessellation = tessellation;
  40566. _this.side = side;
  40567. return _this;
  40568. }
  40569. TorusGeometry.prototype._regenerateVertexData = function () {
  40570. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40571. };
  40572. TorusGeometry.prototype.copy = function (id) {
  40573. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40574. };
  40575. TorusGeometry.prototype.serialize = function () {
  40576. var serializationObject = _super.prototype.serialize.call(this);
  40577. serializationObject.diameter = this.diameter;
  40578. serializationObject.thickness = this.thickness;
  40579. serializationObject.tessellation = this.tessellation;
  40580. return serializationObject;
  40581. };
  40582. TorusGeometry.Parse = function (parsedTorus, scene) {
  40583. if (scene.getGeometryByID(parsedTorus.id)) {
  40584. return null; // null since geometry could be something else than a torus...
  40585. }
  40586. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40587. if (BABYLON.Tags) {
  40588. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40589. }
  40590. scene.pushGeometry(torus, true);
  40591. return torus;
  40592. };
  40593. return TorusGeometry;
  40594. }(_PrimitiveGeometry));
  40595. BABYLON.TorusGeometry = TorusGeometry;
  40596. /**
  40597. * Creates a new ground geometry
  40598. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40599. */
  40600. var GroundGeometry = /** @class */ (function (_super) {
  40601. __extends(GroundGeometry, _super);
  40602. /**
  40603. * Creates a new ground geometry
  40604. * @param id defines the unique ID of the geometry
  40605. * @param scene defines the hosting scene
  40606. * @param width defines the width of the ground
  40607. * @param height defines the height of the ground
  40608. * @param subdivisions defines the subdivisions to apply to the ground
  40609. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40610. * @param mesh defines the hosting mesh (can be null)
  40611. */
  40612. function GroundGeometry(id, scene,
  40613. /**
  40614. * Defines the width of the ground
  40615. */
  40616. width,
  40617. /**
  40618. * Defines the height of the ground
  40619. */
  40620. height,
  40621. /**
  40622. * Defines the subdivisions to apply to the ground
  40623. */
  40624. subdivisions, canBeRegenerated, mesh) {
  40625. if (mesh === void 0) { mesh = null; }
  40626. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40627. _this.width = width;
  40628. _this.height = height;
  40629. _this.subdivisions = subdivisions;
  40630. return _this;
  40631. }
  40632. GroundGeometry.prototype._regenerateVertexData = function () {
  40633. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40634. };
  40635. GroundGeometry.prototype.copy = function (id) {
  40636. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40637. };
  40638. GroundGeometry.prototype.serialize = function () {
  40639. var serializationObject = _super.prototype.serialize.call(this);
  40640. serializationObject.width = this.width;
  40641. serializationObject.height = this.height;
  40642. serializationObject.subdivisions = this.subdivisions;
  40643. return serializationObject;
  40644. };
  40645. GroundGeometry.Parse = function (parsedGround, scene) {
  40646. if (scene.getGeometryByID(parsedGround.id)) {
  40647. return null; // null since geometry could be something else than a ground...
  40648. }
  40649. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40650. if (BABYLON.Tags) {
  40651. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40652. }
  40653. scene.pushGeometry(ground, true);
  40654. return ground;
  40655. };
  40656. return GroundGeometry;
  40657. }(_PrimitiveGeometry));
  40658. BABYLON.GroundGeometry = GroundGeometry;
  40659. /**
  40660. * Creates a tiled ground geometry
  40661. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40662. */
  40663. var TiledGroundGeometry = /** @class */ (function (_super) {
  40664. __extends(TiledGroundGeometry, _super);
  40665. /**
  40666. * Creates a tiled ground geometry
  40667. * @param id defines the unique ID of the geometry
  40668. * @param scene defines the hosting scene
  40669. * @param xmin defines the minimum value on X axis
  40670. * @param zmin defines the minimum value on Z axis
  40671. * @param xmax defines the maximum value on X axis
  40672. * @param zmax defines the maximum value on Z axis
  40673. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40674. * @param precision defines the precision to use when computing the tiles
  40675. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40676. * @param mesh defines the hosting mesh (can be null)
  40677. */
  40678. function TiledGroundGeometry(id, scene,
  40679. /**
  40680. * Defines the minimum value on X axis
  40681. */
  40682. xmin,
  40683. /**
  40684. * Defines the minimum value on Z axis
  40685. */
  40686. zmin,
  40687. /**
  40688. * Defines the maximum value on X axis
  40689. */
  40690. xmax,
  40691. /**
  40692. * Defines the maximum value on Z axis
  40693. */
  40694. zmax,
  40695. /**
  40696. * Defines the subdivisions to apply to the ground
  40697. */
  40698. subdivisions,
  40699. /**
  40700. * Defines the precision to use when computing the tiles
  40701. */
  40702. precision, canBeRegenerated, mesh) {
  40703. if (mesh === void 0) { mesh = null; }
  40704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40705. _this.xmin = xmin;
  40706. _this.zmin = zmin;
  40707. _this.xmax = xmax;
  40708. _this.zmax = zmax;
  40709. _this.subdivisions = subdivisions;
  40710. _this.precision = precision;
  40711. return _this;
  40712. }
  40713. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40714. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40715. };
  40716. TiledGroundGeometry.prototype.copy = function (id) {
  40717. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40718. };
  40719. return TiledGroundGeometry;
  40720. }(_PrimitiveGeometry));
  40721. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40722. /**
  40723. * Creates a plane geometry
  40724. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40725. */
  40726. var PlaneGeometry = /** @class */ (function (_super) {
  40727. __extends(PlaneGeometry, _super);
  40728. /**
  40729. * Creates a plane geometry
  40730. * @param id defines the unique ID of the geometry
  40731. * @param scene defines the hosting scene
  40732. * @param size defines the size of the plane (width === height)
  40733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40734. * @param mesh defines the hosting mesh (can be null)
  40735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40736. */
  40737. function PlaneGeometry(id, scene,
  40738. /**
  40739. * Defines the size of the plane (width === height)
  40740. */
  40741. size, canBeRegenerated, mesh,
  40742. /**
  40743. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40744. */
  40745. side) {
  40746. if (mesh === void 0) { mesh = null; }
  40747. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40748. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40749. _this.size = size;
  40750. _this.side = side;
  40751. return _this;
  40752. }
  40753. PlaneGeometry.prototype._regenerateVertexData = function () {
  40754. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40755. };
  40756. PlaneGeometry.prototype.copy = function (id) {
  40757. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40758. };
  40759. PlaneGeometry.prototype.serialize = function () {
  40760. var serializationObject = _super.prototype.serialize.call(this);
  40761. serializationObject.size = this.size;
  40762. return serializationObject;
  40763. };
  40764. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40765. if (scene.getGeometryByID(parsedPlane.id)) {
  40766. return null; // null since geometry could be something else than a ground...
  40767. }
  40768. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40769. if (BABYLON.Tags) {
  40770. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40771. }
  40772. scene.pushGeometry(plane, true);
  40773. return plane;
  40774. };
  40775. return PlaneGeometry;
  40776. }(_PrimitiveGeometry));
  40777. BABYLON.PlaneGeometry = PlaneGeometry;
  40778. /**
  40779. * Creates a torus knot geometry
  40780. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40781. */
  40782. var TorusKnotGeometry = /** @class */ (function (_super) {
  40783. __extends(TorusKnotGeometry, _super);
  40784. /**
  40785. * Creates a torus knot geometry
  40786. * @param id defines the unique ID of the geometry
  40787. * @param scene defines the hosting scene
  40788. * @param radius defines the radius of the torus knot
  40789. * @param tube defines the thickness of the torus knot tube
  40790. * @param radialSegments defines the number of radial segments
  40791. * @param tubularSegments defines the number of tubular segments
  40792. * @param p defines the first number of windings
  40793. * @param q defines the second number of windings
  40794. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40795. * @param mesh defines the hosting mesh (can be null)
  40796. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40797. */
  40798. function TorusKnotGeometry(id, scene,
  40799. /**
  40800. * Defines the radius of the torus knot
  40801. */
  40802. radius,
  40803. /**
  40804. * Defines the thickness of the torus knot tube
  40805. */
  40806. tube,
  40807. /**
  40808. * Defines the number of radial segments
  40809. */
  40810. radialSegments,
  40811. /**
  40812. * Defines the number of tubular segments
  40813. */
  40814. tubularSegments,
  40815. /**
  40816. * Defines the first number of windings
  40817. */
  40818. p,
  40819. /**
  40820. * Defines the second number of windings
  40821. */
  40822. q, canBeRegenerated, mesh,
  40823. /**
  40824. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40825. */
  40826. side) {
  40827. if (mesh === void 0) { mesh = null; }
  40828. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40829. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40830. _this.radius = radius;
  40831. _this.tube = tube;
  40832. _this.radialSegments = radialSegments;
  40833. _this.tubularSegments = tubularSegments;
  40834. _this.p = p;
  40835. _this.q = q;
  40836. _this.side = side;
  40837. return _this;
  40838. }
  40839. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40840. 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 });
  40841. };
  40842. TorusKnotGeometry.prototype.copy = function (id) {
  40843. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40844. };
  40845. TorusKnotGeometry.prototype.serialize = function () {
  40846. var serializationObject = _super.prototype.serialize.call(this);
  40847. serializationObject.radius = this.radius;
  40848. serializationObject.tube = this.tube;
  40849. serializationObject.radialSegments = this.radialSegments;
  40850. serializationObject.tubularSegments = this.tubularSegments;
  40851. serializationObject.p = this.p;
  40852. serializationObject.q = this.q;
  40853. return serializationObject;
  40854. };
  40855. ;
  40856. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40857. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40858. return null; // null since geometry could be something else than a ground...
  40859. }
  40860. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40861. if (BABYLON.Tags) {
  40862. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40863. }
  40864. scene.pushGeometry(torusKnot, true);
  40865. return torusKnot;
  40866. };
  40867. return TorusKnotGeometry;
  40868. }(_PrimitiveGeometry));
  40869. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40870. //}
  40871. })(BABYLON || (BABYLON = {}));
  40872. //# sourceMappingURL=babylon.geometry.js.map
  40873. var BABYLON;
  40874. (function (BABYLON) {
  40875. /**
  40876. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40877. */
  40878. var PerformanceMonitor = /** @class */ (function () {
  40879. /**
  40880. * constructor
  40881. * @param frameSampleSize The number of samples required to saturate the sliding window
  40882. */
  40883. function PerformanceMonitor(frameSampleSize) {
  40884. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40885. this._enabled = true;
  40886. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40887. }
  40888. /**
  40889. * Samples current frame
  40890. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40891. */
  40892. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40893. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40894. if (!this._enabled)
  40895. return;
  40896. if (this._lastFrameTimeMs != null) {
  40897. var dt = timeMs - this._lastFrameTimeMs;
  40898. this._rollingFrameTime.add(dt);
  40899. }
  40900. this._lastFrameTimeMs = timeMs;
  40901. };
  40902. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40903. /**
  40904. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40905. * @return Average frame time in milliseconds
  40906. */
  40907. get: function () {
  40908. return this._rollingFrameTime.average;
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40914. /**
  40915. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40916. * @return Frame time variance in milliseconds squared
  40917. */
  40918. get: function () {
  40919. return this._rollingFrameTime.variance;
  40920. },
  40921. enumerable: true,
  40922. configurable: true
  40923. });
  40924. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40925. /**
  40926. * Returns the frame time of the most recent frame
  40927. * @return Frame time in milliseconds
  40928. */
  40929. get: function () {
  40930. return this._rollingFrameTime.history(0);
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40936. /**
  40937. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40938. * @return Framerate in frames per second
  40939. */
  40940. get: function () {
  40941. return 1000.0 / this._rollingFrameTime.average;
  40942. },
  40943. enumerable: true,
  40944. configurable: true
  40945. });
  40946. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40947. /**
  40948. * Returns the average framerate in frames per second using the most recent frame time
  40949. * @return Framerate in frames per second
  40950. */
  40951. get: function () {
  40952. var history = this._rollingFrameTime.history(0);
  40953. if (history === 0) {
  40954. return 0;
  40955. }
  40956. return 1000.0 / history;
  40957. },
  40958. enumerable: true,
  40959. configurable: true
  40960. });
  40961. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40962. /**
  40963. * Returns true if enough samples have been taken to completely fill the sliding window
  40964. * @return true if saturated
  40965. */
  40966. get: function () {
  40967. return this._rollingFrameTime.isSaturated();
  40968. },
  40969. enumerable: true,
  40970. configurable: true
  40971. });
  40972. /**
  40973. * Enables contributions to the sliding window sample set
  40974. */
  40975. PerformanceMonitor.prototype.enable = function () {
  40976. this._enabled = true;
  40977. };
  40978. /**
  40979. * Disables contributions to the sliding window sample set
  40980. * Samples will not be interpolated over the disabled period
  40981. */
  40982. PerformanceMonitor.prototype.disable = function () {
  40983. this._enabled = false;
  40984. //clear last sample to avoid interpolating over the disabled period when next enabled
  40985. this._lastFrameTimeMs = null;
  40986. };
  40987. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40988. /**
  40989. * Returns true if sampling is enabled
  40990. * @return true if enabled
  40991. */
  40992. get: function () {
  40993. return this._enabled;
  40994. },
  40995. enumerable: true,
  40996. configurable: true
  40997. });
  40998. /**
  40999. * Resets performance monitor
  41000. */
  41001. PerformanceMonitor.prototype.reset = function () {
  41002. //clear last sample to avoid interpolating over the disabled period when next enabled
  41003. this._lastFrameTimeMs = null;
  41004. //wipe record
  41005. this._rollingFrameTime.reset();
  41006. };
  41007. return PerformanceMonitor;
  41008. }());
  41009. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41010. /**
  41011. * RollingAverage
  41012. *
  41013. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41014. */
  41015. var RollingAverage = /** @class */ (function () {
  41016. /**
  41017. * constructor
  41018. * @param length The number of samples required to saturate the sliding window
  41019. */
  41020. function RollingAverage(length) {
  41021. this._samples = new Array(length);
  41022. this.reset();
  41023. }
  41024. /**
  41025. * Adds a sample to the sample set
  41026. * @param v The sample value
  41027. */
  41028. RollingAverage.prototype.add = function (v) {
  41029. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41030. var delta;
  41031. //we need to check if we've already wrapped round
  41032. if (this.isSaturated()) {
  41033. //remove bottom of stack from mean
  41034. var bottomValue = this._samples[this._pos];
  41035. delta = bottomValue - this.average;
  41036. this.average -= delta / (this._sampleCount - 1);
  41037. this._m2 -= delta * (bottomValue - this.average);
  41038. }
  41039. else {
  41040. this._sampleCount++;
  41041. }
  41042. //add new value to mean
  41043. delta = v - this.average;
  41044. this.average += delta / (this._sampleCount);
  41045. this._m2 += delta * (v - this.average);
  41046. //set the new variance
  41047. this.variance = this._m2 / (this._sampleCount - 1);
  41048. this._samples[this._pos] = v;
  41049. this._pos++;
  41050. this._pos %= this._samples.length; //positive wrap around
  41051. };
  41052. /**
  41053. * Returns previously added values or null if outside of history or outside the sliding window domain
  41054. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41055. * @return Value previously recorded with add() or null if outside of range
  41056. */
  41057. RollingAverage.prototype.history = function (i) {
  41058. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41059. return 0;
  41060. }
  41061. var i0 = this._wrapPosition(this._pos - 1.0);
  41062. return this._samples[this._wrapPosition(i0 - i)];
  41063. };
  41064. /**
  41065. * Returns true if enough samples have been taken to completely fill the sliding window
  41066. * @return true if sample-set saturated
  41067. */
  41068. RollingAverage.prototype.isSaturated = function () {
  41069. return this._sampleCount >= this._samples.length;
  41070. };
  41071. /**
  41072. * Resets the rolling average (equivalent to 0 samples taken so far)
  41073. */
  41074. RollingAverage.prototype.reset = function () {
  41075. this.average = 0;
  41076. this.variance = 0;
  41077. this._sampleCount = 0;
  41078. this._pos = 0;
  41079. this._m2 = 0;
  41080. };
  41081. /**
  41082. * Wraps a value around the sample range boundaries
  41083. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41084. * @return Wrapped position in sample range
  41085. */
  41086. RollingAverage.prototype._wrapPosition = function (i) {
  41087. var max = this._samples.length;
  41088. return ((i % max) + max) % max;
  41089. };
  41090. return RollingAverage;
  41091. }());
  41092. BABYLON.RollingAverage = RollingAverage;
  41093. })(BABYLON || (BABYLON = {}));
  41094. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41095. var BABYLON;
  41096. (function (BABYLON) {
  41097. /**
  41098. * "Static Class" containing the most commonly used helper while dealing with material for
  41099. * rendering purpose.
  41100. *
  41101. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41102. *
  41103. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41104. */
  41105. var MaterialHelper = /** @class */ (function () {
  41106. function MaterialHelper() {
  41107. }
  41108. /**
  41109. * Bind the current view position to an effect.
  41110. * @param effect The effect to be bound
  41111. * @param scene The scene the eyes position is used from
  41112. */
  41113. MaterialHelper.BindEyePosition = function (effect, scene) {
  41114. if (scene._forcedViewPosition) {
  41115. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41116. return;
  41117. }
  41118. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41119. };
  41120. /**
  41121. * Helps preparing the defines values about the UVs in used in the effect.
  41122. * UVs are shared as much as we can accross chanels in the shaders.
  41123. * @param texture The texture we are preparing the UVs for
  41124. * @param defines The defines to update
  41125. * @param key The chanel key "diffuse", "specular"... used in the shader
  41126. */
  41127. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41128. defines._needUVs = true;
  41129. defines[key] = true;
  41130. if (texture.getTextureMatrix().isIdentity(true)) {
  41131. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41132. if (texture.coordinatesIndex === 0) {
  41133. defines["MAINUV1"] = true;
  41134. }
  41135. else {
  41136. defines["MAINUV2"] = true;
  41137. }
  41138. }
  41139. else {
  41140. defines[key + "DIRECTUV"] = 0;
  41141. }
  41142. };
  41143. /**
  41144. * Binds a texture matrix value to its corrsponding uniform
  41145. * @param texture The texture to bind the matrix for
  41146. * @param uniformBuffer The uniform buffer receivin the data
  41147. * @param key The chanel key "diffuse", "specular"... used in the shader
  41148. */
  41149. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41150. var matrix = texture.getTextureMatrix();
  41151. if (!matrix.isIdentity(true)) {
  41152. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41153. }
  41154. };
  41155. /**
  41156. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41157. * @param mesh defines the current mesh
  41158. * @param scene defines the current scene
  41159. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41160. * @param pointsCloud defines if point cloud rendering has to be turned on
  41161. * @param fogEnabled defines if fog has to be turned on
  41162. * @param alphaTest defines if alpha testing has to be turned on
  41163. * @param defines defines the current list of defines
  41164. */
  41165. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41166. if (defines._areMiscDirty) {
  41167. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41168. defines["POINTSIZE"] = pointsCloud;
  41169. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41170. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41171. defines["ALPHATEST"] = alphaTest;
  41172. }
  41173. };
  41174. /**
  41175. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41176. * @param scene defines the current scene
  41177. * @param engine defines the current engine
  41178. * @param defines specifies the list of active defines
  41179. * @param useInstances defines if instances have to be turned on
  41180. * @param useClipPlane defines if clip plane have to be turned on
  41181. */
  41182. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41183. if (useClipPlane === void 0) { useClipPlane = null; }
  41184. var changed = false;
  41185. if (useClipPlane == null) {
  41186. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41187. }
  41188. if (defines["CLIPPLANE"] !== useClipPlane) {
  41189. defines["CLIPPLANE"] = useClipPlane;
  41190. changed = true;
  41191. }
  41192. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41193. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41194. changed = true;
  41195. }
  41196. if (defines["INSTANCES"] !== useInstances) {
  41197. defines["INSTANCES"] = useInstances;
  41198. changed = true;
  41199. }
  41200. if (changed) {
  41201. defines.markAsUnprocessed();
  41202. }
  41203. };
  41204. /**
  41205. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41206. * @param mesh The mesh containing the geometry data we will draw
  41207. * @param defines The defines to update
  41208. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41209. * @param useBones Precise whether bones should be used or not (override mesh info)
  41210. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41211. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41212. * @returns false if defines are considered not dirty and have not been checked
  41213. */
  41214. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41215. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41216. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41217. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41218. return false;
  41219. }
  41220. defines._normals = defines._needNormals;
  41221. defines._uvs = defines._needUVs;
  41222. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41223. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41224. defines["TANGENT"] = true;
  41225. }
  41226. if (defines._needUVs) {
  41227. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41228. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41229. }
  41230. else {
  41231. defines["UV1"] = false;
  41232. defines["UV2"] = false;
  41233. }
  41234. if (useVertexColor) {
  41235. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41236. defines["VERTEXCOLOR"] = hasVertexColors;
  41237. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41238. }
  41239. if (useBones) {
  41240. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41241. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41242. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41243. }
  41244. else {
  41245. defines["NUM_BONE_INFLUENCERS"] = 0;
  41246. defines["BonesPerMesh"] = 0;
  41247. }
  41248. }
  41249. if (useMorphTargets) {
  41250. var manager = mesh.morphTargetManager;
  41251. if (manager) {
  41252. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41253. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41254. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41255. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41256. }
  41257. else {
  41258. defines["MORPHTARGETS_TANGENT"] = false;
  41259. defines["MORPHTARGETS_NORMAL"] = false;
  41260. defines["MORPHTARGETS"] = false;
  41261. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41262. }
  41263. }
  41264. return true;
  41265. };
  41266. /**
  41267. * Prepares the defines related to the light information passed in parameter
  41268. * @param scene The scene we are intending to draw
  41269. * @param mesh The mesh the effect is compiling for
  41270. * @param defines The defines to update
  41271. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41272. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41273. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41274. * @returns true if normals will be required for the rest of the effect
  41275. */
  41276. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41277. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41278. if (disableLighting === void 0) { disableLighting = false; }
  41279. if (!defines._areLightsDirty) {
  41280. return defines._needNormals;
  41281. }
  41282. var lightIndex = 0;
  41283. var needNormals = false;
  41284. var needRebuild = false;
  41285. var lightmapMode = false;
  41286. var shadowEnabled = false;
  41287. var specularEnabled = false;
  41288. if (scene.lightsEnabled && !disableLighting) {
  41289. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41290. var light = _a[_i];
  41291. needNormals = true;
  41292. if (defines["LIGHT" + lightIndex] === undefined) {
  41293. needRebuild = true;
  41294. }
  41295. defines["LIGHT" + lightIndex] = true;
  41296. defines["SPOTLIGHT" + lightIndex] = false;
  41297. defines["HEMILIGHT" + lightIndex] = false;
  41298. defines["POINTLIGHT" + lightIndex] = false;
  41299. defines["DIRLIGHT" + lightIndex] = false;
  41300. var type;
  41301. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41302. type = "SPOTLIGHT" + lightIndex;
  41303. var spotLight = light;
  41304. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41305. }
  41306. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41307. type = "HEMILIGHT" + lightIndex;
  41308. }
  41309. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41310. type = "POINTLIGHT" + lightIndex;
  41311. }
  41312. else {
  41313. type = "DIRLIGHT" + lightIndex;
  41314. }
  41315. defines[type] = true;
  41316. // Specular
  41317. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41318. specularEnabled = true;
  41319. }
  41320. // Shadows
  41321. defines["SHADOW" + lightIndex] = false;
  41322. defines["SHADOWPCF" + lightIndex] = false;
  41323. defines["SHADOWPCSS" + lightIndex] = false;
  41324. defines["SHADOWPOISSON" + lightIndex] = false;
  41325. defines["SHADOWESM" + lightIndex] = false;
  41326. defines["SHADOWCUBE" + lightIndex] = false;
  41327. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41328. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41329. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41330. var shadowGenerator = light.getShadowGenerator();
  41331. if (shadowGenerator) {
  41332. shadowEnabled = true;
  41333. shadowGenerator.prepareDefines(defines, lightIndex);
  41334. }
  41335. }
  41336. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41337. lightmapMode = true;
  41338. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41339. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41340. }
  41341. else {
  41342. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41343. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41344. }
  41345. lightIndex++;
  41346. if (lightIndex === maxSimultaneousLights)
  41347. break;
  41348. }
  41349. }
  41350. defines["SPECULARTERM"] = specularEnabled;
  41351. defines["SHADOWS"] = shadowEnabled;
  41352. // Resetting all other lights if any
  41353. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41354. if (defines["LIGHT" + index] !== undefined) {
  41355. defines["LIGHT" + index] = false;
  41356. defines["HEMILIGHT" + lightIndex] = false;
  41357. defines["POINTLIGHT" + lightIndex] = false;
  41358. defines["DIRLIGHT" + lightIndex] = false;
  41359. defines["SPOTLIGHT" + lightIndex] = false;
  41360. defines["SHADOW" + lightIndex] = false;
  41361. }
  41362. }
  41363. var caps = scene.getEngine().getCaps();
  41364. if (defines["SHADOWFLOAT"] === undefined) {
  41365. needRebuild = true;
  41366. }
  41367. defines["SHADOWFLOAT"] = shadowEnabled &&
  41368. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41369. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41370. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41371. if (needRebuild) {
  41372. defines.rebuild();
  41373. }
  41374. return needNormals;
  41375. };
  41376. /**
  41377. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41378. * that won t be acctive due to defines being turned off.
  41379. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41380. * @param samplersList The samplers list
  41381. * @param defines The defines helping in the list generation
  41382. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41383. */
  41384. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41385. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41386. var uniformsList;
  41387. var uniformBuffersList = null;
  41388. if (uniformsListOrOptions.uniformsNames) {
  41389. var options = uniformsListOrOptions;
  41390. uniformsList = options.uniformsNames;
  41391. uniformBuffersList = options.uniformBuffersNames;
  41392. samplersList = options.samplers;
  41393. defines = options.defines;
  41394. maxSimultaneousLights = options.maxSimultaneousLights;
  41395. }
  41396. else {
  41397. uniformsList = uniformsListOrOptions;
  41398. if (!samplersList) {
  41399. samplersList = [];
  41400. }
  41401. }
  41402. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41403. if (!defines["LIGHT" + lightIndex]) {
  41404. break;
  41405. }
  41406. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41407. if (uniformBuffersList) {
  41408. uniformBuffersList.push("Light" + lightIndex);
  41409. }
  41410. samplersList.push("shadowSampler" + lightIndex);
  41411. samplersList.push("depthSampler" + lightIndex);
  41412. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41413. samplersList.push("projectionLightSampler" + lightIndex);
  41414. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41415. }
  41416. }
  41417. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41418. uniformsList.push("morphTargetInfluences");
  41419. }
  41420. };
  41421. /**
  41422. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41423. * @param defines The defines to update while falling back
  41424. * @param fallbacks The authorized effect fallbacks
  41425. * @param maxSimultaneousLights The maximum number of lights allowed
  41426. * @param rank the current rank of the Effect
  41427. * @returns The newly affected rank
  41428. */
  41429. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41430. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41431. if (rank === void 0) { rank = 0; }
  41432. var lightFallbackRank = 0;
  41433. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41434. if (!defines["LIGHT" + lightIndex]) {
  41435. break;
  41436. }
  41437. if (lightIndex > 0) {
  41438. lightFallbackRank = rank + lightIndex;
  41439. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41440. }
  41441. if (!defines["SHADOWS"]) {
  41442. if (defines["SHADOW" + lightIndex]) {
  41443. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41444. }
  41445. if (defines["SHADOWPCF" + lightIndex]) {
  41446. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41447. }
  41448. if (defines["SHADOWPCSS" + lightIndex]) {
  41449. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41450. }
  41451. if (defines["SHADOWPOISSON" + lightIndex]) {
  41452. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41453. }
  41454. if (defines["SHADOWESM" + lightIndex]) {
  41455. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41456. }
  41457. }
  41458. }
  41459. return lightFallbackRank++;
  41460. };
  41461. /**
  41462. * Prepares the list of attributes required for morph targets according to the effect defines.
  41463. * @param attribs The current list of supported attribs
  41464. * @param mesh The mesh to prepare the morph targets attributes for
  41465. * @param defines The current Defines of the effect
  41466. */
  41467. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41468. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41469. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41470. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41471. var manager = mesh.morphTargetManager;
  41472. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41473. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41474. for (var index = 0; index < influencers; index++) {
  41475. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41476. if (normal) {
  41477. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41478. }
  41479. if (tangent) {
  41480. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41481. }
  41482. if (attribs.length > maxAttributesCount) {
  41483. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41484. }
  41485. }
  41486. }
  41487. };
  41488. /**
  41489. * Prepares the list of attributes required for bones according to the effect defines.
  41490. * @param attribs The current list of supported attribs
  41491. * @param mesh The mesh to prepare the bones attributes for
  41492. * @param defines The current Defines of the effect
  41493. * @param fallbacks The current efffect fallback strategy
  41494. */
  41495. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41496. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41497. fallbacks.addCPUSkinningFallback(0, mesh);
  41498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41500. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41503. }
  41504. }
  41505. };
  41506. /**
  41507. * Prepares the list of attributes required for instances according to the effect defines.
  41508. * @param attribs The current list of supported attribs
  41509. * @param defines The current Defines of the effect
  41510. */
  41511. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41512. if (defines["INSTANCES"]) {
  41513. attribs.push("world0");
  41514. attribs.push("world1");
  41515. attribs.push("world2");
  41516. attribs.push("world3");
  41517. }
  41518. };
  41519. /**
  41520. * Binds the light shadow information to the effect for the given mesh.
  41521. * @param light The light containing the generator
  41522. * @param scene The scene the lights belongs to
  41523. * @param mesh The mesh we are binding the information to render
  41524. * @param lightIndex The light index in the effect used to render the mesh
  41525. * @param effect The effect we are binding the data to
  41526. */
  41527. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41528. if (light.shadowEnabled && mesh.receiveShadows) {
  41529. var shadowGenerator = light.getShadowGenerator();
  41530. if (shadowGenerator) {
  41531. shadowGenerator.bindShadowLight(lightIndex, effect);
  41532. }
  41533. }
  41534. };
  41535. /**
  41536. * Binds the light information to the effect.
  41537. * @param light The light containing the generator
  41538. * @param effect The effect we are binding the data to
  41539. * @param lightIndex The light index in the effect used to render
  41540. */
  41541. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41542. light.transferToEffect(effect, lightIndex + "");
  41543. };
  41544. /**
  41545. * Binds the lights information from the scene to the effect for the given mesh.
  41546. * @param scene The scene the lights belongs to
  41547. * @param mesh The mesh we are binding the information to render
  41548. * @param effect The effect we are binding the data to
  41549. * @param defines The generated defines for the effect
  41550. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41551. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41552. */
  41553. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41554. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41555. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41556. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41557. for (var i = 0; i < len; i++) {
  41558. var light = mesh._lightSources[i];
  41559. var iAsString = i.toString();
  41560. var scaledIntensity = light.getScaledIntensity();
  41561. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41562. MaterialHelper.BindLightProperties(light, effect, i);
  41563. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41564. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41565. if (defines["SPECULARTERM"]) {
  41566. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41567. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41568. }
  41569. // Shadows
  41570. if (scene.shadowsEnabled) {
  41571. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41572. }
  41573. light._uniformBuffer.update();
  41574. }
  41575. };
  41576. /**
  41577. * Binds the fog information from the scene to the effect for the given mesh.
  41578. * @param scene The scene the lights belongs to
  41579. * @param mesh The mesh we are binding the information to render
  41580. * @param effect The effect we are binding the data to
  41581. */
  41582. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41583. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41584. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41585. effect.setColor3("vFogColor", scene.fogColor);
  41586. }
  41587. };
  41588. /**
  41589. * Binds the bones information from the mesh to the effect.
  41590. * @param mesh The mesh we are binding the information to render
  41591. * @param effect The effect we are binding the data to
  41592. */
  41593. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41594. if (!effect || !mesh) {
  41595. return;
  41596. }
  41597. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41598. mesh.computeBonesUsingShaders = false;
  41599. }
  41600. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41601. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41602. if (matrices) {
  41603. effect.setMatrices("mBones", matrices);
  41604. }
  41605. }
  41606. };
  41607. /**
  41608. * Binds the morph targets information from the mesh to the effect.
  41609. * @param abstractMesh The mesh we are binding the information to render
  41610. * @param effect The effect we are binding the data to
  41611. */
  41612. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41613. var manager = abstractMesh.morphTargetManager;
  41614. if (!abstractMesh || !manager) {
  41615. return;
  41616. }
  41617. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41618. };
  41619. /**
  41620. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41621. * @param defines The generated defines used in the effect
  41622. * @param effect The effect we are binding the data to
  41623. * @param scene The scene we are willing to render with logarithmic scale for
  41624. */
  41625. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41626. if (defines["LOGARITHMICDEPTH"]) {
  41627. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41628. }
  41629. };
  41630. /**
  41631. * Binds the clip plane information from the scene to the effect.
  41632. * @param scene The scene the clip plane information are extracted from
  41633. * @param effect The effect we are binding the data to
  41634. */
  41635. MaterialHelper.BindClipPlane = function (effect, scene) {
  41636. if (scene.clipPlane) {
  41637. var clipPlane = scene.clipPlane;
  41638. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41639. }
  41640. };
  41641. return MaterialHelper;
  41642. }());
  41643. BABYLON.MaterialHelper = MaterialHelper;
  41644. })(BABYLON || (BABYLON = {}));
  41645. //# sourceMappingURL=babylon.materialHelper.js.map
  41646. var BABYLON;
  41647. (function (BABYLON) {
  41648. var PushMaterial = /** @class */ (function (_super) {
  41649. __extends(PushMaterial, _super);
  41650. function PushMaterial(name, scene) {
  41651. var _this = _super.call(this, name, scene) || this;
  41652. _this._normalMatrix = new BABYLON.Matrix();
  41653. _this.storeEffectOnSubMeshes = true;
  41654. return _this;
  41655. }
  41656. PushMaterial.prototype.getEffect = function () {
  41657. return this._activeEffect;
  41658. };
  41659. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41660. if (!mesh) {
  41661. return false;
  41662. }
  41663. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41664. return true;
  41665. }
  41666. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41667. };
  41668. /**
  41669. * Binds the given world matrix to the active effect
  41670. *
  41671. * @param world the matrix to bind
  41672. */
  41673. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41674. this._activeEffect.setMatrix("world", world);
  41675. };
  41676. /**
  41677. * Binds the given normal matrix to the active effect
  41678. *
  41679. * @param normalMatrix the matrix to bind
  41680. */
  41681. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41682. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41683. };
  41684. PushMaterial.prototype.bind = function (world, mesh) {
  41685. if (!mesh) {
  41686. return;
  41687. }
  41688. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41689. };
  41690. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41691. if (effect === void 0) { effect = null; }
  41692. _super.prototype._afterBind.call(this, mesh);
  41693. this.getScene()._cachedEffect = effect;
  41694. };
  41695. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41696. if (visibility === void 0) { visibility = 1; }
  41697. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41698. };
  41699. return PushMaterial;
  41700. }(BABYLON.Material));
  41701. BABYLON.PushMaterial = PushMaterial;
  41702. })(BABYLON || (BABYLON = {}));
  41703. //# sourceMappingURL=babylon.pushMaterial.js.map
  41704. var BABYLON;
  41705. (function (BABYLON) {
  41706. /** @hidden */
  41707. var StandardMaterialDefines = /** @class */ (function (_super) {
  41708. __extends(StandardMaterialDefines, _super);
  41709. function StandardMaterialDefines() {
  41710. var _this = _super.call(this) || this;
  41711. _this.MAINUV1 = false;
  41712. _this.MAINUV2 = false;
  41713. _this.DIFFUSE = false;
  41714. _this.DIFFUSEDIRECTUV = 0;
  41715. _this.AMBIENT = false;
  41716. _this.AMBIENTDIRECTUV = 0;
  41717. _this.OPACITY = false;
  41718. _this.OPACITYDIRECTUV = 0;
  41719. _this.OPACITYRGB = false;
  41720. _this.REFLECTION = false;
  41721. _this.EMISSIVE = false;
  41722. _this.EMISSIVEDIRECTUV = 0;
  41723. _this.SPECULAR = false;
  41724. _this.SPECULARDIRECTUV = 0;
  41725. _this.BUMP = false;
  41726. _this.BUMPDIRECTUV = 0;
  41727. _this.PARALLAX = false;
  41728. _this.PARALLAXOCCLUSION = false;
  41729. _this.SPECULAROVERALPHA = false;
  41730. _this.CLIPPLANE = false;
  41731. _this.ALPHATEST = false;
  41732. _this.DEPTHPREPASS = false;
  41733. _this.ALPHAFROMDIFFUSE = false;
  41734. _this.POINTSIZE = false;
  41735. _this.FOG = false;
  41736. _this.SPECULARTERM = false;
  41737. _this.DIFFUSEFRESNEL = false;
  41738. _this.OPACITYFRESNEL = false;
  41739. _this.REFLECTIONFRESNEL = false;
  41740. _this.REFRACTIONFRESNEL = false;
  41741. _this.EMISSIVEFRESNEL = false;
  41742. _this.FRESNEL = false;
  41743. _this.NORMAL = false;
  41744. _this.UV1 = false;
  41745. _this.UV2 = false;
  41746. _this.VERTEXCOLOR = false;
  41747. _this.VERTEXALPHA = false;
  41748. _this.NUM_BONE_INFLUENCERS = 0;
  41749. _this.BonesPerMesh = 0;
  41750. _this.INSTANCES = false;
  41751. _this.GLOSSINESS = false;
  41752. _this.ROUGHNESS = false;
  41753. _this.EMISSIVEASILLUMINATION = false;
  41754. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41755. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41756. _this.LIGHTMAP = false;
  41757. _this.LIGHTMAPDIRECTUV = 0;
  41758. _this.OBJECTSPACE_NORMALMAP = false;
  41759. _this.USELIGHTMAPASSHADOWMAP = false;
  41760. _this.REFLECTIONMAP_3D = false;
  41761. _this.REFLECTIONMAP_SPHERICAL = false;
  41762. _this.REFLECTIONMAP_PLANAR = false;
  41763. _this.REFLECTIONMAP_CUBIC = false;
  41764. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41765. _this.REFLECTIONMAP_PROJECTION = false;
  41766. _this.REFLECTIONMAP_SKYBOX = false;
  41767. _this.REFLECTIONMAP_EXPLICIT = false;
  41768. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41769. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41770. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41771. _this.INVERTCUBICMAP = false;
  41772. _this.LOGARITHMICDEPTH = false;
  41773. _this.REFRACTION = false;
  41774. _this.REFRACTIONMAP_3D = false;
  41775. _this.REFLECTIONOVERALPHA = false;
  41776. _this.TWOSIDEDLIGHTING = false;
  41777. _this.SHADOWFLOAT = false;
  41778. _this.MORPHTARGETS = false;
  41779. _this.MORPHTARGETS_NORMAL = false;
  41780. _this.MORPHTARGETS_TANGENT = false;
  41781. _this.NUM_MORPH_INFLUENCERS = 0;
  41782. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41783. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41784. _this.IMAGEPROCESSING = false;
  41785. _this.VIGNETTE = false;
  41786. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41787. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41788. _this.TONEMAPPING = false;
  41789. _this.CONTRAST = false;
  41790. _this.COLORCURVES = false;
  41791. _this.COLORGRADING = false;
  41792. _this.COLORGRADING3D = false;
  41793. _this.SAMPLER3DGREENDEPTH = false;
  41794. _this.SAMPLER3DBGRMAP = false;
  41795. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41796. /**
  41797. * If the reflection texture on this material is in linear color space
  41798. * @hidden
  41799. */
  41800. _this.IS_REFLECTION_LINEAR = false;
  41801. /**
  41802. * If the refraction texture on this material is in linear color space
  41803. * @hidden
  41804. */
  41805. _this.IS_REFRACTION_LINEAR = false;
  41806. _this.EXPOSURE = false;
  41807. _this.rebuild();
  41808. return _this;
  41809. }
  41810. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41811. var modes = [
  41812. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41813. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41814. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41815. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41816. ];
  41817. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41818. var mode = modes_1[_i];
  41819. this[mode] = (mode === modeToEnable);
  41820. }
  41821. };
  41822. return StandardMaterialDefines;
  41823. }(BABYLON.MaterialDefines));
  41824. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41825. var StandardMaterial = /** @class */ (function (_super) {
  41826. __extends(StandardMaterial, _super);
  41827. function StandardMaterial(name, scene) {
  41828. var _this = _super.call(this, name, scene) || this;
  41829. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41830. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41831. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41832. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41833. _this.specularPower = 64;
  41834. _this._useAlphaFromDiffuseTexture = false;
  41835. _this._useEmissiveAsIllumination = false;
  41836. _this._linkEmissiveWithDiffuse = false;
  41837. _this._useSpecularOverAlpha = false;
  41838. _this._useReflectionOverAlpha = false;
  41839. _this._disableLighting = false;
  41840. _this._useObjectSpaceNormalMap = false;
  41841. _this._useParallax = false;
  41842. _this._useParallaxOcclusion = false;
  41843. _this.parallaxScaleBias = 0.05;
  41844. _this._roughness = 0;
  41845. _this.indexOfRefraction = 0.98;
  41846. _this.invertRefractionY = true;
  41847. /**
  41848. * Defines the alpha limits in alpha test mode
  41849. */
  41850. _this.alphaCutOff = 0.4;
  41851. _this._useLightmapAsShadowmap = false;
  41852. _this._useReflectionFresnelFromSpecular = false;
  41853. _this._useGlossinessFromSpecularMapAlpha = false;
  41854. _this._maxSimultaneousLights = 4;
  41855. /**
  41856. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41857. */
  41858. _this._invertNormalMapX = false;
  41859. /**
  41860. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41861. */
  41862. _this._invertNormalMapY = false;
  41863. /**
  41864. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41865. */
  41866. _this._twoSidedLighting = false;
  41867. _this._renderTargets = new BABYLON.SmartArray(16);
  41868. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41869. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41870. // Setup the default processing configuration to the scene.
  41871. _this._attachImageProcessingConfiguration(null);
  41872. _this.getRenderTargetTextures = function () {
  41873. _this._renderTargets.reset();
  41874. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41875. _this._renderTargets.push(_this._reflectionTexture);
  41876. }
  41877. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41878. _this._renderTargets.push(_this._refractionTexture);
  41879. }
  41880. return _this._renderTargets;
  41881. };
  41882. return _this;
  41883. }
  41884. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41885. /**
  41886. * Gets the image processing configuration used either in this material.
  41887. */
  41888. get: function () {
  41889. return this._imageProcessingConfiguration;
  41890. },
  41891. /**
  41892. * Sets the Default image processing configuration used either in the this material.
  41893. *
  41894. * If sets to null, the scene one is in use.
  41895. */
  41896. set: function (value) {
  41897. this._attachImageProcessingConfiguration(value);
  41898. // Ensure the effect will be rebuilt.
  41899. this._markAllSubMeshesAsTexturesDirty();
  41900. },
  41901. enumerable: true,
  41902. configurable: true
  41903. });
  41904. /**
  41905. * Attaches a new image processing configuration to the Standard Material.
  41906. * @param configuration
  41907. */
  41908. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41909. var _this = this;
  41910. if (configuration === this._imageProcessingConfiguration) {
  41911. return;
  41912. }
  41913. // Detaches observer.
  41914. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41915. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41916. }
  41917. // Pick the scene configuration if needed.
  41918. if (!configuration) {
  41919. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41920. }
  41921. else {
  41922. this._imageProcessingConfiguration = configuration;
  41923. }
  41924. // Attaches observer.
  41925. if (this._imageProcessingConfiguration) {
  41926. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41927. _this._markAllSubMeshesAsImageProcessingDirty();
  41928. });
  41929. }
  41930. };
  41931. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41932. /**
  41933. * Gets wether the color curves effect is enabled.
  41934. */
  41935. get: function () {
  41936. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41937. },
  41938. /**
  41939. * Sets wether the color curves effect is enabled.
  41940. */
  41941. set: function (value) {
  41942. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41943. },
  41944. enumerable: true,
  41945. configurable: true
  41946. });
  41947. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41948. /**
  41949. * Gets wether the color grading effect is enabled.
  41950. */
  41951. get: function () {
  41952. return this.imageProcessingConfiguration.colorGradingEnabled;
  41953. },
  41954. /**
  41955. * Gets wether the color grading effect is enabled.
  41956. */
  41957. set: function (value) {
  41958. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41959. },
  41960. enumerable: true,
  41961. configurable: true
  41962. });
  41963. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41964. /**
  41965. * Gets wether tonemapping is enabled or not.
  41966. */
  41967. get: function () {
  41968. return this._imageProcessingConfiguration.toneMappingEnabled;
  41969. },
  41970. /**
  41971. * Sets wether tonemapping is enabled or not
  41972. */
  41973. set: function (value) {
  41974. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41975. },
  41976. enumerable: true,
  41977. configurable: true
  41978. });
  41979. ;
  41980. ;
  41981. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41982. /**
  41983. * The camera exposure used on this material.
  41984. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41985. * This corresponds to a photographic exposure.
  41986. */
  41987. get: function () {
  41988. return this._imageProcessingConfiguration.exposure;
  41989. },
  41990. /**
  41991. * The camera exposure used on this material.
  41992. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41993. * This corresponds to a photographic exposure.
  41994. */
  41995. set: function (value) {
  41996. this._imageProcessingConfiguration.exposure = value;
  41997. },
  41998. enumerable: true,
  41999. configurable: true
  42000. });
  42001. ;
  42002. ;
  42003. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42004. /**
  42005. * Gets The camera contrast used on this material.
  42006. */
  42007. get: function () {
  42008. return this._imageProcessingConfiguration.contrast;
  42009. },
  42010. /**
  42011. * Sets The camera contrast used on this material.
  42012. */
  42013. set: function (value) {
  42014. this._imageProcessingConfiguration.contrast = value;
  42015. },
  42016. enumerable: true,
  42017. configurable: true
  42018. });
  42019. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42020. /**
  42021. * Gets the Color Grading 2D Lookup Texture.
  42022. */
  42023. get: function () {
  42024. return this._imageProcessingConfiguration.colorGradingTexture;
  42025. },
  42026. /**
  42027. * Sets the Color Grading 2D Lookup Texture.
  42028. */
  42029. set: function (value) {
  42030. this._imageProcessingConfiguration.colorGradingTexture = value;
  42031. },
  42032. enumerable: true,
  42033. configurable: true
  42034. });
  42035. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42036. /**
  42037. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42038. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42039. * 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;
  42040. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42041. */
  42042. get: function () {
  42043. return this._imageProcessingConfiguration.colorCurves;
  42044. },
  42045. /**
  42046. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42047. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42048. * 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;
  42049. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42050. */
  42051. set: function (value) {
  42052. this._imageProcessingConfiguration.colorCurves = value;
  42053. },
  42054. enumerable: true,
  42055. configurable: true
  42056. });
  42057. StandardMaterial.prototype.getClassName = function () {
  42058. return "StandardMaterial";
  42059. };
  42060. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42061. get: function () {
  42062. return this._useLogarithmicDepth;
  42063. },
  42064. set: function (value) {
  42065. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42066. this._markAllSubMeshesAsMiscDirty();
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. StandardMaterial.prototype.needAlphaBlending = function () {
  42072. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42073. };
  42074. StandardMaterial.prototype.needAlphaTesting = function () {
  42075. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42076. };
  42077. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42078. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42079. };
  42080. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42081. return this._diffuseTexture;
  42082. };
  42083. /**
  42084. * Child classes can use it to update shaders
  42085. */
  42086. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42087. if (useInstances === void 0) { useInstances = false; }
  42088. if (subMesh.effect && this.isFrozen) {
  42089. if (this._wasPreviouslyReady && subMesh.effect) {
  42090. return true;
  42091. }
  42092. }
  42093. if (!subMesh._materialDefines) {
  42094. subMesh._materialDefines = new StandardMaterialDefines();
  42095. }
  42096. var scene = this.getScene();
  42097. var defines = subMesh._materialDefines;
  42098. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42099. if (defines._renderId === scene.getRenderId()) {
  42100. return true;
  42101. }
  42102. }
  42103. var engine = scene.getEngine();
  42104. // Lights
  42105. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42106. // Textures
  42107. if (defines._areTexturesDirty) {
  42108. defines._needUVs = false;
  42109. defines.MAINUV1 = false;
  42110. defines.MAINUV2 = false;
  42111. if (scene.texturesEnabled) {
  42112. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42113. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42114. return false;
  42115. }
  42116. else {
  42117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42118. }
  42119. }
  42120. else {
  42121. defines.DIFFUSE = false;
  42122. }
  42123. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42124. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42125. return false;
  42126. }
  42127. else {
  42128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42129. }
  42130. }
  42131. else {
  42132. defines.AMBIENT = false;
  42133. }
  42134. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42135. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42136. return false;
  42137. }
  42138. else {
  42139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42140. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42141. }
  42142. }
  42143. else {
  42144. defines.OPACITY = false;
  42145. }
  42146. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42147. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42148. return false;
  42149. }
  42150. else {
  42151. defines._needNormals = true;
  42152. defines.REFLECTION = true;
  42153. defines.ROUGHNESS = (this._roughness > 0);
  42154. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42155. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42156. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42157. switch (this._reflectionTexture.coordinatesMode) {
  42158. case BABYLON.Texture.EXPLICIT_MODE:
  42159. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42160. break;
  42161. case BABYLON.Texture.PLANAR_MODE:
  42162. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42163. break;
  42164. case BABYLON.Texture.PROJECTION_MODE:
  42165. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42166. break;
  42167. case BABYLON.Texture.SKYBOX_MODE:
  42168. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42169. break;
  42170. case BABYLON.Texture.SPHERICAL_MODE:
  42171. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42172. break;
  42173. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42174. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42175. break;
  42176. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42177. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42178. break;
  42179. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42180. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42181. break;
  42182. case BABYLON.Texture.CUBIC_MODE:
  42183. case BABYLON.Texture.INVCUBIC_MODE:
  42184. default:
  42185. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42186. break;
  42187. }
  42188. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42189. }
  42190. }
  42191. else {
  42192. defines.REFLECTION = false;
  42193. }
  42194. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42195. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42196. return false;
  42197. }
  42198. else {
  42199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42200. }
  42201. }
  42202. else {
  42203. defines.EMISSIVE = false;
  42204. }
  42205. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42206. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42207. return false;
  42208. }
  42209. else {
  42210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42211. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42212. }
  42213. }
  42214. else {
  42215. defines.LIGHTMAP = false;
  42216. }
  42217. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42218. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42219. return false;
  42220. }
  42221. else {
  42222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42223. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42224. }
  42225. }
  42226. else {
  42227. defines.SPECULAR = false;
  42228. }
  42229. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42230. // Bump texure can not be not blocking.
  42231. if (!this._bumpTexture.isReady()) {
  42232. return false;
  42233. }
  42234. else {
  42235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42236. defines.PARALLAX = this._useParallax;
  42237. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42238. }
  42239. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42240. }
  42241. else {
  42242. defines.BUMP = false;
  42243. }
  42244. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42245. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42246. return false;
  42247. }
  42248. else {
  42249. defines._needUVs = true;
  42250. defines.REFRACTION = true;
  42251. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42252. }
  42253. }
  42254. else {
  42255. defines.REFRACTION = false;
  42256. }
  42257. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42258. }
  42259. else {
  42260. defines.DIFFUSE = false;
  42261. defines.AMBIENT = false;
  42262. defines.OPACITY = false;
  42263. defines.REFLECTION = false;
  42264. defines.EMISSIVE = false;
  42265. defines.LIGHTMAP = false;
  42266. defines.BUMP = false;
  42267. defines.REFRACTION = false;
  42268. }
  42269. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42270. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42271. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42272. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42273. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42274. }
  42275. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42276. if (!this._imageProcessingConfiguration.isReady()) {
  42277. return false;
  42278. }
  42279. this._imageProcessingConfiguration.prepareDefines(defines);
  42280. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42281. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42282. }
  42283. if (defines._areFresnelDirty) {
  42284. if (StandardMaterial.FresnelEnabled) {
  42285. // Fresnel
  42286. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42287. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42288. this._reflectionFresnelParameters) {
  42289. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42290. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42291. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42292. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42293. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42294. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42295. defines._needNormals = true;
  42296. defines.FRESNEL = true;
  42297. }
  42298. }
  42299. else {
  42300. defines.FRESNEL = false;
  42301. }
  42302. }
  42303. // Misc.
  42304. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42305. // Attribs
  42306. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42307. // Values that need to be evaluated on every frame
  42308. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42309. // Get correct effect
  42310. if (defines.isDirty) {
  42311. defines.markAsProcessed();
  42312. scene.resetCachedMaterial();
  42313. // Fallbacks
  42314. var fallbacks = new BABYLON.EffectFallbacks();
  42315. if (defines.REFLECTION) {
  42316. fallbacks.addFallback(0, "REFLECTION");
  42317. }
  42318. if (defines.SPECULAR) {
  42319. fallbacks.addFallback(0, "SPECULAR");
  42320. }
  42321. if (defines.BUMP) {
  42322. fallbacks.addFallback(0, "BUMP");
  42323. }
  42324. if (defines.PARALLAX) {
  42325. fallbacks.addFallback(1, "PARALLAX");
  42326. }
  42327. if (defines.PARALLAXOCCLUSION) {
  42328. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42329. }
  42330. if (defines.SPECULAROVERALPHA) {
  42331. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42332. }
  42333. if (defines.FOG) {
  42334. fallbacks.addFallback(1, "FOG");
  42335. }
  42336. if (defines.POINTSIZE) {
  42337. fallbacks.addFallback(0, "POINTSIZE");
  42338. }
  42339. if (defines.LOGARITHMICDEPTH) {
  42340. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42341. }
  42342. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42343. if (defines.SPECULARTERM) {
  42344. fallbacks.addFallback(0, "SPECULARTERM");
  42345. }
  42346. if (defines.DIFFUSEFRESNEL) {
  42347. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42348. }
  42349. if (defines.OPACITYFRESNEL) {
  42350. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42351. }
  42352. if (defines.REFLECTIONFRESNEL) {
  42353. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42354. }
  42355. if (defines.EMISSIVEFRESNEL) {
  42356. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42357. }
  42358. if (defines.FRESNEL) {
  42359. fallbacks.addFallback(4, "FRESNEL");
  42360. }
  42361. //Attributes
  42362. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42363. if (defines.NORMAL) {
  42364. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42365. }
  42366. if (defines.UV1) {
  42367. attribs.push(BABYLON.VertexBuffer.UVKind);
  42368. }
  42369. if (defines.UV2) {
  42370. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42371. }
  42372. if (defines.VERTEXCOLOR) {
  42373. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42374. }
  42375. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42376. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42377. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42378. var shaderName = "default";
  42379. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42380. "vFogInfos", "vFogColor", "pointSize",
  42381. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42382. "mBones",
  42383. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42384. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42385. "vReflectionPosition", "vReflectionSize",
  42386. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42387. ];
  42388. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42389. var uniformBuffers = ["Material", "Scene"];
  42390. if (BABYLON.ImageProcessingConfiguration) {
  42391. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42392. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42393. }
  42394. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42395. uniformsNames: uniforms,
  42396. uniformBuffersNames: uniformBuffers,
  42397. samplers: samplers,
  42398. defines: defines,
  42399. maxSimultaneousLights: this._maxSimultaneousLights
  42400. });
  42401. if (this.customShaderNameResolve) {
  42402. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42403. }
  42404. var join = defines.toString();
  42405. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42406. attributes: attribs,
  42407. uniformsNames: uniforms,
  42408. uniformBuffersNames: uniformBuffers,
  42409. samplers: samplers,
  42410. defines: join,
  42411. fallbacks: fallbacks,
  42412. onCompiled: this.onCompiled,
  42413. onError: this.onError,
  42414. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42415. }, engine), defines);
  42416. this.buildUniformLayout();
  42417. }
  42418. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42419. return false;
  42420. }
  42421. defines._renderId = scene.getRenderId();
  42422. this._wasPreviouslyReady = true;
  42423. return true;
  42424. };
  42425. StandardMaterial.prototype.buildUniformLayout = function () {
  42426. // Order is important !
  42427. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42428. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42429. this._uniformBuffer.addUniform("opacityParts", 4);
  42430. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42431. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42432. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42433. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42434. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42435. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42436. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42437. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42438. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42439. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42440. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42441. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42442. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42443. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42444. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42445. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42446. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42447. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42448. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42449. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42450. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42451. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42452. this._uniformBuffer.addUniform("specularMatrix", 16);
  42453. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42454. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42455. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42456. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42457. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42458. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42459. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42460. this._uniformBuffer.addUniform("pointSize", 1);
  42461. this._uniformBuffer.create();
  42462. };
  42463. StandardMaterial.prototype.unbind = function () {
  42464. if (this._activeEffect) {
  42465. var needFlag = false;
  42466. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42467. this._activeEffect.setTexture("reflection2DSampler", null);
  42468. needFlag = true;
  42469. }
  42470. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42471. this._activeEffect.setTexture("refraction2DSampler", null);
  42472. needFlag = true;
  42473. }
  42474. if (needFlag) {
  42475. this._markAllSubMeshesAsTexturesDirty();
  42476. }
  42477. }
  42478. _super.prototype.unbind.call(this);
  42479. };
  42480. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42481. var scene = this.getScene();
  42482. var defines = subMesh._materialDefines;
  42483. if (!defines) {
  42484. return;
  42485. }
  42486. var effect = subMesh.effect;
  42487. if (!effect) {
  42488. return;
  42489. }
  42490. this._activeEffect = effect;
  42491. // Matrices
  42492. this.bindOnlyWorldMatrix(world);
  42493. // Normal Matrix
  42494. if (defines.OBJECTSPACE_NORMALMAP) {
  42495. world.toNormalMatrix(this._normalMatrix);
  42496. this.bindOnlyNormalMatrix(this._normalMatrix);
  42497. }
  42498. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42499. // Bones
  42500. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42501. if (mustRebind) {
  42502. this._uniformBuffer.bindToEffect(effect, "Material");
  42503. this.bindViewProjection(effect);
  42504. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42505. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42506. // Fresnel
  42507. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42508. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42509. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42510. }
  42511. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42512. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42513. }
  42514. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42515. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42516. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42517. }
  42518. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42519. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42520. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42521. }
  42522. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42523. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42524. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42525. }
  42526. }
  42527. // Textures
  42528. if (scene.texturesEnabled) {
  42529. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42530. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42531. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42532. if (this._diffuseTexture.hasAlpha) {
  42533. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42534. }
  42535. }
  42536. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42537. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42538. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42539. }
  42540. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42541. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42542. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42543. }
  42544. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42545. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42546. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42547. if (this._reflectionTexture.boundingBoxSize) {
  42548. var cubeTexture = this._reflectionTexture;
  42549. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42550. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42551. }
  42552. }
  42553. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42554. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42555. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42556. }
  42557. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42558. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42559. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42560. }
  42561. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42562. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42563. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42564. }
  42565. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42566. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42567. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42568. if (scene._mirroredCameraPosition) {
  42569. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42570. }
  42571. else {
  42572. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42573. }
  42574. }
  42575. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42576. var depth = 1.0;
  42577. if (!this._refractionTexture.isCube) {
  42578. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42579. if (this._refractionTexture.depth) {
  42580. depth = this._refractionTexture.depth;
  42581. }
  42582. }
  42583. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42584. }
  42585. }
  42586. // Point size
  42587. if (this.pointsCloud) {
  42588. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42589. }
  42590. if (defines.SPECULARTERM) {
  42591. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42592. }
  42593. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42594. // Diffuse
  42595. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42596. }
  42597. // Textures
  42598. if (scene.texturesEnabled) {
  42599. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42600. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42601. }
  42602. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42603. effect.setTexture("ambientSampler", this._ambientTexture);
  42604. }
  42605. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42606. effect.setTexture("opacitySampler", this._opacityTexture);
  42607. }
  42608. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42609. if (this._reflectionTexture.isCube) {
  42610. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42611. }
  42612. else {
  42613. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42614. }
  42615. }
  42616. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42617. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42618. }
  42619. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42620. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42621. }
  42622. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42623. effect.setTexture("specularSampler", this._specularTexture);
  42624. }
  42625. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42626. effect.setTexture("bumpSampler", this._bumpTexture);
  42627. }
  42628. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42629. var depth = 1.0;
  42630. if (this._refractionTexture.isCube) {
  42631. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42632. }
  42633. else {
  42634. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42635. }
  42636. }
  42637. }
  42638. // Clip plane
  42639. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42640. // Colors
  42641. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42642. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42643. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42644. }
  42645. if (mustRebind || !this.isFrozen) {
  42646. // Lights
  42647. if (scene.lightsEnabled && !this._disableLighting) {
  42648. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42649. }
  42650. // View
  42651. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42652. this.bindView(effect);
  42653. }
  42654. // Fog
  42655. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42656. // Morph targets
  42657. if (defines.NUM_MORPH_INFLUENCERS) {
  42658. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42659. }
  42660. // Log. depth
  42661. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42662. // image processing
  42663. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42664. this._imageProcessingConfiguration.bind(this._activeEffect);
  42665. }
  42666. }
  42667. this._uniformBuffer.update();
  42668. this._afterBind(mesh, this._activeEffect);
  42669. };
  42670. StandardMaterial.prototype.getAnimatables = function () {
  42671. var results = [];
  42672. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42673. results.push(this._diffuseTexture);
  42674. }
  42675. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42676. results.push(this._ambientTexture);
  42677. }
  42678. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42679. results.push(this._opacityTexture);
  42680. }
  42681. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42682. results.push(this._reflectionTexture);
  42683. }
  42684. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42685. results.push(this._emissiveTexture);
  42686. }
  42687. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42688. results.push(this._specularTexture);
  42689. }
  42690. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42691. results.push(this._bumpTexture);
  42692. }
  42693. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42694. results.push(this._lightmapTexture);
  42695. }
  42696. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42697. results.push(this._refractionTexture);
  42698. }
  42699. return results;
  42700. };
  42701. StandardMaterial.prototype.getActiveTextures = function () {
  42702. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42703. if (this._diffuseTexture) {
  42704. activeTextures.push(this._diffuseTexture);
  42705. }
  42706. if (this._ambientTexture) {
  42707. activeTextures.push(this._ambientTexture);
  42708. }
  42709. if (this._opacityTexture) {
  42710. activeTextures.push(this._opacityTexture);
  42711. }
  42712. if (this._reflectionTexture) {
  42713. activeTextures.push(this._reflectionTexture);
  42714. }
  42715. if (this._emissiveTexture) {
  42716. activeTextures.push(this._emissiveTexture);
  42717. }
  42718. if (this._specularTexture) {
  42719. activeTextures.push(this._specularTexture);
  42720. }
  42721. if (this._bumpTexture) {
  42722. activeTextures.push(this._bumpTexture);
  42723. }
  42724. if (this._lightmapTexture) {
  42725. activeTextures.push(this._lightmapTexture);
  42726. }
  42727. if (this._refractionTexture) {
  42728. activeTextures.push(this._refractionTexture);
  42729. }
  42730. return activeTextures;
  42731. };
  42732. StandardMaterial.prototype.hasTexture = function (texture) {
  42733. if (_super.prototype.hasTexture.call(this, texture)) {
  42734. return true;
  42735. }
  42736. if (this._diffuseTexture === texture) {
  42737. return true;
  42738. }
  42739. if (this._ambientTexture === texture) {
  42740. return true;
  42741. }
  42742. if (this._opacityTexture === texture) {
  42743. return true;
  42744. }
  42745. if (this._reflectionTexture === texture) {
  42746. return true;
  42747. }
  42748. if (this._emissiveTexture === texture) {
  42749. return true;
  42750. }
  42751. if (this._specularTexture === texture) {
  42752. return true;
  42753. }
  42754. if (this._bumpTexture === texture) {
  42755. return true;
  42756. }
  42757. if (this._lightmapTexture === texture) {
  42758. return true;
  42759. }
  42760. if (this._refractionTexture === texture) {
  42761. return true;
  42762. }
  42763. return false;
  42764. };
  42765. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42766. if (forceDisposeTextures) {
  42767. if (this._diffuseTexture) {
  42768. this._diffuseTexture.dispose();
  42769. }
  42770. if (this._ambientTexture) {
  42771. this._ambientTexture.dispose();
  42772. }
  42773. if (this._opacityTexture) {
  42774. this._opacityTexture.dispose();
  42775. }
  42776. if (this._reflectionTexture) {
  42777. this._reflectionTexture.dispose();
  42778. }
  42779. if (this._emissiveTexture) {
  42780. this._emissiveTexture.dispose();
  42781. }
  42782. if (this._specularTexture) {
  42783. this._specularTexture.dispose();
  42784. }
  42785. if (this._bumpTexture) {
  42786. this._bumpTexture.dispose();
  42787. }
  42788. if (this._lightmapTexture) {
  42789. this._lightmapTexture.dispose();
  42790. }
  42791. if (this._refractionTexture) {
  42792. this._refractionTexture.dispose();
  42793. }
  42794. }
  42795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42797. }
  42798. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42799. };
  42800. StandardMaterial.prototype.clone = function (name) {
  42801. var _this = this;
  42802. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42803. result.name = name;
  42804. result.id = name;
  42805. return result;
  42806. };
  42807. StandardMaterial.prototype.serialize = function () {
  42808. return BABYLON.SerializationHelper.Serialize(this);
  42809. };
  42810. // Statics
  42811. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42812. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42813. };
  42814. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42815. get: function () {
  42816. return StandardMaterial._DiffuseTextureEnabled;
  42817. },
  42818. set: function (value) {
  42819. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42820. return;
  42821. }
  42822. StandardMaterial._DiffuseTextureEnabled = value;
  42823. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42829. get: function () {
  42830. return StandardMaterial._AmbientTextureEnabled;
  42831. },
  42832. set: function (value) {
  42833. if (StandardMaterial._AmbientTextureEnabled === value) {
  42834. return;
  42835. }
  42836. StandardMaterial._AmbientTextureEnabled = value;
  42837. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42838. },
  42839. enumerable: true,
  42840. configurable: true
  42841. });
  42842. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42843. get: function () {
  42844. return StandardMaterial._OpacityTextureEnabled;
  42845. },
  42846. set: function (value) {
  42847. if (StandardMaterial._OpacityTextureEnabled === value) {
  42848. return;
  42849. }
  42850. StandardMaterial._OpacityTextureEnabled = value;
  42851. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42852. },
  42853. enumerable: true,
  42854. configurable: true
  42855. });
  42856. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42857. get: function () {
  42858. return StandardMaterial._ReflectionTextureEnabled;
  42859. },
  42860. set: function (value) {
  42861. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42862. return;
  42863. }
  42864. StandardMaterial._ReflectionTextureEnabled = value;
  42865. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42866. },
  42867. enumerable: true,
  42868. configurable: true
  42869. });
  42870. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42871. get: function () {
  42872. return StandardMaterial._EmissiveTextureEnabled;
  42873. },
  42874. set: function (value) {
  42875. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42876. return;
  42877. }
  42878. StandardMaterial._EmissiveTextureEnabled = value;
  42879. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42880. },
  42881. enumerable: true,
  42882. configurable: true
  42883. });
  42884. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42885. get: function () {
  42886. return StandardMaterial._SpecularTextureEnabled;
  42887. },
  42888. set: function (value) {
  42889. if (StandardMaterial._SpecularTextureEnabled === value) {
  42890. return;
  42891. }
  42892. StandardMaterial._SpecularTextureEnabled = value;
  42893. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42894. },
  42895. enumerable: true,
  42896. configurable: true
  42897. });
  42898. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42899. get: function () {
  42900. return StandardMaterial._BumpTextureEnabled;
  42901. },
  42902. set: function (value) {
  42903. if (StandardMaterial._BumpTextureEnabled === value) {
  42904. return;
  42905. }
  42906. StandardMaterial._BumpTextureEnabled = value;
  42907. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42908. },
  42909. enumerable: true,
  42910. configurable: true
  42911. });
  42912. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42913. get: function () {
  42914. return StandardMaterial._LightmapTextureEnabled;
  42915. },
  42916. set: function (value) {
  42917. if (StandardMaterial._LightmapTextureEnabled === value) {
  42918. return;
  42919. }
  42920. StandardMaterial._LightmapTextureEnabled = value;
  42921. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42922. },
  42923. enumerable: true,
  42924. configurable: true
  42925. });
  42926. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42927. get: function () {
  42928. return StandardMaterial._RefractionTextureEnabled;
  42929. },
  42930. set: function (value) {
  42931. if (StandardMaterial._RefractionTextureEnabled === value) {
  42932. return;
  42933. }
  42934. StandardMaterial._RefractionTextureEnabled = value;
  42935. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42936. },
  42937. enumerable: true,
  42938. configurable: true
  42939. });
  42940. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42941. get: function () {
  42942. return StandardMaterial._ColorGradingTextureEnabled;
  42943. },
  42944. set: function (value) {
  42945. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42946. return;
  42947. }
  42948. StandardMaterial._ColorGradingTextureEnabled = value;
  42949. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42950. },
  42951. enumerable: true,
  42952. configurable: true
  42953. });
  42954. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42955. get: function () {
  42956. return StandardMaterial._FresnelEnabled;
  42957. },
  42958. set: function (value) {
  42959. if (StandardMaterial._FresnelEnabled === value) {
  42960. return;
  42961. }
  42962. StandardMaterial._FresnelEnabled = value;
  42963. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42964. },
  42965. enumerable: true,
  42966. configurable: true
  42967. });
  42968. // Flags used to enable or disable a type of texture for all Standard Materials
  42969. StandardMaterial._DiffuseTextureEnabled = true;
  42970. StandardMaterial._AmbientTextureEnabled = true;
  42971. StandardMaterial._OpacityTextureEnabled = true;
  42972. StandardMaterial._ReflectionTextureEnabled = true;
  42973. StandardMaterial._EmissiveTextureEnabled = true;
  42974. StandardMaterial._SpecularTextureEnabled = true;
  42975. StandardMaterial._BumpTextureEnabled = true;
  42976. StandardMaterial._LightmapTextureEnabled = true;
  42977. StandardMaterial._RefractionTextureEnabled = true;
  42978. StandardMaterial._ColorGradingTextureEnabled = true;
  42979. StandardMaterial._FresnelEnabled = true;
  42980. __decorate([
  42981. BABYLON.serializeAsTexture("diffuseTexture")
  42982. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42983. __decorate([
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42985. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42986. __decorate([
  42987. BABYLON.serializeAsTexture("ambientTexture")
  42988. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42989. __decorate([
  42990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42991. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42992. __decorate([
  42993. BABYLON.serializeAsTexture("opacityTexture")
  42994. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42995. __decorate([
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42997. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42998. __decorate([
  42999. BABYLON.serializeAsTexture("reflectionTexture")
  43000. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43001. __decorate([
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43003. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsTexture("emissiveTexture")
  43006. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43007. __decorate([
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43010. __decorate([
  43011. BABYLON.serializeAsTexture("specularTexture")
  43012. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43013. __decorate([
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], StandardMaterial.prototype, "specularTexture", void 0);
  43016. __decorate([
  43017. BABYLON.serializeAsTexture("bumpTexture")
  43018. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43019. __decorate([
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43022. __decorate([
  43023. BABYLON.serializeAsTexture("lightmapTexture")
  43024. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43025. __decorate([
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43028. __decorate([
  43029. BABYLON.serializeAsTexture("refractionTexture")
  43030. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43031. __decorate([
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43034. __decorate([
  43035. BABYLON.serializeAsColor3("ambient")
  43036. ], StandardMaterial.prototype, "ambientColor", void 0);
  43037. __decorate([
  43038. BABYLON.serializeAsColor3("diffuse")
  43039. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43040. __decorate([
  43041. BABYLON.serializeAsColor3("specular")
  43042. ], StandardMaterial.prototype, "specularColor", void 0);
  43043. __decorate([
  43044. BABYLON.serializeAsColor3("emissive")
  43045. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43046. __decorate([
  43047. BABYLON.serialize()
  43048. ], StandardMaterial.prototype, "specularPower", void 0);
  43049. __decorate([
  43050. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43051. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43052. __decorate([
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43054. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43055. __decorate([
  43056. BABYLON.serialize("useEmissiveAsIllumination")
  43057. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43058. __decorate([
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43060. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43061. __decorate([
  43062. BABYLON.serialize("linkEmissiveWithDiffuse")
  43063. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43064. __decorate([
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43067. __decorate([
  43068. BABYLON.serialize("useSpecularOverAlpha")
  43069. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43070. __decorate([
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43072. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43073. __decorate([
  43074. BABYLON.serialize("useReflectionOverAlpha")
  43075. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43076. __decorate([
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43079. __decorate([
  43080. BABYLON.serialize("disableLighting")
  43081. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43082. __decorate([
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43084. ], StandardMaterial.prototype, "disableLighting", void 0);
  43085. __decorate([
  43086. BABYLON.serialize("useObjectSpaceNormalMap")
  43087. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43088. __decorate([
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43091. __decorate([
  43092. BABYLON.serialize("useParallax")
  43093. ], StandardMaterial.prototype, "_useParallax", void 0);
  43094. __decorate([
  43095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43096. ], StandardMaterial.prototype, "useParallax", void 0);
  43097. __decorate([
  43098. BABYLON.serialize("useParallaxOcclusion")
  43099. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43100. __decorate([
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43103. __decorate([
  43104. BABYLON.serialize()
  43105. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43106. __decorate([
  43107. BABYLON.serialize("roughness")
  43108. ], StandardMaterial.prototype, "_roughness", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], StandardMaterial.prototype, "roughness", void 0);
  43112. __decorate([
  43113. BABYLON.serialize()
  43114. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43115. __decorate([
  43116. BABYLON.serialize()
  43117. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43118. __decorate([
  43119. BABYLON.serialize()
  43120. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43121. __decorate([
  43122. BABYLON.serialize("useLightmapAsShadowmap")
  43123. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43124. __decorate([
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43127. __decorate([
  43128. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43129. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43130. __decorate([
  43131. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43132. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43133. __decorate([
  43134. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43135. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43136. __decorate([
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43138. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43139. __decorate([
  43140. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43141. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43142. __decorate([
  43143. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43144. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43145. __decorate([
  43146. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43147. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43148. __decorate([
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43150. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43151. __decorate([
  43152. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43153. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43154. __decorate([
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43156. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43157. __decorate([
  43158. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43159. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43160. __decorate([
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43162. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43163. __decorate([
  43164. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43165. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43166. __decorate([
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43169. __decorate([
  43170. BABYLON.serialize("maxSimultaneousLights")
  43171. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43172. __decorate([
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43174. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43175. __decorate([
  43176. BABYLON.serialize("invertNormalMapX")
  43177. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43178. __decorate([
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43181. __decorate([
  43182. BABYLON.serialize("invertNormalMapY")
  43183. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43184. __decorate([
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43187. __decorate([
  43188. BABYLON.serialize("twoSidedLighting")
  43189. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43190. __decorate([
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43192. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43193. __decorate([
  43194. BABYLON.serialize()
  43195. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43196. return StandardMaterial;
  43197. }(BABYLON.PushMaterial));
  43198. BABYLON.StandardMaterial = StandardMaterial;
  43199. })(BABYLON || (BABYLON = {}));
  43200. //# sourceMappingURL=babylon.standardMaterial.js.map
  43201. var BABYLON;
  43202. (function (BABYLON) {
  43203. /**
  43204. * Manages the defines for the PBR Material.
  43205. * @hiddenChildren
  43206. */
  43207. var PBRMaterialDefines = /** @class */ (function (_super) {
  43208. __extends(PBRMaterialDefines, _super);
  43209. /**
  43210. * Initializes the PBR Material defines.
  43211. */
  43212. function PBRMaterialDefines() {
  43213. var _this = _super.call(this) || this;
  43214. _this.PBR = true;
  43215. _this.MAINUV1 = false;
  43216. _this.MAINUV2 = false;
  43217. _this.UV1 = false;
  43218. _this.UV2 = false;
  43219. _this.ALBEDO = false;
  43220. _this.ALBEDODIRECTUV = 0;
  43221. _this.VERTEXCOLOR = false;
  43222. _this.AMBIENT = false;
  43223. _this.AMBIENTDIRECTUV = 0;
  43224. _this.AMBIENTINGRAYSCALE = false;
  43225. _this.OPACITY = false;
  43226. _this.VERTEXALPHA = false;
  43227. _this.OPACITYDIRECTUV = 0;
  43228. _this.OPACITYRGB = false;
  43229. _this.ALPHATEST = false;
  43230. _this.DEPTHPREPASS = false;
  43231. _this.ALPHABLEND = false;
  43232. _this.ALPHAFROMALBEDO = false;
  43233. _this.ALPHATESTVALUE = "0.5";
  43234. _this.SPECULAROVERALPHA = false;
  43235. _this.RADIANCEOVERALPHA = false;
  43236. _this.ALPHAFRESNEL = false;
  43237. _this.LINEARALPHAFRESNEL = false;
  43238. _this.PREMULTIPLYALPHA = false;
  43239. _this.EMISSIVE = false;
  43240. _this.EMISSIVEDIRECTUV = 0;
  43241. _this.REFLECTIVITY = false;
  43242. _this.REFLECTIVITYDIRECTUV = 0;
  43243. _this.SPECULARTERM = false;
  43244. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43245. _this.MICROSURFACEAUTOMATIC = false;
  43246. _this.LODBASEDMICROSFURACE = false;
  43247. _this.MICROSURFACEMAP = false;
  43248. _this.MICROSURFACEMAPDIRECTUV = 0;
  43249. _this.METALLICWORKFLOW = false;
  43250. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43251. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43252. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43253. _this.AOSTOREINMETALMAPRED = false;
  43254. _this.ENVIRONMENTBRDF = false;
  43255. _this.NORMAL = false;
  43256. _this.TANGENT = false;
  43257. _this.BUMP = false;
  43258. _this.BUMPDIRECTUV = 0;
  43259. _this.OBJECTSPACE_NORMALMAP = false;
  43260. _this.PARALLAX = false;
  43261. _this.PARALLAXOCCLUSION = false;
  43262. _this.NORMALXYSCALE = true;
  43263. _this.LIGHTMAP = false;
  43264. _this.LIGHTMAPDIRECTUV = 0;
  43265. _this.USELIGHTMAPASSHADOWMAP = false;
  43266. _this.GAMMALIGHTMAP = false;
  43267. _this.REFLECTION = false;
  43268. _this.REFLECTIONMAP_3D = false;
  43269. _this.REFLECTIONMAP_SPHERICAL = false;
  43270. _this.REFLECTIONMAP_PLANAR = false;
  43271. _this.REFLECTIONMAP_CUBIC = false;
  43272. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43273. _this.REFLECTIONMAP_PROJECTION = false;
  43274. _this.REFLECTIONMAP_SKYBOX = false;
  43275. _this.REFLECTIONMAP_EXPLICIT = false;
  43276. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43277. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43278. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43279. _this.INVERTCUBICMAP = false;
  43280. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43281. _this.USESPHERICALINVERTEX = false;
  43282. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43283. _this.LODINREFLECTIONALPHA = false;
  43284. _this.GAMMAREFLECTION = false;
  43285. _this.RGBDREFLECTION = false;
  43286. _this.RADIANCEOCCLUSION = false;
  43287. _this.HORIZONOCCLUSION = false;
  43288. _this.REFRACTION = false;
  43289. _this.REFRACTIONMAP_3D = false;
  43290. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43291. _this.LODINREFRACTIONALPHA = false;
  43292. _this.GAMMAREFRACTION = false;
  43293. _this.RGBDREFRACTION = false;
  43294. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43295. _this.INSTANCES = false;
  43296. _this.NUM_BONE_INFLUENCERS = 0;
  43297. _this.BonesPerMesh = 0;
  43298. _this.NONUNIFORMSCALING = false;
  43299. _this.MORPHTARGETS = false;
  43300. _this.MORPHTARGETS_NORMAL = false;
  43301. _this.MORPHTARGETS_TANGENT = false;
  43302. _this.NUM_MORPH_INFLUENCERS = 0;
  43303. _this.IMAGEPROCESSING = false;
  43304. _this.VIGNETTE = false;
  43305. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43306. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43307. _this.TONEMAPPING = false;
  43308. _this.CONTRAST = false;
  43309. _this.COLORCURVES = false;
  43310. _this.COLORGRADING = false;
  43311. _this.COLORGRADING3D = false;
  43312. _this.SAMPLER3DGREENDEPTH = false;
  43313. _this.SAMPLER3DBGRMAP = false;
  43314. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43315. _this.EXPOSURE = false;
  43316. _this.USEPHYSICALLIGHTFALLOFF = false;
  43317. _this.TWOSIDEDLIGHTING = false;
  43318. _this.SHADOWFLOAT = false;
  43319. _this.CLIPPLANE = false;
  43320. _this.POINTSIZE = false;
  43321. _this.FOG = false;
  43322. _this.LOGARITHMICDEPTH = false;
  43323. _this.FORCENORMALFORWARD = false;
  43324. _this.SPECULARAA = false;
  43325. _this.UNLIT = false;
  43326. _this.rebuild();
  43327. return _this;
  43328. }
  43329. /**
  43330. * Resets the PBR Material defines.
  43331. */
  43332. PBRMaterialDefines.prototype.reset = function () {
  43333. _super.prototype.reset.call(this);
  43334. this.ALPHATESTVALUE = "0.5";
  43335. this.PBR = true;
  43336. };
  43337. return PBRMaterialDefines;
  43338. }(BABYLON.MaterialDefines));
  43339. /**
  43340. * The Physically based material base class of BJS.
  43341. *
  43342. * This offers the main features of a standard PBR material.
  43343. * For more information, please refer to the documentation :
  43344. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43345. */
  43346. var PBRBaseMaterial = /** @class */ (function (_super) {
  43347. __extends(PBRBaseMaterial, _super);
  43348. /**
  43349. * Instantiates a new PBRMaterial instance.
  43350. *
  43351. * @param name The material name
  43352. * @param scene The scene the material will be use in.
  43353. */
  43354. function PBRBaseMaterial(name, scene) {
  43355. var _this = _super.call(this, name, scene) || this;
  43356. /**
  43357. * Intensity of the direct lights e.g. the four lights available in your scene.
  43358. * This impacts both the direct diffuse and specular highlights.
  43359. */
  43360. _this._directIntensity = 1.0;
  43361. /**
  43362. * Intensity of the emissive part of the material.
  43363. * This helps controlling the emissive effect without modifying the emissive color.
  43364. */
  43365. _this._emissiveIntensity = 1.0;
  43366. /**
  43367. * Intensity of the environment e.g. how much the environment will light the object
  43368. * either through harmonics for rough material or through the refelction for shiny ones.
  43369. */
  43370. _this._environmentIntensity = 1.0;
  43371. /**
  43372. * This is a special control allowing the reduction of the specular highlights coming from the
  43373. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43374. */
  43375. _this._specularIntensity = 1.0;
  43376. /**
  43377. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43378. */
  43379. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43380. /**
  43381. * Debug Control allowing disabling the bump map on this material.
  43382. */
  43383. _this._disableBumpMap = false;
  43384. /**
  43385. * AKA Occlusion Texture Intensity in other nomenclature.
  43386. */
  43387. _this._ambientTextureStrength = 1.0;
  43388. /**
  43389. * The color of a material in ambient lighting.
  43390. */
  43391. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43392. /**
  43393. * AKA Diffuse Color in other nomenclature.
  43394. */
  43395. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43396. /**
  43397. * AKA Specular Color in other nomenclature.
  43398. */
  43399. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43400. /**
  43401. * The color applied when light is reflected from a material.
  43402. */
  43403. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43404. /**
  43405. * The color applied when light is emitted from a material.
  43406. */
  43407. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43408. /**
  43409. * AKA Glossiness in other nomenclature.
  43410. */
  43411. _this._microSurface = 0.9;
  43412. /**
  43413. * source material index of refraction (IOR)' / 'destination material IOR.
  43414. */
  43415. _this._indexOfRefraction = 0.66;
  43416. /**
  43417. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43418. */
  43419. _this._invertRefractionY = false;
  43420. /**
  43421. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43422. * Materials half opaque for instance using refraction could benefit from this control.
  43423. */
  43424. _this._linkRefractionWithTransparency = false;
  43425. /**
  43426. * Specifies that the material will use the light map as a show map.
  43427. */
  43428. _this._useLightmapAsShadowmap = false;
  43429. /**
  43430. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43431. * makes the reflect vector face the model (under horizon).
  43432. */
  43433. _this._useHorizonOcclusion = true;
  43434. /**
  43435. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43436. * too much the area relying on ambient texture to define their ambient occlusion.
  43437. */
  43438. _this._useRadianceOcclusion = true;
  43439. /**
  43440. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43441. */
  43442. _this._useAlphaFromAlbedoTexture = false;
  43443. /**
  43444. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43445. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43446. */
  43447. _this._useSpecularOverAlpha = true;
  43448. /**
  43449. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43450. */
  43451. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43452. /**
  43453. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43454. */
  43455. _this._useRoughnessFromMetallicTextureAlpha = true;
  43456. /**
  43457. * Specifies if the metallic texture contains the roughness information in its green channel.
  43458. */
  43459. _this._useRoughnessFromMetallicTextureGreen = false;
  43460. /**
  43461. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43462. */
  43463. _this._useMetallnessFromMetallicTextureBlue = false;
  43464. /**
  43465. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43466. */
  43467. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43468. /**
  43469. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43470. */
  43471. _this._useAmbientInGrayScale = false;
  43472. /**
  43473. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43474. * The material will try to infer what glossiness each pixel should be.
  43475. */
  43476. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43477. /**
  43478. * BJS is using an harcoded light falloff based on a manually sets up range.
  43479. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43480. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43481. */
  43482. _this._usePhysicalLightFalloff = true;
  43483. /**
  43484. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43485. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43486. */
  43487. _this._useRadianceOverAlpha = true;
  43488. /**
  43489. * Allows using an object space normal map (instead of tangent space).
  43490. */
  43491. _this._useObjectSpaceNormalMap = false;
  43492. /**
  43493. * Allows using the bump map in parallax mode.
  43494. */
  43495. _this._useParallax = false;
  43496. /**
  43497. * Allows using the bump map in parallax occlusion mode.
  43498. */
  43499. _this._useParallaxOcclusion = false;
  43500. /**
  43501. * Controls the scale bias of the parallax mode.
  43502. */
  43503. _this._parallaxScaleBias = 0.05;
  43504. /**
  43505. * If sets to true, disables all the lights affecting the material.
  43506. */
  43507. _this._disableLighting = false;
  43508. /**
  43509. * Number of Simultaneous lights allowed on the material.
  43510. */
  43511. _this._maxSimultaneousLights = 4;
  43512. /**
  43513. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43514. */
  43515. _this._invertNormalMapX = false;
  43516. /**
  43517. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43518. */
  43519. _this._invertNormalMapY = false;
  43520. /**
  43521. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43522. */
  43523. _this._twoSidedLighting = false;
  43524. /**
  43525. * Defines the alpha limits in alpha test mode.
  43526. */
  43527. _this._alphaCutOff = 0.4;
  43528. /**
  43529. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43530. */
  43531. _this._forceAlphaTest = false;
  43532. /**
  43533. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43534. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43535. */
  43536. _this._useAlphaFresnel = false;
  43537. /**
  43538. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43539. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43540. */
  43541. _this._useLinearAlphaFresnel = false;
  43542. /**
  43543. * The transparency mode of the material.
  43544. */
  43545. _this._transparencyMode = null;
  43546. /**
  43547. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43548. * from cos thetav and roughness:
  43549. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43550. */
  43551. _this._environmentBRDFTexture = null;
  43552. /**
  43553. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43554. */
  43555. _this._forceIrradianceInFragment = false;
  43556. /**
  43557. * Force normal to face away from face.
  43558. */
  43559. _this._forceNormalForward = false;
  43560. /**
  43561. * Enables specular anti aliasing in the PBR shader.
  43562. * It will both interacts on the Geometry for analytical and IBL lighting.
  43563. * It also prefilter the roughness map based on the bump values.
  43564. */
  43565. _this._enableSpecularAntiAliasing = false;
  43566. /**
  43567. * Stores the available render targets.
  43568. */
  43569. _this._renderTargets = new BABYLON.SmartArray(16);
  43570. /**
  43571. * Sets the global ambient color for the material used in lighting calculations.
  43572. */
  43573. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43574. /**
  43575. * If set to true, no lighting calculations will be applied.
  43576. */
  43577. _this._unlit = false;
  43578. // Setup the default processing configuration to the scene.
  43579. _this._attachImageProcessingConfiguration(null);
  43580. _this.getRenderTargetTextures = function () {
  43581. _this._renderTargets.reset();
  43582. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43583. _this._renderTargets.push(_this._reflectionTexture);
  43584. }
  43585. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43586. _this._renderTargets.push(_this._refractionTexture);
  43587. }
  43588. return _this._renderTargets;
  43589. };
  43590. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43591. return _this;
  43592. }
  43593. /**
  43594. * Attaches a new image processing configuration to the PBR Material.
  43595. * @param configuration
  43596. */
  43597. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43598. var _this = this;
  43599. if (configuration === this._imageProcessingConfiguration) {
  43600. return;
  43601. }
  43602. // Detaches observer.
  43603. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43604. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43605. }
  43606. // Pick the scene configuration if needed.
  43607. if (!configuration) {
  43608. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43609. }
  43610. else {
  43611. this._imageProcessingConfiguration = configuration;
  43612. }
  43613. // Attaches observer.
  43614. if (this._imageProcessingConfiguration) {
  43615. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43616. _this._markAllSubMeshesAsImageProcessingDirty();
  43617. });
  43618. }
  43619. };
  43620. /**
  43621. * Gets the name of the material class.
  43622. */
  43623. PBRBaseMaterial.prototype.getClassName = function () {
  43624. return "PBRBaseMaterial";
  43625. };
  43626. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43627. /**
  43628. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43629. */
  43630. get: function () {
  43631. return this._useLogarithmicDepth;
  43632. },
  43633. /**
  43634. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43635. */
  43636. set: function (value) {
  43637. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43638. },
  43639. enumerable: true,
  43640. configurable: true
  43641. });
  43642. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43643. /**
  43644. * Gets the current transparency mode.
  43645. */
  43646. get: function () {
  43647. return this._transparencyMode;
  43648. },
  43649. /**
  43650. * Sets the transparency mode of the material.
  43651. *
  43652. * | Value | Type | Description |
  43653. * | ----- | ----------------------------------- | ----------- |
  43654. * | 0 | OPAQUE | |
  43655. * | 1 | ALPHATEST | |
  43656. * | 2 | ALPHABLEND | |
  43657. * | 3 | ALPHATESTANDBLEND | |
  43658. *
  43659. */
  43660. set: function (value) {
  43661. if (this._transparencyMode === value) {
  43662. return;
  43663. }
  43664. this._transparencyMode = value;
  43665. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43666. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43667. },
  43668. enumerable: true,
  43669. configurable: true
  43670. });
  43671. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43672. /**
  43673. * Returns true if alpha blending should be disabled.
  43674. */
  43675. get: function () {
  43676. return (this._linkRefractionWithTransparency ||
  43677. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43678. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43679. },
  43680. enumerable: true,
  43681. configurable: true
  43682. });
  43683. /**
  43684. * Specifies whether or not this material should be rendered in alpha blend mode.
  43685. */
  43686. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43687. if (this._disableAlphaBlending) {
  43688. return false;
  43689. }
  43690. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43691. };
  43692. /**
  43693. * Specifies if the mesh will require alpha blending.
  43694. * @param mesh - BJS mesh.
  43695. */
  43696. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43697. if (this._disableAlphaBlending) {
  43698. return false;
  43699. }
  43700. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43701. };
  43702. /**
  43703. * Specifies whether or not this material should be rendered in alpha test mode.
  43704. */
  43705. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43706. if (this._forceAlphaTest) {
  43707. return true;
  43708. }
  43709. if (this._linkRefractionWithTransparency) {
  43710. return false;
  43711. }
  43712. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43713. };
  43714. /**
  43715. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43716. */
  43717. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43718. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43719. };
  43720. /**
  43721. * Gets the texture used for the alpha test.
  43722. */
  43723. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43724. return this._albedoTexture;
  43725. };
  43726. /**
  43727. * Specifies that the submesh is ready to be used.
  43728. * @param mesh - BJS mesh.
  43729. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43730. * @param useInstances - Specifies that instances should be used.
  43731. * @returns - boolean indicating that the submesh is ready or not.
  43732. */
  43733. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43734. if (subMesh.effect && this.isFrozen) {
  43735. if (this._wasPreviouslyReady) {
  43736. return true;
  43737. }
  43738. }
  43739. if (!subMesh._materialDefines) {
  43740. subMesh._materialDefines = new PBRMaterialDefines();
  43741. }
  43742. var defines = subMesh._materialDefines;
  43743. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43744. if (defines._renderId === this.getScene().getRenderId()) {
  43745. return true;
  43746. }
  43747. }
  43748. var scene = this.getScene();
  43749. var engine = scene.getEngine();
  43750. if (defines._areTexturesDirty) {
  43751. if (scene.texturesEnabled) {
  43752. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43753. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43754. return false;
  43755. }
  43756. }
  43757. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43758. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43759. return false;
  43760. }
  43761. }
  43762. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43763. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43764. return false;
  43765. }
  43766. }
  43767. var reflectionTexture = this._getReflectionTexture();
  43768. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43769. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43770. return false;
  43771. }
  43772. }
  43773. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43774. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43775. return false;
  43776. }
  43777. }
  43778. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43779. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43780. return false;
  43781. }
  43782. }
  43783. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43784. if (this._metallicTexture) {
  43785. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43786. return false;
  43787. }
  43788. }
  43789. else if (this._reflectivityTexture) {
  43790. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43791. return false;
  43792. }
  43793. }
  43794. if (this._microSurfaceTexture) {
  43795. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43796. return false;
  43797. }
  43798. }
  43799. }
  43800. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43801. // Bump texture cannot be not blocking.
  43802. if (!this._bumpTexture.isReady()) {
  43803. return false;
  43804. }
  43805. }
  43806. var refractionTexture = this._getRefractionTexture();
  43807. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43808. if (!refractionTexture.isReadyOrNotBlocking()) {
  43809. return false;
  43810. }
  43811. }
  43812. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43813. // This is blocking.
  43814. if (!this._environmentBRDFTexture.isReady()) {
  43815. return false;
  43816. }
  43817. }
  43818. }
  43819. }
  43820. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43821. if (!this._imageProcessingConfiguration.isReady()) {
  43822. return false;
  43823. }
  43824. }
  43825. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43826. mesh.createNormals(true);
  43827. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43828. }
  43829. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43830. if (effect) {
  43831. scene.resetCachedMaterial();
  43832. subMesh.setEffect(effect, defines);
  43833. this.buildUniformLayout();
  43834. }
  43835. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43836. return false;
  43837. }
  43838. defines._renderId = scene.getRenderId();
  43839. this._wasPreviouslyReady = true;
  43840. return true;
  43841. };
  43842. /**
  43843. * Specifies if the material uses metallic roughness workflow.
  43844. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43845. */
  43846. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43847. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43848. return true;
  43849. }
  43850. return false;
  43851. };
  43852. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43853. if (onCompiled === void 0) { onCompiled = null; }
  43854. if (onError === void 0) { onError = null; }
  43855. if (useInstances === void 0) { useInstances = null; }
  43856. if (useClipPlane === void 0) { useClipPlane = null; }
  43857. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43858. if (!defines.isDirty) {
  43859. return null;
  43860. }
  43861. defines.markAsProcessed();
  43862. var scene = this.getScene();
  43863. var engine = scene.getEngine();
  43864. // Fallbacks
  43865. var fallbacks = new BABYLON.EffectFallbacks();
  43866. var fallbackRank = 0;
  43867. if (defines.USESPHERICALINVERTEX) {
  43868. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43869. }
  43870. if (defines.FOG) {
  43871. fallbacks.addFallback(fallbackRank, "FOG");
  43872. }
  43873. if (defines.SPECULARAA) {
  43874. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43875. }
  43876. if (defines.POINTSIZE) {
  43877. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43878. }
  43879. if (defines.LOGARITHMICDEPTH) {
  43880. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43881. }
  43882. if (defines.PARALLAX) {
  43883. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43884. }
  43885. if (defines.PARALLAXOCCLUSION) {
  43886. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43887. }
  43888. if (defines.ENVIRONMENTBRDF) {
  43889. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43890. }
  43891. if (defines.TANGENT) {
  43892. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43893. }
  43894. if (defines.BUMP) {
  43895. fallbacks.addFallback(fallbackRank++, "BUMP");
  43896. }
  43897. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43898. if (defines.SPECULARTERM) {
  43899. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43900. }
  43901. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43902. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43903. }
  43904. if (defines.LIGHTMAP) {
  43905. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43906. }
  43907. if (defines.NORMAL) {
  43908. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43909. }
  43910. if (defines.AMBIENT) {
  43911. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43912. }
  43913. if (defines.EMISSIVE) {
  43914. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43915. }
  43916. if (defines.VERTEXCOLOR) {
  43917. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43918. }
  43919. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43920. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43921. }
  43922. if (defines.MORPHTARGETS) {
  43923. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43924. }
  43925. //Attributes
  43926. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43927. if (defines.NORMAL) {
  43928. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43929. }
  43930. if (defines.TANGENT) {
  43931. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43932. }
  43933. if (defines.UV1) {
  43934. attribs.push(BABYLON.VertexBuffer.UVKind);
  43935. }
  43936. if (defines.UV2) {
  43937. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43938. }
  43939. if (defines.VERTEXCOLOR) {
  43940. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43941. }
  43942. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43943. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43944. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43945. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43946. "vFogInfos", "vFogColor", "pointSize",
  43947. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43948. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43949. "mBones",
  43950. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43951. "vLightingIntensity",
  43952. "logarithmicDepthConstant",
  43953. "vSphericalX", "vSphericalY", "vSphericalZ",
  43954. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43955. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43956. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43957. "vTangentSpaceParams"
  43958. ];
  43959. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43960. "bumpSampler", "lightmapSampler", "opacitySampler",
  43961. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43962. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43963. "microSurfaceSampler", "environmentBrdfSampler"];
  43964. var uniformBuffers = ["Material", "Scene"];
  43965. if (BABYLON.ImageProcessingConfiguration) {
  43966. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43967. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43968. }
  43969. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43970. uniformsNames: uniforms,
  43971. uniformBuffersNames: uniformBuffers,
  43972. samplers: samplers,
  43973. defines: defines,
  43974. maxSimultaneousLights: this._maxSimultaneousLights
  43975. });
  43976. var join = defines.toString();
  43977. return engine.createEffect("pbr", {
  43978. attributes: attribs,
  43979. uniformsNames: uniforms,
  43980. uniformBuffersNames: uniformBuffers,
  43981. samplers: samplers,
  43982. defines: join,
  43983. fallbacks: fallbacks,
  43984. onCompiled: onCompiled,
  43985. onError: onError,
  43986. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43987. }, engine);
  43988. };
  43989. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43990. if (useInstances === void 0) { useInstances = null; }
  43991. if (useClipPlane === void 0) { useClipPlane = null; }
  43992. var scene = this.getScene();
  43993. var engine = scene.getEngine();
  43994. // Lights
  43995. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43996. defines._needNormals = true;
  43997. // Textures
  43998. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43999. if (defines._areTexturesDirty) {
  44000. defines._needUVs = false;
  44001. if (scene.texturesEnabled) {
  44002. if (scene.getEngine().getCaps().textureLOD) {
  44003. defines.LODBASEDMICROSFURACE = true;
  44004. }
  44005. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44007. }
  44008. else {
  44009. defines.ALBEDO = false;
  44010. }
  44011. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44012. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44013. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44014. }
  44015. else {
  44016. defines.AMBIENT = false;
  44017. }
  44018. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44019. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44020. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44021. }
  44022. else {
  44023. defines.OPACITY = false;
  44024. }
  44025. var reflectionTexture = this._getReflectionTexture();
  44026. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44027. defines.REFLECTION = true;
  44028. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44029. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44030. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44031. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44032. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44033. defines.INVERTCUBICMAP = true;
  44034. }
  44035. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44036. switch (reflectionTexture.coordinatesMode) {
  44037. case BABYLON.Texture.EXPLICIT_MODE:
  44038. defines.REFLECTIONMAP_EXPLICIT = true;
  44039. break;
  44040. case BABYLON.Texture.PLANAR_MODE:
  44041. defines.REFLECTIONMAP_PLANAR = true;
  44042. break;
  44043. case BABYLON.Texture.PROJECTION_MODE:
  44044. defines.REFLECTIONMAP_PROJECTION = true;
  44045. break;
  44046. case BABYLON.Texture.SKYBOX_MODE:
  44047. defines.REFLECTIONMAP_SKYBOX = true;
  44048. break;
  44049. case BABYLON.Texture.SPHERICAL_MODE:
  44050. defines.REFLECTIONMAP_SPHERICAL = true;
  44051. break;
  44052. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44053. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44054. break;
  44055. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44056. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44057. break;
  44058. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44059. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44060. break;
  44061. case BABYLON.Texture.CUBIC_MODE:
  44062. case BABYLON.Texture.INVCUBIC_MODE:
  44063. default:
  44064. defines.REFLECTIONMAP_CUBIC = true;
  44065. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44066. break;
  44067. }
  44068. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44069. if (reflectionTexture.sphericalPolynomial) {
  44070. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44071. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44072. defines.USESPHERICALINVERTEX = false;
  44073. }
  44074. else {
  44075. defines.USESPHERICALINVERTEX = true;
  44076. }
  44077. }
  44078. }
  44079. }
  44080. else {
  44081. defines.REFLECTION = false;
  44082. defines.REFLECTIONMAP_3D = false;
  44083. defines.REFLECTIONMAP_SPHERICAL = false;
  44084. defines.REFLECTIONMAP_PLANAR = false;
  44085. defines.REFLECTIONMAP_CUBIC = false;
  44086. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44087. defines.REFLECTIONMAP_PROJECTION = false;
  44088. defines.REFLECTIONMAP_SKYBOX = false;
  44089. defines.REFLECTIONMAP_EXPLICIT = false;
  44090. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44091. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44092. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44093. defines.INVERTCUBICMAP = false;
  44094. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44095. defines.USESPHERICALINVERTEX = false;
  44096. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44097. defines.LODINREFLECTIONALPHA = false;
  44098. defines.GAMMAREFLECTION = false;
  44099. defines.RGBDREFLECTION = false;
  44100. }
  44101. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44103. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44104. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44105. }
  44106. else {
  44107. defines.LIGHTMAP = false;
  44108. }
  44109. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44111. }
  44112. else {
  44113. defines.EMISSIVE = false;
  44114. }
  44115. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44116. if (this._metallicTexture) {
  44117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44118. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44119. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44120. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44121. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44122. }
  44123. else if (this._reflectivityTexture) {
  44124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44125. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44126. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44127. }
  44128. else {
  44129. defines.REFLECTIVITY = false;
  44130. }
  44131. if (this._microSurfaceTexture) {
  44132. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44133. }
  44134. else {
  44135. defines.MICROSURFACEMAP = false;
  44136. }
  44137. }
  44138. else {
  44139. defines.REFLECTIVITY = false;
  44140. defines.MICROSURFACEMAP = false;
  44141. }
  44142. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44143. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44144. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44145. defines.PARALLAX = true;
  44146. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44147. }
  44148. else {
  44149. defines.PARALLAX = false;
  44150. }
  44151. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44152. }
  44153. else {
  44154. defines.BUMP = false;
  44155. }
  44156. var refractionTexture = this._getRefractionTexture();
  44157. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44158. defines.REFRACTION = true;
  44159. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44160. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44161. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44162. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44163. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44164. if (this._linkRefractionWithTransparency) {
  44165. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44166. }
  44167. }
  44168. else {
  44169. defines.REFRACTION = false;
  44170. }
  44171. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44172. defines.ENVIRONMENTBRDF = true;
  44173. }
  44174. else {
  44175. defines.ENVIRONMENTBRDF = false;
  44176. }
  44177. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44178. defines.ALPHAFROMALBEDO = true;
  44179. }
  44180. else {
  44181. defines.ALPHAFROMALBEDO = false;
  44182. }
  44183. }
  44184. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44185. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44186. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44187. if (!this.backFaceCulling && this._twoSidedLighting) {
  44188. defines.TWOSIDEDLIGHTING = true;
  44189. }
  44190. else {
  44191. defines.TWOSIDEDLIGHTING = false;
  44192. }
  44193. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44194. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44195. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44196. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44197. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44198. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44199. }
  44200. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44201. this._imageProcessingConfiguration.prepareDefines(defines);
  44202. }
  44203. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44204. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44205. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44206. // Misc.
  44207. if (defines._areMiscDirty) {
  44208. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44209. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44210. }
  44211. // Values that need to be evaluated on every frame
  44212. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44213. // Attribs
  44214. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44215. };
  44216. /**
  44217. * Force shader compilation
  44218. */
  44219. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44220. var _this = this;
  44221. var localOptions = __assign({ clipPlane: false }, options);
  44222. var defines = new PBRMaterialDefines();
  44223. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44224. if (effect.isReady()) {
  44225. if (onCompiled) {
  44226. onCompiled(this);
  44227. }
  44228. }
  44229. else {
  44230. effect.onCompileObservable.add(function () {
  44231. if (onCompiled) {
  44232. onCompiled(_this);
  44233. }
  44234. });
  44235. }
  44236. };
  44237. /**
  44238. * Initializes the uniform buffer layout for the shader.
  44239. */
  44240. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44241. // Order is important !
  44242. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44243. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44244. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44245. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44246. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44247. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44248. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44249. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44250. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44251. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44252. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44253. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44254. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44255. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44256. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44257. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44258. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44259. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44260. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44261. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44262. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44263. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44264. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44265. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44266. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44267. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44268. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44269. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44270. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44271. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44272. this._uniformBuffer.addUniform("pointSize", 1);
  44273. this._uniformBuffer.create();
  44274. };
  44275. /**
  44276. * Unbinds the textures.
  44277. */
  44278. PBRBaseMaterial.prototype.unbind = function () {
  44279. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44280. this._uniformBuffer.setTexture("reflectionSampler", null);
  44281. }
  44282. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44283. this._uniformBuffer.setTexture("refractionSampler", null);
  44284. }
  44285. _super.prototype.unbind.call(this);
  44286. };
  44287. /**
  44288. * Binds the submesh data.
  44289. * @param world - The world matrix.
  44290. * @param mesh - The BJS mesh.
  44291. * @param subMesh - A submesh of the BJS mesh.
  44292. */
  44293. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44294. var scene = this.getScene();
  44295. var defines = subMesh._materialDefines;
  44296. if (!defines) {
  44297. return;
  44298. }
  44299. var effect = subMesh.effect;
  44300. if (!effect) {
  44301. return;
  44302. }
  44303. this._activeEffect = effect;
  44304. // Matrices
  44305. this.bindOnlyWorldMatrix(world);
  44306. // Normal Matrix
  44307. if (defines.OBJECTSPACE_NORMALMAP) {
  44308. world.toNormalMatrix(this._normalMatrix);
  44309. this.bindOnlyNormalMatrix(this._normalMatrix);
  44310. }
  44311. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44312. // Bones
  44313. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44314. var reflectionTexture = null;
  44315. if (mustRebind) {
  44316. this._uniformBuffer.bindToEffect(effect, "Material");
  44317. this.bindViewProjection(effect);
  44318. reflectionTexture = this._getReflectionTexture();
  44319. var refractionTexture = this._getRefractionTexture();
  44320. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44321. // Texture uniforms
  44322. if (scene.texturesEnabled) {
  44323. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44324. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44325. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44326. }
  44327. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44328. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44329. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44330. }
  44331. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44332. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44333. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44334. }
  44335. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44336. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44337. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44338. if (reflectionTexture.boundingBoxSize) {
  44339. var cubeTexture = reflectionTexture;
  44340. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44341. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44342. }
  44343. var polynomials = reflectionTexture.sphericalPolynomial;
  44344. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44345. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44346. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44347. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44348. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44349. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44350. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44351. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44352. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44353. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44354. }
  44355. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44356. }
  44357. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44358. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44359. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44360. }
  44361. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44362. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44363. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44364. }
  44365. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44366. if (this._metallicTexture) {
  44367. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44368. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44369. }
  44370. else if (this._reflectivityTexture) {
  44371. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44372. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44373. }
  44374. if (this._microSurfaceTexture) {
  44375. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44376. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44377. }
  44378. }
  44379. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44380. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44381. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44382. if (scene._mirroredCameraPosition) {
  44383. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44384. }
  44385. else {
  44386. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44387. }
  44388. }
  44389. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44390. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44391. var depth = 1.0;
  44392. if (!refractionTexture.isCube) {
  44393. if (refractionTexture.depth) {
  44394. depth = refractionTexture.depth;
  44395. }
  44396. }
  44397. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44398. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44399. }
  44400. }
  44401. // Point size
  44402. if (this.pointsCloud) {
  44403. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44404. }
  44405. // Colors
  44406. if (defines.METALLICWORKFLOW) {
  44407. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44408. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44409. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44410. }
  44411. else {
  44412. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44413. }
  44414. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44415. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44416. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44417. // Misc
  44418. this._lightingInfos.x = this._directIntensity;
  44419. this._lightingInfos.y = this._emissiveIntensity;
  44420. this._lightingInfos.z = this._environmentIntensity;
  44421. this._lightingInfos.w = this._specularIntensity;
  44422. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44423. }
  44424. // Textures
  44425. if (scene.texturesEnabled) {
  44426. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44427. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44428. }
  44429. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44430. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44431. }
  44432. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44433. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44434. }
  44435. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44436. if (defines.LODBASEDMICROSFURACE) {
  44437. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44438. }
  44439. else {
  44440. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44441. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44442. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44443. }
  44444. }
  44445. if (defines.ENVIRONMENTBRDF) {
  44446. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44447. }
  44448. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44449. if (defines.LODBASEDMICROSFURACE) {
  44450. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44451. }
  44452. else {
  44453. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44454. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44455. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44456. }
  44457. }
  44458. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44459. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44460. }
  44461. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44462. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44463. }
  44464. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44465. if (this._metallicTexture) {
  44466. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44467. }
  44468. else if (this._reflectivityTexture) {
  44469. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44470. }
  44471. if (this._microSurfaceTexture) {
  44472. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44473. }
  44474. }
  44475. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44476. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44477. }
  44478. }
  44479. // Clip plane
  44480. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44481. // Colors
  44482. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44483. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44484. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44485. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44486. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44487. }
  44488. if (mustRebind || !this.isFrozen) {
  44489. // Lights
  44490. if (scene.lightsEnabled && !this._disableLighting) {
  44491. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44492. }
  44493. // View
  44494. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44495. this.bindView(effect);
  44496. }
  44497. // Fog
  44498. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44499. // Morph targets
  44500. if (defines.NUM_MORPH_INFLUENCERS) {
  44501. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44502. }
  44503. // image processing
  44504. this._imageProcessingConfiguration.bind(this._activeEffect);
  44505. // Log. depth
  44506. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44507. }
  44508. this._uniformBuffer.update();
  44509. this._afterBind(mesh, this._activeEffect);
  44510. };
  44511. /**
  44512. * Returns the animatable textures.
  44513. * @returns - Array of animatable textures.
  44514. */
  44515. PBRBaseMaterial.prototype.getAnimatables = function () {
  44516. var results = [];
  44517. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44518. results.push(this._albedoTexture);
  44519. }
  44520. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44521. results.push(this._ambientTexture);
  44522. }
  44523. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44524. results.push(this._opacityTexture);
  44525. }
  44526. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44527. results.push(this._reflectionTexture);
  44528. }
  44529. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44530. results.push(this._emissiveTexture);
  44531. }
  44532. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44533. results.push(this._metallicTexture);
  44534. }
  44535. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44536. results.push(this._reflectivityTexture);
  44537. }
  44538. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44539. results.push(this._bumpTexture);
  44540. }
  44541. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44542. results.push(this._lightmapTexture);
  44543. }
  44544. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44545. results.push(this._refractionTexture);
  44546. }
  44547. return results;
  44548. };
  44549. /**
  44550. * Returns the texture used for reflections.
  44551. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44552. */
  44553. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44554. if (this._reflectionTexture) {
  44555. return this._reflectionTexture;
  44556. }
  44557. return this.getScene().environmentTexture;
  44558. };
  44559. /**
  44560. * Returns the texture used for refraction or null if none is used.
  44561. * @returns - Refection texture if present. If no refraction texture and refraction
  44562. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44563. */
  44564. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44565. if (this._refractionTexture) {
  44566. return this._refractionTexture;
  44567. }
  44568. if (this._linkRefractionWithTransparency) {
  44569. return this.getScene().environmentTexture;
  44570. }
  44571. return null;
  44572. };
  44573. /**
  44574. * Disposes the resources of the material.
  44575. * @param forceDisposeEffect - Forces the disposal of effects.
  44576. * @param forceDisposeTextures - Forces the disposal of all textures.
  44577. */
  44578. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44579. if (forceDisposeTextures) {
  44580. if (this._albedoTexture) {
  44581. this._albedoTexture.dispose();
  44582. }
  44583. if (this._ambientTexture) {
  44584. this._ambientTexture.dispose();
  44585. }
  44586. if (this._opacityTexture) {
  44587. this._opacityTexture.dispose();
  44588. }
  44589. if (this._reflectionTexture) {
  44590. this._reflectionTexture.dispose();
  44591. }
  44592. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44593. this._environmentBRDFTexture.dispose();
  44594. }
  44595. if (this._emissiveTexture) {
  44596. this._emissiveTexture.dispose();
  44597. }
  44598. if (this._metallicTexture) {
  44599. this._metallicTexture.dispose();
  44600. }
  44601. if (this._reflectivityTexture) {
  44602. this._reflectivityTexture.dispose();
  44603. }
  44604. if (this._bumpTexture) {
  44605. this._bumpTexture.dispose();
  44606. }
  44607. if (this._lightmapTexture) {
  44608. this._lightmapTexture.dispose();
  44609. }
  44610. if (this._refractionTexture) {
  44611. this._refractionTexture.dispose();
  44612. }
  44613. }
  44614. this._renderTargets.dispose();
  44615. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44616. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44617. }
  44618. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44619. };
  44620. /**
  44621. * Stores the reflectivity values based on metallic roughness workflow.
  44622. */
  44623. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44624. __decorate([
  44625. BABYLON.serializeAsImageProcessingConfiguration()
  44626. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44633. return PBRBaseMaterial;
  44634. }(BABYLON.PushMaterial));
  44635. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44636. })(BABYLON || (BABYLON = {}));
  44637. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44638. var BABYLON;
  44639. (function (BABYLON) {
  44640. /**
  44641. * The Physically based simple base material of BJS.
  44642. *
  44643. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44644. * It is used as the base class for both the specGloss and metalRough conventions.
  44645. */
  44646. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44647. __extends(PBRBaseSimpleMaterial, _super);
  44648. /**
  44649. * Instantiates a new PBRMaterial instance.
  44650. *
  44651. * @param name The material name
  44652. * @param scene The scene the material will be use in.
  44653. */
  44654. function PBRBaseSimpleMaterial(name, scene) {
  44655. var _this = _super.call(this, name, scene) || this;
  44656. /**
  44657. * Number of Simultaneous lights allowed on the material.
  44658. */
  44659. _this.maxSimultaneousLights = 4;
  44660. /**
  44661. * If sets to true, disables all the lights affecting the material.
  44662. */
  44663. _this.disableLighting = false;
  44664. /**
  44665. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44666. */
  44667. _this.invertNormalMapX = false;
  44668. /**
  44669. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44670. */
  44671. _this.invertNormalMapY = false;
  44672. /**
  44673. * Emissivie color used to self-illuminate the model.
  44674. */
  44675. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44676. /**
  44677. * Occlusion Channel Strenght.
  44678. */
  44679. _this.occlusionStrength = 1.0;
  44680. _this.useLightmapAsShadowmap = false;
  44681. _this._useAlphaFromAlbedoTexture = true;
  44682. _this._useAmbientInGrayScale = true;
  44683. return _this;
  44684. }
  44685. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44686. /**
  44687. * Gets the current double sided mode.
  44688. */
  44689. get: function () {
  44690. return this._twoSidedLighting;
  44691. },
  44692. /**
  44693. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44694. */
  44695. set: function (value) {
  44696. if (this._twoSidedLighting === value) {
  44697. return;
  44698. }
  44699. this._twoSidedLighting = value;
  44700. this.backFaceCulling = !value;
  44701. this._markAllSubMeshesAsTexturesDirty();
  44702. },
  44703. enumerable: true,
  44704. configurable: true
  44705. });
  44706. /**
  44707. * Return the active textures of the material.
  44708. */
  44709. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44710. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44711. if (this.environmentTexture) {
  44712. activeTextures.push(this.environmentTexture);
  44713. }
  44714. if (this.normalTexture) {
  44715. activeTextures.push(this.normalTexture);
  44716. }
  44717. if (this.emissiveTexture) {
  44718. activeTextures.push(this.emissiveTexture);
  44719. }
  44720. if (this.occlusionTexture) {
  44721. activeTextures.push(this.occlusionTexture);
  44722. }
  44723. if (this.lightmapTexture) {
  44724. activeTextures.push(this.lightmapTexture);
  44725. }
  44726. return activeTextures;
  44727. };
  44728. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44729. if (_super.prototype.hasTexture.call(this, texture)) {
  44730. return true;
  44731. }
  44732. if (this.lightmapTexture === texture) {
  44733. return true;
  44734. }
  44735. return false;
  44736. };
  44737. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44738. return "PBRBaseSimpleMaterial";
  44739. };
  44740. __decorate([
  44741. BABYLON.serialize(),
  44742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44743. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44744. __decorate([
  44745. BABYLON.serialize(),
  44746. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44747. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44748. __decorate([
  44749. BABYLON.serializeAsTexture(),
  44750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44751. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44752. __decorate([
  44753. BABYLON.serialize(),
  44754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44755. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44756. __decorate([
  44757. BABYLON.serialize(),
  44758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44759. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44760. __decorate([
  44761. BABYLON.serializeAsTexture(),
  44762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44763. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44764. __decorate([
  44765. BABYLON.serializeAsColor3("emissive"),
  44766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44767. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44768. __decorate([
  44769. BABYLON.serializeAsTexture(),
  44770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44771. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44772. __decorate([
  44773. BABYLON.serialize(),
  44774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44775. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44776. __decorate([
  44777. BABYLON.serializeAsTexture(),
  44778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44779. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44780. __decorate([
  44781. BABYLON.serialize(),
  44782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44783. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44784. __decorate([
  44785. BABYLON.serialize()
  44786. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44787. __decorate([
  44788. BABYLON.serializeAsTexture(),
  44789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44790. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44791. __decorate([
  44792. BABYLON.serialize(),
  44793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44794. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44795. return PBRBaseSimpleMaterial;
  44796. }(BABYLON.PBRBaseMaterial));
  44797. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44798. })(BABYLON || (BABYLON = {}));
  44799. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44800. var BABYLON;
  44801. (function (BABYLON) {
  44802. /**
  44803. * The Physically based material of BJS.
  44804. *
  44805. * This offers the main features of a standard PBR material.
  44806. * For more information, please refer to the documentation :
  44807. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44808. */
  44809. var PBRMaterial = /** @class */ (function (_super) {
  44810. __extends(PBRMaterial, _super);
  44811. /**
  44812. * Instantiates a new PBRMaterial instance.
  44813. *
  44814. * @param name The material name
  44815. * @param scene The scene the material will be use in.
  44816. */
  44817. function PBRMaterial(name, scene) {
  44818. var _this = _super.call(this, name, scene) || this;
  44819. /**
  44820. * Intensity of the direct lights e.g. the four lights available in your scene.
  44821. * This impacts both the direct diffuse and specular highlights.
  44822. */
  44823. _this.directIntensity = 1.0;
  44824. /**
  44825. * Intensity of the emissive part of the material.
  44826. * This helps controlling the emissive effect without modifying the emissive color.
  44827. */
  44828. _this.emissiveIntensity = 1.0;
  44829. /**
  44830. * Intensity of the environment e.g. how much the environment will light the object
  44831. * either through harmonics for rough material or through the refelction for shiny ones.
  44832. */
  44833. _this.environmentIntensity = 1.0;
  44834. /**
  44835. * This is a special control allowing the reduction of the specular highlights coming from the
  44836. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44837. */
  44838. _this.specularIntensity = 1.0;
  44839. /**
  44840. * Debug Control allowing disabling the bump map on this material.
  44841. */
  44842. _this.disableBumpMap = false;
  44843. /**
  44844. * AKA Occlusion Texture Intensity in other nomenclature.
  44845. */
  44846. _this.ambientTextureStrength = 1.0;
  44847. /**
  44848. * The color of a material in ambient lighting.
  44849. */
  44850. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44851. /**
  44852. * AKA Diffuse Color in other nomenclature.
  44853. */
  44854. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44855. /**
  44856. * AKA Specular Color in other nomenclature.
  44857. */
  44858. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44859. /**
  44860. * The color reflected from the material.
  44861. */
  44862. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44863. /**
  44864. * The color emitted from the material.
  44865. */
  44866. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44867. /**
  44868. * AKA Glossiness in other nomenclature.
  44869. */
  44870. _this.microSurface = 1.0;
  44871. /**
  44872. * source material index of refraction (IOR)' / 'destination material IOR.
  44873. */
  44874. _this.indexOfRefraction = 0.66;
  44875. /**
  44876. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44877. */
  44878. _this.invertRefractionY = false;
  44879. /**
  44880. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44881. * Materials half opaque for instance using refraction could benefit from this control.
  44882. */
  44883. _this.linkRefractionWithTransparency = false;
  44884. _this.useLightmapAsShadowmap = false;
  44885. /**
  44886. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44887. */
  44888. _this.useAlphaFromAlbedoTexture = false;
  44889. /**
  44890. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44891. */
  44892. _this.forceAlphaTest = false;
  44893. /**
  44894. * Defines the alpha limits in alpha test mode.
  44895. */
  44896. _this.alphaCutOff = 0.4;
  44897. /**
  44898. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44899. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44900. */
  44901. _this.useSpecularOverAlpha = true;
  44902. /**
  44903. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44904. */
  44905. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44906. /**
  44907. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44908. */
  44909. _this.useRoughnessFromMetallicTextureAlpha = true;
  44910. /**
  44911. * Specifies if the metallic texture contains the roughness information in its green channel.
  44912. */
  44913. _this.useRoughnessFromMetallicTextureGreen = false;
  44914. /**
  44915. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44916. */
  44917. _this.useMetallnessFromMetallicTextureBlue = false;
  44918. /**
  44919. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44920. */
  44921. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44922. /**
  44923. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44924. */
  44925. _this.useAmbientInGrayScale = false;
  44926. /**
  44927. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44928. * The material will try to infer what glossiness each pixel should be.
  44929. */
  44930. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44931. /**
  44932. * BJS is using an harcoded light falloff based on a manually sets up range.
  44933. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44934. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44935. */
  44936. _this.usePhysicalLightFalloff = true;
  44937. /**
  44938. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44939. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44940. */
  44941. _this.useRadianceOverAlpha = true;
  44942. /**
  44943. * Allows using an object space normal map (instead of tangent space).
  44944. */
  44945. _this.useObjectSpaceNormalMap = false;
  44946. /**
  44947. * Allows using the bump map in parallax mode.
  44948. */
  44949. _this.useParallax = false;
  44950. /**
  44951. * Allows using the bump map in parallax occlusion mode.
  44952. */
  44953. _this.useParallaxOcclusion = false;
  44954. /**
  44955. * Controls the scale bias of the parallax mode.
  44956. */
  44957. _this.parallaxScaleBias = 0.05;
  44958. /**
  44959. * If sets to true, disables all the lights affecting the material.
  44960. */
  44961. _this.disableLighting = false;
  44962. /**
  44963. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44964. */
  44965. _this.forceIrradianceInFragment = false;
  44966. /**
  44967. * Number of Simultaneous lights allowed on the material.
  44968. */
  44969. _this.maxSimultaneousLights = 4;
  44970. /**
  44971. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44972. */
  44973. _this.invertNormalMapX = false;
  44974. /**
  44975. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44976. */
  44977. _this.invertNormalMapY = false;
  44978. /**
  44979. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44980. */
  44981. _this.twoSidedLighting = false;
  44982. /**
  44983. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44984. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44985. */
  44986. _this.useAlphaFresnel = false;
  44987. /**
  44988. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44989. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44990. */
  44991. _this.useLinearAlphaFresnel = false;
  44992. /**
  44993. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44994. * And/Or occlude the blended part.
  44995. */
  44996. _this.environmentBRDFTexture = null;
  44997. /**
  44998. * Force normal to face away from face.
  44999. */
  45000. _this.forceNormalForward = false;
  45001. /**
  45002. * Enables specular anti aliasing in the PBR shader.
  45003. * It will both interacts on the Geometry for analytical and IBL lighting.
  45004. * It also prefilter the roughness map based on the bump values.
  45005. */
  45006. _this.enableSpecularAntiAliasing = false;
  45007. /**
  45008. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45009. * makes the reflect vector face the model (under horizon).
  45010. */
  45011. _this.useHorizonOcclusion = true;
  45012. /**
  45013. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45014. * too much the area relying on ambient texture to define their ambient occlusion.
  45015. */
  45016. _this.useRadianceOcclusion = true;
  45017. /**
  45018. * If set to true, no lighting calculations will be applied.
  45019. */
  45020. _this.unlit = false;
  45021. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45022. return _this;
  45023. }
  45024. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45025. /**
  45026. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45027. */
  45028. get: function () {
  45029. return this._PBRMATERIAL_OPAQUE;
  45030. },
  45031. enumerable: true,
  45032. configurable: true
  45033. });
  45034. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45035. /**
  45036. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45037. */
  45038. get: function () {
  45039. return this._PBRMATERIAL_ALPHATEST;
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45045. /**
  45046. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45047. */
  45048. get: function () {
  45049. return this._PBRMATERIAL_ALPHABLEND;
  45050. },
  45051. enumerable: true,
  45052. configurable: true
  45053. });
  45054. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45055. /**
  45056. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45057. * They are also discarded below the alpha cutoff threshold to improve performances.
  45058. */
  45059. get: function () {
  45060. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45061. },
  45062. enumerable: true,
  45063. configurable: true
  45064. });
  45065. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45066. /**
  45067. * Gets the image processing configuration used either in this material.
  45068. */
  45069. get: function () {
  45070. return this._imageProcessingConfiguration;
  45071. },
  45072. /**
  45073. * Sets the Default image processing configuration used either in the this material.
  45074. *
  45075. * If sets to null, the scene one is in use.
  45076. */
  45077. set: function (value) {
  45078. this._attachImageProcessingConfiguration(value);
  45079. // Ensure the effect will be rebuilt.
  45080. this._markAllSubMeshesAsTexturesDirty();
  45081. },
  45082. enumerable: true,
  45083. configurable: true
  45084. });
  45085. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45086. /**
  45087. * Gets wether the color curves effect is enabled.
  45088. */
  45089. get: function () {
  45090. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45091. },
  45092. /**
  45093. * Sets wether the color curves effect is enabled.
  45094. */
  45095. set: function (value) {
  45096. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45097. },
  45098. enumerable: true,
  45099. configurable: true
  45100. });
  45101. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45102. /**
  45103. * Gets wether the color grading effect is enabled.
  45104. */
  45105. get: function () {
  45106. return this.imageProcessingConfiguration.colorGradingEnabled;
  45107. },
  45108. /**
  45109. * Gets wether the color grading effect is enabled.
  45110. */
  45111. set: function (value) {
  45112. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45113. },
  45114. enumerable: true,
  45115. configurable: true
  45116. });
  45117. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45118. /**
  45119. * Gets wether tonemapping is enabled or not.
  45120. */
  45121. get: function () {
  45122. return this._imageProcessingConfiguration.toneMappingEnabled;
  45123. },
  45124. /**
  45125. * Sets wether tonemapping is enabled or not
  45126. */
  45127. set: function (value) {
  45128. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45129. },
  45130. enumerable: true,
  45131. configurable: true
  45132. });
  45133. ;
  45134. ;
  45135. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45136. /**
  45137. * The camera exposure used on this material.
  45138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45139. * This corresponds to a photographic exposure.
  45140. */
  45141. get: function () {
  45142. return this._imageProcessingConfiguration.exposure;
  45143. },
  45144. /**
  45145. * The camera exposure used on this material.
  45146. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45147. * This corresponds to a photographic exposure.
  45148. */
  45149. set: function (value) {
  45150. this._imageProcessingConfiguration.exposure = value;
  45151. },
  45152. enumerable: true,
  45153. configurable: true
  45154. });
  45155. ;
  45156. ;
  45157. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45158. /**
  45159. * Gets The camera contrast used on this material.
  45160. */
  45161. get: function () {
  45162. return this._imageProcessingConfiguration.contrast;
  45163. },
  45164. /**
  45165. * Sets The camera contrast used on this material.
  45166. */
  45167. set: function (value) {
  45168. this._imageProcessingConfiguration.contrast = value;
  45169. },
  45170. enumerable: true,
  45171. configurable: true
  45172. });
  45173. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45174. /**
  45175. * Gets the Color Grading 2D Lookup Texture.
  45176. */
  45177. get: function () {
  45178. return this._imageProcessingConfiguration.colorGradingTexture;
  45179. },
  45180. /**
  45181. * Sets the Color Grading 2D Lookup Texture.
  45182. */
  45183. set: function (value) {
  45184. this._imageProcessingConfiguration.colorGradingTexture = value;
  45185. },
  45186. enumerable: true,
  45187. configurable: true
  45188. });
  45189. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45190. /**
  45191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45193. * 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;
  45194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45195. */
  45196. get: function () {
  45197. return this._imageProcessingConfiguration.colorCurves;
  45198. },
  45199. /**
  45200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45202. * 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;
  45203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45204. */
  45205. set: function (value) {
  45206. this._imageProcessingConfiguration.colorCurves = value;
  45207. },
  45208. enumerable: true,
  45209. configurable: true
  45210. });
  45211. /**
  45212. * Returns the name of this material class.
  45213. */
  45214. PBRMaterial.prototype.getClassName = function () {
  45215. return "PBRMaterial";
  45216. };
  45217. /**
  45218. * Returns an array of the actively used textures.
  45219. * @returns - Array of BaseTextures
  45220. */
  45221. PBRMaterial.prototype.getActiveTextures = function () {
  45222. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45223. if (this._albedoTexture) {
  45224. activeTextures.push(this._albedoTexture);
  45225. }
  45226. if (this._ambientTexture) {
  45227. activeTextures.push(this._ambientTexture);
  45228. }
  45229. if (this._opacityTexture) {
  45230. activeTextures.push(this._opacityTexture);
  45231. }
  45232. if (this._reflectionTexture) {
  45233. activeTextures.push(this._reflectionTexture);
  45234. }
  45235. if (this._emissiveTexture) {
  45236. activeTextures.push(this._emissiveTexture);
  45237. }
  45238. if (this._reflectivityTexture) {
  45239. activeTextures.push(this._reflectivityTexture);
  45240. }
  45241. if (this._metallicTexture) {
  45242. activeTextures.push(this._metallicTexture);
  45243. }
  45244. if (this._microSurfaceTexture) {
  45245. activeTextures.push(this._microSurfaceTexture);
  45246. }
  45247. if (this._bumpTexture) {
  45248. activeTextures.push(this._bumpTexture);
  45249. }
  45250. if (this._lightmapTexture) {
  45251. activeTextures.push(this._lightmapTexture);
  45252. }
  45253. if (this._refractionTexture) {
  45254. activeTextures.push(this._refractionTexture);
  45255. }
  45256. return activeTextures;
  45257. };
  45258. /**
  45259. * Checks to see if a texture is used in the material.
  45260. * @param texture - Base texture to use.
  45261. * @returns - Boolean specifying if a texture is used in the material.
  45262. */
  45263. PBRMaterial.prototype.hasTexture = function (texture) {
  45264. if (_super.prototype.hasTexture.call(this, texture)) {
  45265. return true;
  45266. }
  45267. if (this._albedoTexture === texture) {
  45268. return true;
  45269. }
  45270. if (this._ambientTexture === texture) {
  45271. return true;
  45272. }
  45273. if (this._opacityTexture === texture) {
  45274. return true;
  45275. }
  45276. if (this._reflectionTexture === texture) {
  45277. return true;
  45278. }
  45279. if (this._reflectivityTexture === texture) {
  45280. return true;
  45281. }
  45282. if (this._metallicTexture === texture) {
  45283. return true;
  45284. }
  45285. if (this._microSurfaceTexture === texture) {
  45286. return true;
  45287. }
  45288. if (this._bumpTexture === texture) {
  45289. return true;
  45290. }
  45291. if (this._lightmapTexture === texture) {
  45292. return true;
  45293. }
  45294. if (this._refractionTexture === texture) {
  45295. return true;
  45296. }
  45297. return false;
  45298. };
  45299. /**
  45300. * Makes a duplicate of the current material.
  45301. * @param name - name to use for the new material.
  45302. */
  45303. PBRMaterial.prototype.clone = function (name) {
  45304. var _this = this;
  45305. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45306. clone.id = name;
  45307. clone.name = name;
  45308. return clone;
  45309. };
  45310. /**
  45311. * Serializes this PBR Material.
  45312. * @returns - An object with the serialized material.
  45313. */
  45314. PBRMaterial.prototype.serialize = function () {
  45315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45316. serializationObject.customType = "BABYLON.PBRMaterial";
  45317. return serializationObject;
  45318. };
  45319. // Statics
  45320. /**
  45321. * Parses a PBR Material from a serialized object.
  45322. * @param source - Serialized object.
  45323. * @param scene - BJS scene instance.
  45324. * @param rootUrl - url for the scene object
  45325. * @returns - PBRMaterial
  45326. */
  45327. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45328. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45329. };
  45330. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45331. /**
  45332. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45333. */
  45334. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45335. /**
  45336. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45337. */
  45338. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45339. /**
  45340. * 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.
  45341. * They are also discarded below the alpha cutoff threshold to improve performances.
  45342. */
  45343. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45344. __decorate([
  45345. BABYLON.serialize(),
  45346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45347. ], PBRMaterial.prototype, "directIntensity", void 0);
  45348. __decorate([
  45349. BABYLON.serialize(),
  45350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45351. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45352. __decorate([
  45353. BABYLON.serialize(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45355. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45356. __decorate([
  45357. BABYLON.serialize(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45359. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45360. __decorate([
  45361. BABYLON.serialize(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45363. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45364. __decorate([
  45365. BABYLON.serializeAsTexture(),
  45366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45367. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45368. __decorate([
  45369. BABYLON.serializeAsTexture(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45371. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45372. __decorate([
  45373. BABYLON.serialize(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45375. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45376. __decorate([
  45377. BABYLON.serializeAsTexture(),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45379. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45380. __decorate([
  45381. BABYLON.serializeAsTexture(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45384. __decorate([
  45385. BABYLON.serializeAsTexture(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45387. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45388. __decorate([
  45389. BABYLON.serializeAsTexture(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45391. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45392. __decorate([
  45393. BABYLON.serializeAsTexture(),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45395. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45396. __decorate([
  45397. BABYLON.serialize(),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45399. ], PBRMaterial.prototype, "metallic", void 0);
  45400. __decorate([
  45401. BABYLON.serialize(),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45403. ], PBRMaterial.prototype, "roughness", void 0);
  45404. __decorate([
  45405. BABYLON.serializeAsTexture(),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45407. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45408. __decorate([
  45409. BABYLON.serializeAsTexture(),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45411. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45412. __decorate([
  45413. BABYLON.serializeAsTexture(),
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45415. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45416. __decorate([
  45417. BABYLON.serializeAsTexture(),
  45418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45419. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45420. __decorate([
  45421. BABYLON.serializeAsColor3("ambient"),
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45423. ], PBRMaterial.prototype, "ambientColor", void 0);
  45424. __decorate([
  45425. BABYLON.serializeAsColor3("albedo"),
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], PBRMaterial.prototype, "albedoColor", void 0);
  45428. __decorate([
  45429. BABYLON.serializeAsColor3("reflectivity"),
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45431. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45432. __decorate([
  45433. BABYLON.serializeAsColor3("reflection"),
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45435. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45436. __decorate([
  45437. BABYLON.serializeAsColor3("emissive"),
  45438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45439. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45440. __decorate([
  45441. BABYLON.serialize(),
  45442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45443. ], PBRMaterial.prototype, "microSurface", void 0);
  45444. __decorate([
  45445. BABYLON.serialize(),
  45446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45447. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45448. __decorate([
  45449. BABYLON.serialize(),
  45450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45451. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45452. __decorate([
  45453. BABYLON.serialize(),
  45454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45455. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45456. __decorate([
  45457. BABYLON.serialize(),
  45458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45459. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45460. __decorate([
  45461. BABYLON.serialize(),
  45462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45463. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45464. __decorate([
  45465. BABYLON.serialize(),
  45466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45467. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45468. __decorate([
  45469. BABYLON.serialize(),
  45470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45471. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45472. __decorate([
  45473. BABYLON.serialize(),
  45474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45475. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45476. __decorate([
  45477. BABYLON.serialize(),
  45478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45479. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45480. __decorate([
  45481. BABYLON.serialize(),
  45482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45483. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45484. __decorate([
  45485. BABYLON.serialize(),
  45486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45487. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45488. __decorate([
  45489. BABYLON.serialize(),
  45490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45491. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45492. __decorate([
  45493. BABYLON.serialize(),
  45494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45495. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45500. __decorate([
  45501. BABYLON.serialize(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45512. __decorate([
  45513. BABYLON.serialize(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45515. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45516. __decorate([
  45517. BABYLON.serialize(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "useParallax", void 0);
  45520. __decorate([
  45521. BABYLON.serialize(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45523. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45524. __decorate([
  45525. BABYLON.serialize(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45527. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45528. __decorate([
  45529. BABYLON.serialize(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45531. ], PBRMaterial.prototype, "disableLighting", void 0);
  45532. __decorate([
  45533. BABYLON.serialize(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45536. __decorate([
  45537. BABYLON.serialize(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45539. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45540. __decorate([
  45541. BABYLON.serialize(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45544. __decorate([
  45545. BABYLON.serialize(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45548. __decorate([
  45549. BABYLON.serialize(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45552. __decorate([
  45553. BABYLON.serialize(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45556. __decorate([
  45557. BABYLON.serialize(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45560. __decorate([
  45561. BABYLON.serializeAsTexture(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45564. __decorate([
  45565. BABYLON.serialize(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45567. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45568. __decorate([
  45569. BABYLON.serialize(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45571. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45572. __decorate([
  45573. BABYLON.serialize(),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45576. __decorate([
  45577. BABYLON.serialize(),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45580. __decorate([
  45581. BABYLON.serialize(),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45583. ], PBRMaterial.prototype, "unlit", void 0);
  45584. return PBRMaterial;
  45585. }(BABYLON.PBRBaseMaterial));
  45586. BABYLON.PBRMaterial = PBRMaterial;
  45587. })(BABYLON || (BABYLON = {}));
  45588. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45589. var BABYLON;
  45590. (function (BABYLON) {
  45591. /**
  45592. * The PBR material of BJS following the metal roughness convention.
  45593. *
  45594. * This fits to the PBR convention in the GLTF definition:
  45595. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45596. */
  45597. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45598. __extends(PBRMetallicRoughnessMaterial, _super);
  45599. /**
  45600. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45601. *
  45602. * @param name The material name
  45603. * @param scene The scene the material will be use in.
  45604. */
  45605. function PBRMetallicRoughnessMaterial(name, scene) {
  45606. var _this = _super.call(this, name, scene) || this;
  45607. _this._useRoughnessFromMetallicTextureAlpha = false;
  45608. _this._useRoughnessFromMetallicTextureGreen = true;
  45609. _this._useMetallnessFromMetallicTextureBlue = true;
  45610. _this.metallic = 1.0;
  45611. _this.roughness = 1.0;
  45612. return _this;
  45613. }
  45614. /**
  45615. * Return the currrent class name of the material.
  45616. */
  45617. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45618. return "PBRMetallicRoughnessMaterial";
  45619. };
  45620. /**
  45621. * Return the active textures of the material.
  45622. */
  45623. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45624. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45625. if (this.baseTexture) {
  45626. activeTextures.push(this.baseTexture);
  45627. }
  45628. if (this.metallicRoughnessTexture) {
  45629. activeTextures.push(this.metallicRoughnessTexture);
  45630. }
  45631. return activeTextures;
  45632. };
  45633. /**
  45634. * Checks to see if a texture is used in the material.
  45635. * @param texture - Base texture to use.
  45636. * @returns - Boolean specifying if a texture is used in the material.
  45637. */
  45638. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45639. if (_super.prototype.hasTexture.call(this, texture)) {
  45640. return true;
  45641. }
  45642. if (this.baseTexture === texture) {
  45643. return true;
  45644. }
  45645. if (this.metallicRoughnessTexture === texture) {
  45646. return true;
  45647. }
  45648. return false;
  45649. };
  45650. /**
  45651. * Makes a duplicate of the current material.
  45652. * @param name - name to use for the new material.
  45653. */
  45654. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45655. var _this = this;
  45656. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45657. clone.id = name;
  45658. clone.name = name;
  45659. return clone;
  45660. };
  45661. /**
  45662. * Serialize the material to a parsable JSON object.
  45663. */
  45664. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45665. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45666. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45667. return serializationObject;
  45668. };
  45669. /**
  45670. * Parses a JSON object correponding to the serialize function.
  45671. */
  45672. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45673. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45674. };
  45675. __decorate([
  45676. BABYLON.serializeAsColor3(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45678. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45679. __decorate([
  45680. BABYLON.serializeAsTexture(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45682. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45690. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45691. __decorate([
  45692. BABYLON.serializeAsTexture(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45694. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45695. return PBRMetallicRoughnessMaterial;
  45696. }(BABYLON.PBRBaseSimpleMaterial));
  45697. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45698. })(BABYLON || (BABYLON = {}));
  45699. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45700. var BABYLON;
  45701. (function (BABYLON) {
  45702. /**
  45703. * The PBR material of BJS following the specular glossiness convention.
  45704. *
  45705. * This fits to the PBR convention in the GLTF definition:
  45706. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45707. */
  45708. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45709. __extends(PBRSpecularGlossinessMaterial, _super);
  45710. /**
  45711. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45712. *
  45713. * @param name The material name
  45714. * @param scene The scene the material will be use in.
  45715. */
  45716. function PBRSpecularGlossinessMaterial(name, scene) {
  45717. var _this = _super.call(this, name, scene) || this;
  45718. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45719. return _this;
  45720. }
  45721. /**
  45722. * Return the currrent class name of the material.
  45723. */
  45724. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45725. return "PBRSpecularGlossinessMaterial";
  45726. };
  45727. /**
  45728. * Return the active textures of the material.
  45729. */
  45730. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45731. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45732. if (this.diffuseTexture) {
  45733. activeTextures.push(this.diffuseTexture);
  45734. }
  45735. if (this.specularGlossinessTexture) {
  45736. activeTextures.push(this.specularGlossinessTexture);
  45737. }
  45738. return activeTextures;
  45739. };
  45740. /**
  45741. * Checks to see if a texture is used in the material.
  45742. * @param texture - Base texture to use.
  45743. * @returns - Boolean specifying if a texture is used in the material.
  45744. */
  45745. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45746. if (_super.prototype.hasTexture.call(this, texture)) {
  45747. return true;
  45748. }
  45749. if (this.diffuseTexture === texture) {
  45750. return true;
  45751. }
  45752. if (this.specularGlossinessTexture === texture) {
  45753. return true;
  45754. }
  45755. return false;
  45756. };
  45757. /**
  45758. * Makes a duplicate of the current material.
  45759. * @param name - name to use for the new material.
  45760. */
  45761. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45762. var _this = this;
  45763. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45764. clone.id = name;
  45765. clone.name = name;
  45766. return clone;
  45767. };
  45768. /**
  45769. * Serialize the material to a parsable JSON object.
  45770. */
  45771. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45772. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45773. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45774. return serializationObject;
  45775. };
  45776. /**
  45777. * Parses a JSON object correponding to the serialize function.
  45778. */
  45779. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45780. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45781. };
  45782. __decorate([
  45783. BABYLON.serializeAsColor3("diffuse"),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45785. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsTexture(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45789. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45790. __decorate([
  45791. BABYLON.serializeAsColor3("specular"),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45793. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45797. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45798. __decorate([
  45799. BABYLON.serializeAsTexture(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45801. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45802. return PBRSpecularGlossinessMaterial;
  45803. }(BABYLON.PBRBaseSimpleMaterial));
  45804. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45805. })(BABYLON || (BABYLON = {}));
  45806. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45807. var BABYLON;
  45808. (function (BABYLON) {
  45809. BABYLON.CameraInputTypes = {};
  45810. var CameraInputsManager = /** @class */ (function () {
  45811. function CameraInputsManager(camera) {
  45812. this.attached = {};
  45813. this.camera = camera;
  45814. this.checkInputs = function () { };
  45815. }
  45816. /**
  45817. * Add an input method to a camera.
  45818. * builtin inputs example: camera.inputs.addGamepad();
  45819. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45820. * @param input camera input method
  45821. */
  45822. CameraInputsManager.prototype.add = function (input) {
  45823. var type = input.getSimpleName();
  45824. if (this.attached[type]) {
  45825. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45826. return;
  45827. }
  45828. this.attached[type] = input;
  45829. input.camera = this.camera;
  45830. //for checkInputs, we are dynamically creating a function
  45831. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45832. if (input.checkInputs) {
  45833. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45834. }
  45835. if (this.attachedElement) {
  45836. input.attachControl(this.attachedElement);
  45837. }
  45838. };
  45839. /**
  45840. * Remove a specific input method from a camera
  45841. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45842. * @param inputToRemove camera input method
  45843. */
  45844. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45845. for (var cam in this.attached) {
  45846. var input = this.attached[cam];
  45847. if (input === inputToRemove) {
  45848. input.detachControl(this.attachedElement);
  45849. input.camera = null;
  45850. delete this.attached[cam];
  45851. this.rebuildInputCheck();
  45852. }
  45853. }
  45854. };
  45855. CameraInputsManager.prototype.removeByType = function (inputType) {
  45856. for (var cam in this.attached) {
  45857. var input = this.attached[cam];
  45858. if (input.getClassName() === inputType) {
  45859. input.detachControl(this.attachedElement);
  45860. input.camera = null;
  45861. delete this.attached[cam];
  45862. this.rebuildInputCheck();
  45863. }
  45864. }
  45865. };
  45866. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45867. var current = this.checkInputs;
  45868. return function () {
  45869. current();
  45870. fn();
  45871. };
  45872. };
  45873. CameraInputsManager.prototype.attachInput = function (input) {
  45874. if (this.attachedElement) {
  45875. input.attachControl(this.attachedElement, this.noPreventDefault);
  45876. }
  45877. };
  45878. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45879. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45880. if (this.attachedElement) {
  45881. return;
  45882. }
  45883. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45884. this.attachedElement = element;
  45885. this.noPreventDefault = noPreventDefault;
  45886. for (var cam in this.attached) {
  45887. this.attached[cam].attachControl(element, noPreventDefault);
  45888. }
  45889. };
  45890. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45891. if (disconnect === void 0) { disconnect = false; }
  45892. if (this.attachedElement !== element) {
  45893. return;
  45894. }
  45895. for (var cam in this.attached) {
  45896. this.attached[cam].detachControl(element);
  45897. if (disconnect) {
  45898. this.attached[cam].camera = null;
  45899. }
  45900. }
  45901. this.attachedElement = null;
  45902. };
  45903. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45904. this.checkInputs = function () { };
  45905. for (var cam in this.attached) {
  45906. var input = this.attached[cam];
  45907. if (input.checkInputs) {
  45908. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45909. }
  45910. }
  45911. };
  45912. /**
  45913. * Remove all attached input methods from a camera
  45914. */
  45915. CameraInputsManager.prototype.clear = function () {
  45916. if (this.attachedElement) {
  45917. this.detachElement(this.attachedElement, true);
  45918. }
  45919. this.attached = {};
  45920. this.attachedElement = null;
  45921. this.checkInputs = function () { };
  45922. };
  45923. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45924. var inputs = {};
  45925. for (var cam in this.attached) {
  45926. var input = this.attached[cam];
  45927. var res = BABYLON.SerializationHelper.Serialize(input);
  45928. inputs[input.getClassName()] = res;
  45929. }
  45930. serializedCamera.inputsmgr = inputs;
  45931. };
  45932. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45933. var parsedInputs = parsedCamera.inputsmgr;
  45934. if (parsedInputs) {
  45935. this.clear();
  45936. for (var n in parsedInputs) {
  45937. var construct = BABYLON.CameraInputTypes[n];
  45938. if (construct) {
  45939. var parsedinput = parsedInputs[n];
  45940. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45941. this.add(input);
  45942. }
  45943. }
  45944. }
  45945. else {
  45946. //2016-03-08 this part is for managing backward compatibility
  45947. for (var n in this.attached) {
  45948. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45949. if (construct) {
  45950. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45951. this.remove(this.attached[n]);
  45952. this.add(input);
  45953. }
  45954. }
  45955. }
  45956. };
  45957. return CameraInputsManager;
  45958. }());
  45959. BABYLON.CameraInputsManager = CameraInputsManager;
  45960. })(BABYLON || (BABYLON = {}));
  45961. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45962. var BABYLON;
  45963. (function (BABYLON) {
  45964. var TargetCamera = /** @class */ (function (_super) {
  45965. __extends(TargetCamera, _super);
  45966. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45967. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45968. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45969. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45970. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45971. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45972. _this.speed = 2.0;
  45973. _this.noRotationConstraint = false;
  45974. _this.lockedTarget = null;
  45975. _this._currentTarget = BABYLON.Vector3.Zero();
  45976. _this._viewMatrix = BABYLON.Matrix.Zero();
  45977. _this._camMatrix = BABYLON.Matrix.Zero();
  45978. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45979. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45980. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45981. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45982. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45983. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45984. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45985. return _this;
  45986. }
  45987. TargetCamera.prototype.getFrontPosition = function (distance) {
  45988. this.getWorldMatrix();
  45989. var direction = this.getTarget().subtract(this.position);
  45990. direction.normalize();
  45991. direction.scaleInPlace(distance);
  45992. return this.globalPosition.add(direction);
  45993. };
  45994. TargetCamera.prototype._getLockedTargetPosition = function () {
  45995. if (!this.lockedTarget) {
  45996. return null;
  45997. }
  45998. if (this.lockedTarget.absolutePosition) {
  45999. this.lockedTarget.computeWorldMatrix();
  46000. }
  46001. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46002. };
  46003. TargetCamera.prototype.storeState = function () {
  46004. this._storedPosition = this.position.clone();
  46005. this._storedRotation = this.rotation.clone();
  46006. if (this.rotationQuaternion) {
  46007. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46008. }
  46009. return _super.prototype.storeState.call(this);
  46010. };
  46011. /**
  46012. * Restored camera state. You must call storeState() first
  46013. */
  46014. TargetCamera.prototype._restoreStateValues = function () {
  46015. if (!_super.prototype._restoreStateValues.call(this)) {
  46016. return false;
  46017. }
  46018. this.position = this._storedPosition.clone();
  46019. this.rotation = this._storedRotation.clone();
  46020. if (this.rotationQuaternion) {
  46021. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46022. }
  46023. this.cameraDirection.copyFromFloats(0, 0, 0);
  46024. this.cameraRotation.copyFromFloats(0, 0);
  46025. return true;
  46026. };
  46027. // Cache
  46028. TargetCamera.prototype._initCache = function () {
  46029. _super.prototype._initCache.call(this);
  46030. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46031. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46032. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46033. };
  46034. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46035. if (!ignoreParentClass) {
  46036. _super.prototype._updateCache.call(this);
  46037. }
  46038. var lockedTargetPosition = this._getLockedTargetPosition();
  46039. if (!lockedTargetPosition) {
  46040. this._cache.lockedTarget = null;
  46041. }
  46042. else {
  46043. if (!this._cache.lockedTarget) {
  46044. this._cache.lockedTarget = lockedTargetPosition.clone();
  46045. }
  46046. else {
  46047. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46048. }
  46049. }
  46050. this._cache.rotation.copyFrom(this.rotation);
  46051. if (this.rotationQuaternion)
  46052. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46053. };
  46054. // Synchronized
  46055. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46056. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46057. return false;
  46058. }
  46059. var lockedTargetPosition = this._getLockedTargetPosition();
  46060. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46061. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46062. };
  46063. // Methods
  46064. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46065. var engine = this.getEngine();
  46066. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46067. };
  46068. // Target
  46069. TargetCamera.prototype.setTarget = function (target) {
  46070. this.upVector.normalize();
  46071. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46072. this._camMatrix.invert();
  46073. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46074. var vDir = target.subtract(this.position);
  46075. if (vDir.x >= 0.0) {
  46076. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46077. }
  46078. else {
  46079. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46080. }
  46081. this.rotation.z = 0;
  46082. if (isNaN(this.rotation.x)) {
  46083. this.rotation.x = 0;
  46084. }
  46085. if (isNaN(this.rotation.y)) {
  46086. this.rotation.y = 0;
  46087. }
  46088. if (isNaN(this.rotation.z)) {
  46089. this.rotation.z = 0;
  46090. }
  46091. if (this.rotationQuaternion) {
  46092. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46093. }
  46094. };
  46095. /**
  46096. * Return the current target position of the camera. This value is expressed in local space.
  46097. */
  46098. TargetCamera.prototype.getTarget = function () {
  46099. return this._currentTarget;
  46100. };
  46101. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46102. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46103. };
  46104. TargetCamera.prototype._updatePosition = function () {
  46105. if (this.parent) {
  46106. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46107. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46108. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46109. return;
  46110. }
  46111. this.position.addInPlace(this.cameraDirection);
  46112. };
  46113. TargetCamera.prototype._checkInputs = function () {
  46114. var needToMove = this._decideIfNeedsToMove();
  46115. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46116. // Move
  46117. if (needToMove) {
  46118. this._updatePosition();
  46119. }
  46120. // Rotate
  46121. if (needToRotate) {
  46122. this.rotation.x += this.cameraRotation.x;
  46123. this.rotation.y += this.cameraRotation.y;
  46124. //rotate, if quaternion is set and rotation was used
  46125. if (this.rotationQuaternion) {
  46126. var len = this.rotation.lengthSquared();
  46127. if (len) {
  46128. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46129. }
  46130. }
  46131. if (!this.noRotationConstraint) {
  46132. var limit = (Math.PI / 2) * 0.95;
  46133. if (this.rotation.x > limit)
  46134. this.rotation.x = limit;
  46135. if (this.rotation.x < -limit)
  46136. this.rotation.x = -limit;
  46137. }
  46138. }
  46139. // Inertia
  46140. if (needToMove) {
  46141. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46142. this.cameraDirection.x = 0;
  46143. }
  46144. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46145. this.cameraDirection.y = 0;
  46146. }
  46147. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46148. this.cameraDirection.z = 0;
  46149. }
  46150. this.cameraDirection.scaleInPlace(this.inertia);
  46151. }
  46152. if (needToRotate) {
  46153. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46154. this.cameraRotation.x = 0;
  46155. }
  46156. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46157. this.cameraRotation.y = 0;
  46158. }
  46159. this.cameraRotation.scaleInPlace(this.inertia);
  46160. }
  46161. _super.prototype._checkInputs.call(this);
  46162. };
  46163. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46164. if (this.rotationQuaternion) {
  46165. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46166. }
  46167. else {
  46168. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46169. }
  46170. //update the up vector!
  46171. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46172. };
  46173. TargetCamera.prototype._getViewMatrix = function () {
  46174. if (this.lockedTarget) {
  46175. this.setTarget(this._getLockedTargetPosition());
  46176. }
  46177. // Compute
  46178. this._updateCameraRotationMatrix();
  46179. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46180. // Computing target and final matrix
  46181. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46182. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46183. return this._viewMatrix;
  46184. };
  46185. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46186. if (this.parent) {
  46187. var parentWorldMatrix = this.parent.getWorldMatrix();
  46188. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46189. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46190. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46191. this._markSyncedWithParent();
  46192. }
  46193. else {
  46194. this._globalPosition.copyFrom(this.position);
  46195. this._globalCurrentTarget.copyFrom(target);
  46196. this._globalCurrentUpVector.copyFrom(up);
  46197. }
  46198. if (this.getScene().useRightHandedSystem) {
  46199. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46200. }
  46201. else {
  46202. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46203. }
  46204. };
  46205. /**
  46206. * @override
  46207. * Override Camera.createRigCamera
  46208. */
  46209. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46210. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46211. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46212. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46213. if (!this.rotationQuaternion) {
  46214. this.rotationQuaternion = new BABYLON.Quaternion();
  46215. }
  46216. rigCamera._cameraRigParams = {};
  46217. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46218. }
  46219. return rigCamera;
  46220. }
  46221. return null;
  46222. };
  46223. /**
  46224. * @override
  46225. * Override Camera._updateRigCameras
  46226. */
  46227. TargetCamera.prototype._updateRigCameras = function () {
  46228. var camLeft = this._rigCameras[0];
  46229. var camRight = this._rigCameras[1];
  46230. switch (this.cameraRigMode) {
  46231. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46232. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46233. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46234. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46235. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46236. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46237. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46238. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46239. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46240. camLeft.setTarget(this.getTarget());
  46241. camRight.setTarget(this.getTarget());
  46242. break;
  46243. case BABYLON.Camera.RIG_MODE_VR:
  46244. if (camLeft.rotationQuaternion) {
  46245. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46246. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46247. }
  46248. else {
  46249. camLeft.rotation.copyFrom(this.rotation);
  46250. camRight.rotation.copyFrom(this.rotation);
  46251. }
  46252. camLeft.position.copyFrom(this.position);
  46253. camRight.position.copyFrom(this.position);
  46254. break;
  46255. }
  46256. _super.prototype._updateRigCameras.call(this);
  46257. };
  46258. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46259. if (!this._rigCamTransformMatrix) {
  46260. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46261. }
  46262. var target = this.getTarget();
  46263. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46264. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46265. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46266. };
  46267. TargetCamera.prototype.getClassName = function () {
  46268. return "TargetCamera";
  46269. };
  46270. __decorate([
  46271. BABYLON.serializeAsVector3()
  46272. ], TargetCamera.prototype, "rotation", void 0);
  46273. __decorate([
  46274. BABYLON.serialize()
  46275. ], TargetCamera.prototype, "speed", void 0);
  46276. __decorate([
  46277. BABYLON.serializeAsMeshReference("lockedTargetId")
  46278. ], TargetCamera.prototype, "lockedTarget", void 0);
  46279. return TargetCamera;
  46280. }(BABYLON.Camera));
  46281. BABYLON.TargetCamera = TargetCamera;
  46282. })(BABYLON || (BABYLON = {}));
  46283. //# sourceMappingURL=babylon.targetCamera.js.map
  46284. var BABYLON;
  46285. (function (BABYLON) {
  46286. var FreeCameraMouseInput = /** @class */ (function () {
  46287. function FreeCameraMouseInput(touchEnabled) {
  46288. if (touchEnabled === void 0) { touchEnabled = true; }
  46289. this.touchEnabled = touchEnabled;
  46290. this.buttons = [0, 1, 2];
  46291. this.angularSensibility = 2000.0;
  46292. this.previousPosition = null;
  46293. }
  46294. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46295. var _this = this;
  46296. var engine = this.camera.getEngine();
  46297. if (!this._pointerInput) {
  46298. this._pointerInput = function (p, s) {
  46299. var evt = p.event;
  46300. if (engine.isInVRExclusivePointerMode) {
  46301. return;
  46302. }
  46303. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46304. return;
  46305. }
  46306. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46307. return;
  46308. }
  46309. var srcElement = (evt.srcElement || evt.target);
  46310. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46311. try {
  46312. srcElement.setPointerCapture(evt.pointerId);
  46313. }
  46314. catch (e) {
  46315. //Nothing to do with the error. Execution will continue.
  46316. }
  46317. _this.previousPosition = {
  46318. x: evt.clientX,
  46319. y: evt.clientY
  46320. };
  46321. if (!noPreventDefault) {
  46322. evt.preventDefault();
  46323. element.focus();
  46324. }
  46325. }
  46326. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46327. try {
  46328. srcElement.releasePointerCapture(evt.pointerId);
  46329. }
  46330. catch (e) {
  46331. //Nothing to do with the error.
  46332. }
  46333. _this.previousPosition = null;
  46334. if (!noPreventDefault) {
  46335. evt.preventDefault();
  46336. }
  46337. }
  46338. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46339. if (!_this.previousPosition || engine.isPointerLock) {
  46340. return;
  46341. }
  46342. var offsetX = evt.clientX - _this.previousPosition.x;
  46343. if (_this.camera.getScene().useRightHandedSystem)
  46344. offsetX *= -1;
  46345. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46346. offsetX *= -1;
  46347. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46348. var offsetY = evt.clientY - _this.previousPosition.y;
  46349. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46350. _this.previousPosition = {
  46351. x: evt.clientX,
  46352. y: evt.clientY
  46353. };
  46354. if (!noPreventDefault) {
  46355. evt.preventDefault();
  46356. }
  46357. }
  46358. };
  46359. }
  46360. this._onMouseMove = function (evt) {
  46361. if (!engine.isPointerLock) {
  46362. return;
  46363. }
  46364. if (engine.isInVRExclusivePointerMode) {
  46365. return;
  46366. }
  46367. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46368. if (_this.camera.getScene().useRightHandedSystem)
  46369. offsetX *= -1;
  46370. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46371. offsetX *= -1;
  46372. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46373. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46374. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46375. _this.previousPosition = null;
  46376. if (!noPreventDefault) {
  46377. evt.preventDefault();
  46378. }
  46379. };
  46380. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46381. element.addEventListener("mousemove", this._onMouseMove, false);
  46382. };
  46383. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46384. if (this._observer && element) {
  46385. this.camera.getScene().onPointerObservable.remove(this._observer);
  46386. if (this._onMouseMove) {
  46387. element.removeEventListener("mousemove", this._onMouseMove);
  46388. }
  46389. this._observer = null;
  46390. this._onMouseMove = null;
  46391. this.previousPosition = null;
  46392. }
  46393. };
  46394. FreeCameraMouseInput.prototype.getClassName = function () {
  46395. return "FreeCameraMouseInput";
  46396. };
  46397. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46398. return "mouse";
  46399. };
  46400. __decorate([
  46401. BABYLON.serialize()
  46402. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46403. __decorate([
  46404. BABYLON.serialize()
  46405. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46406. return FreeCameraMouseInput;
  46407. }());
  46408. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46409. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46410. })(BABYLON || (BABYLON = {}));
  46411. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46412. var BABYLON;
  46413. (function (BABYLON) {
  46414. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46415. function FreeCameraKeyboardMoveInput() {
  46416. this._keys = new Array();
  46417. this.keysUp = [38];
  46418. this.keysDown = [40];
  46419. this.keysLeft = [37];
  46420. this.keysRight = [39];
  46421. }
  46422. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46423. var _this = this;
  46424. if (this._onCanvasBlurObserver) {
  46425. return;
  46426. }
  46427. this._scene = this.camera.getScene();
  46428. this._engine = this._scene.getEngine();
  46429. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46430. _this._keys = [];
  46431. });
  46432. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46433. var evt = info.event;
  46434. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46435. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46436. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46437. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46438. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46439. var index = _this._keys.indexOf(evt.keyCode);
  46440. if (index === -1) {
  46441. _this._keys.push(evt.keyCode);
  46442. }
  46443. if (!noPreventDefault) {
  46444. evt.preventDefault();
  46445. }
  46446. }
  46447. }
  46448. else {
  46449. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46450. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46451. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46452. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46453. var index = _this._keys.indexOf(evt.keyCode);
  46454. if (index >= 0) {
  46455. _this._keys.splice(index, 1);
  46456. }
  46457. if (!noPreventDefault) {
  46458. evt.preventDefault();
  46459. }
  46460. }
  46461. }
  46462. });
  46463. };
  46464. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46465. if (this._scene) {
  46466. if (this._onKeyboardObserver) {
  46467. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46468. }
  46469. if (this._onCanvasBlurObserver) {
  46470. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46471. }
  46472. this._onKeyboardObserver = null;
  46473. this._onCanvasBlurObserver = null;
  46474. }
  46475. this._keys = [];
  46476. };
  46477. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46478. if (this._onKeyboardObserver) {
  46479. var camera = this.camera;
  46480. // Keyboard
  46481. for (var index = 0; index < this._keys.length; index++) {
  46482. var keyCode = this._keys[index];
  46483. var speed = camera._computeLocalCameraSpeed();
  46484. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46485. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46486. }
  46487. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46488. camera._localDirection.copyFromFloats(0, 0, speed);
  46489. }
  46490. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46491. camera._localDirection.copyFromFloats(speed, 0, 0);
  46492. }
  46493. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46494. camera._localDirection.copyFromFloats(0, 0, -speed);
  46495. }
  46496. if (camera.getScene().useRightHandedSystem) {
  46497. camera._localDirection.z *= -1;
  46498. }
  46499. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46500. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46501. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46502. }
  46503. }
  46504. };
  46505. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46506. return "FreeCameraKeyboardMoveInput";
  46507. };
  46508. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46509. this._keys = [];
  46510. };
  46511. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46512. return "keyboard";
  46513. };
  46514. __decorate([
  46515. BABYLON.serialize()
  46516. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46517. __decorate([
  46518. BABYLON.serialize()
  46519. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46520. __decorate([
  46521. BABYLON.serialize()
  46522. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46523. __decorate([
  46524. BABYLON.serialize()
  46525. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46526. return FreeCameraKeyboardMoveInput;
  46527. }());
  46528. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46529. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46530. })(BABYLON || (BABYLON = {}));
  46531. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46532. var BABYLON;
  46533. (function (BABYLON) {
  46534. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46535. __extends(FreeCameraInputsManager, _super);
  46536. function FreeCameraInputsManager(camera) {
  46537. return _super.call(this, camera) || this;
  46538. }
  46539. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46540. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46541. return this;
  46542. };
  46543. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46544. if (touchEnabled === void 0) { touchEnabled = true; }
  46545. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46546. return this;
  46547. };
  46548. FreeCameraInputsManager.prototype.addGamepad = function () {
  46549. this.add(new BABYLON.FreeCameraGamepadInput());
  46550. return this;
  46551. };
  46552. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46553. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46554. return this;
  46555. };
  46556. FreeCameraInputsManager.prototype.addTouch = function () {
  46557. this.add(new BABYLON.FreeCameraTouchInput());
  46558. return this;
  46559. };
  46560. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46561. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46562. return this;
  46563. };
  46564. return FreeCameraInputsManager;
  46565. }(BABYLON.CameraInputsManager));
  46566. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46567. })(BABYLON || (BABYLON = {}));
  46568. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46569. var BABYLON;
  46570. (function (BABYLON) {
  46571. var FreeCamera = /** @class */ (function (_super) {
  46572. __extends(FreeCamera, _super);
  46573. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46574. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46575. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46576. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46577. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46578. _this.checkCollisions = false;
  46579. _this.applyGravity = false;
  46580. _this._needMoveForGravity = false;
  46581. _this._oldPosition = BABYLON.Vector3.Zero();
  46582. _this._diffPosition = BABYLON.Vector3.Zero();
  46583. _this._newPosition = BABYLON.Vector3.Zero();
  46584. // Collisions
  46585. _this._collisionMask = -1;
  46586. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46587. if (collidedMesh === void 0) { collidedMesh = null; }
  46588. //TODO move this to the collision coordinator!
  46589. if (_this.getScene().workerCollisions)
  46590. newPosition.multiplyInPlace(_this._collider._radius);
  46591. var updatePosition = function (newPos) {
  46592. _this._newPosition.copyFrom(newPos);
  46593. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46594. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46595. _this.position.addInPlace(_this._diffPosition);
  46596. if (_this.onCollide && collidedMesh) {
  46597. _this.onCollide(collidedMesh);
  46598. }
  46599. }
  46600. };
  46601. updatePosition(newPosition);
  46602. };
  46603. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46604. _this.inputs.addKeyboard().addMouse();
  46605. return _this;
  46606. }
  46607. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46608. //-- begin properties for backward compatibility for inputs
  46609. /**
  46610. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46611. * Higher values reduce sensitivity.
  46612. */
  46613. get: function () {
  46614. var mouse = this.inputs.attached["mouse"];
  46615. if (mouse)
  46616. return mouse.angularSensibility;
  46617. return 0;
  46618. },
  46619. /**
  46620. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46621. * Higher values reduce sensitivity.
  46622. */
  46623. set: function (value) {
  46624. var mouse = this.inputs.attached["mouse"];
  46625. if (mouse)
  46626. mouse.angularSensibility = value;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46632. get: function () {
  46633. var keyboard = this.inputs.attached["keyboard"];
  46634. if (keyboard)
  46635. return keyboard.keysUp;
  46636. return [];
  46637. },
  46638. set: function (value) {
  46639. var keyboard = this.inputs.attached["keyboard"];
  46640. if (keyboard)
  46641. keyboard.keysUp = value;
  46642. },
  46643. enumerable: true,
  46644. configurable: true
  46645. });
  46646. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46647. get: function () {
  46648. var keyboard = this.inputs.attached["keyboard"];
  46649. if (keyboard)
  46650. return keyboard.keysDown;
  46651. return [];
  46652. },
  46653. set: function (value) {
  46654. var keyboard = this.inputs.attached["keyboard"];
  46655. if (keyboard)
  46656. keyboard.keysDown = value;
  46657. },
  46658. enumerable: true,
  46659. configurable: true
  46660. });
  46661. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46662. get: function () {
  46663. var keyboard = this.inputs.attached["keyboard"];
  46664. if (keyboard)
  46665. return keyboard.keysLeft;
  46666. return [];
  46667. },
  46668. set: function (value) {
  46669. var keyboard = this.inputs.attached["keyboard"];
  46670. if (keyboard)
  46671. keyboard.keysLeft = value;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46677. get: function () {
  46678. var keyboard = this.inputs.attached["keyboard"];
  46679. if (keyboard)
  46680. return keyboard.keysRight;
  46681. return [];
  46682. },
  46683. set: function (value) {
  46684. var keyboard = this.inputs.attached["keyboard"];
  46685. if (keyboard)
  46686. keyboard.keysRight = value;
  46687. },
  46688. enumerable: true,
  46689. configurable: true
  46690. });
  46691. // Controls
  46692. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46693. this.inputs.attachElement(element, noPreventDefault);
  46694. };
  46695. FreeCamera.prototype.detachControl = function (element) {
  46696. this.inputs.detachElement(element);
  46697. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46698. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46699. };
  46700. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46701. get: function () {
  46702. return this._collisionMask;
  46703. },
  46704. set: function (mask) {
  46705. this._collisionMask = !isNaN(mask) ? mask : -1;
  46706. },
  46707. enumerable: true,
  46708. configurable: true
  46709. });
  46710. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46711. var globalPosition;
  46712. if (this.parent) {
  46713. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46714. }
  46715. else {
  46716. globalPosition = this.position;
  46717. }
  46718. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46719. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46720. if (!this._collider) {
  46721. this._collider = new BABYLON.Collider();
  46722. }
  46723. this._collider._radius = this.ellipsoid;
  46724. this._collider.collisionMask = this._collisionMask;
  46725. //no need for clone, as long as gravity is not on.
  46726. var actualDisplacement = displacement;
  46727. //add gravity to the direction to prevent the dual-collision checking
  46728. if (this.applyGravity) {
  46729. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46730. actualDisplacement = displacement.add(this.getScene().gravity);
  46731. }
  46732. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46733. };
  46734. FreeCamera.prototype._checkInputs = function () {
  46735. if (!this._localDirection) {
  46736. this._localDirection = BABYLON.Vector3.Zero();
  46737. this._transformedDirection = BABYLON.Vector3.Zero();
  46738. }
  46739. this.inputs.checkInputs();
  46740. _super.prototype._checkInputs.call(this);
  46741. };
  46742. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46743. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46744. };
  46745. FreeCamera.prototype._updatePosition = function () {
  46746. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46747. this._collideWithWorld(this.cameraDirection);
  46748. }
  46749. else {
  46750. _super.prototype._updatePosition.call(this);
  46751. }
  46752. };
  46753. FreeCamera.prototype.dispose = function () {
  46754. this.inputs.clear();
  46755. _super.prototype.dispose.call(this);
  46756. };
  46757. FreeCamera.prototype.getClassName = function () {
  46758. return "FreeCamera";
  46759. };
  46760. __decorate([
  46761. BABYLON.serializeAsVector3()
  46762. ], FreeCamera.prototype, "ellipsoid", void 0);
  46763. __decorate([
  46764. BABYLON.serializeAsVector3()
  46765. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], FreeCamera.prototype, "checkCollisions", void 0);
  46769. __decorate([
  46770. BABYLON.serialize()
  46771. ], FreeCamera.prototype, "applyGravity", void 0);
  46772. return FreeCamera;
  46773. }(BABYLON.TargetCamera));
  46774. BABYLON.FreeCamera = FreeCamera;
  46775. })(BABYLON || (BABYLON = {}));
  46776. //# sourceMappingURL=babylon.freeCamera.js.map
  46777. var BABYLON;
  46778. (function (BABYLON) {
  46779. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46780. function ArcRotateCameraKeyboardMoveInput() {
  46781. this._keys = new Array();
  46782. this.keysUp = [38];
  46783. this.keysDown = [40];
  46784. this.keysLeft = [37];
  46785. this.keysRight = [39];
  46786. this.keysReset = [220];
  46787. this.panningSensibility = 50.0;
  46788. this.zoomingSensibility = 25.0;
  46789. this.useAltToZoom = true;
  46790. }
  46791. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46792. var _this = this;
  46793. if (this._onCanvasBlurObserver) {
  46794. return;
  46795. }
  46796. this._scene = this.camera.getScene();
  46797. this._engine = this._scene.getEngine();
  46798. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46799. _this._keys = [];
  46800. });
  46801. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46802. var evt = info.event;
  46803. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46804. _this._ctrlPressed = evt.ctrlKey;
  46805. _this._altPressed = evt.altKey;
  46806. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46807. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46808. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46809. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46810. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46811. var index = _this._keys.indexOf(evt.keyCode);
  46812. if (index === -1) {
  46813. _this._keys.push(evt.keyCode);
  46814. }
  46815. if (evt.preventDefault) {
  46816. if (!noPreventDefault) {
  46817. evt.preventDefault();
  46818. }
  46819. }
  46820. }
  46821. }
  46822. else {
  46823. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46824. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46825. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46826. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46827. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46828. var index = _this._keys.indexOf(evt.keyCode);
  46829. if (index >= 0) {
  46830. _this._keys.splice(index, 1);
  46831. }
  46832. if (evt.preventDefault) {
  46833. if (!noPreventDefault) {
  46834. evt.preventDefault();
  46835. }
  46836. }
  46837. }
  46838. }
  46839. });
  46840. };
  46841. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46842. if (this._scene) {
  46843. if (this._onKeyboardObserver) {
  46844. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46845. }
  46846. if (this._onCanvasBlurObserver) {
  46847. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46848. }
  46849. this._onKeyboardObserver = null;
  46850. this._onCanvasBlurObserver = null;
  46851. }
  46852. this._keys = [];
  46853. };
  46854. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46855. if (this._onKeyboardObserver) {
  46856. var camera = this.camera;
  46857. for (var index = 0; index < this._keys.length; index++) {
  46858. var keyCode = this._keys[index];
  46859. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46860. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46861. camera.inertialPanningX -= 1 / this.panningSensibility;
  46862. }
  46863. else {
  46864. camera.inertialAlphaOffset -= 0.01;
  46865. }
  46866. }
  46867. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46868. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46869. camera.inertialPanningY += 1 / this.panningSensibility;
  46870. }
  46871. else if (this._altPressed && this.useAltToZoom) {
  46872. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46873. }
  46874. else {
  46875. camera.inertialBetaOffset -= 0.01;
  46876. }
  46877. }
  46878. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46879. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46880. camera.inertialPanningX += 1 / this.panningSensibility;
  46881. }
  46882. else {
  46883. camera.inertialAlphaOffset += 0.01;
  46884. }
  46885. }
  46886. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46887. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46888. camera.inertialPanningY -= 1 / this.panningSensibility;
  46889. }
  46890. else if (this._altPressed && this.useAltToZoom) {
  46891. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46892. }
  46893. else {
  46894. camera.inertialBetaOffset += 0.01;
  46895. }
  46896. }
  46897. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46898. camera.restoreState();
  46899. }
  46900. }
  46901. }
  46902. };
  46903. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46904. return "ArcRotateCameraKeyboardMoveInput";
  46905. };
  46906. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46907. return "keyboard";
  46908. };
  46909. __decorate([
  46910. BABYLON.serialize()
  46911. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46912. __decorate([
  46913. BABYLON.serialize()
  46914. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46915. __decorate([
  46916. BABYLON.serialize()
  46917. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46918. __decorate([
  46919. BABYLON.serialize()
  46920. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46924. __decorate([
  46925. BABYLON.serialize()
  46926. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46927. __decorate([
  46928. BABYLON.serialize()
  46929. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46930. __decorate([
  46931. BABYLON.serialize()
  46932. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46933. return ArcRotateCameraKeyboardMoveInput;
  46934. }());
  46935. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46936. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46937. })(BABYLON || (BABYLON = {}));
  46938. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46939. var BABYLON;
  46940. (function (BABYLON) {
  46941. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46942. function ArcRotateCameraMouseWheelInput() {
  46943. this.wheelPrecision = 3.0;
  46944. /**
  46945. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46946. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46947. */
  46948. this.wheelDeltaPercentage = 0;
  46949. }
  46950. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46951. var _this = this;
  46952. this._wheel = function (p, s) {
  46953. //sanity check - this should be a PointerWheel event.
  46954. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46955. return;
  46956. var event = p.event;
  46957. var delta = 0;
  46958. if (event.wheelDelta) {
  46959. if (_this.wheelDeltaPercentage) {
  46960. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46961. if (event.wheelDelta > 0) {
  46962. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46963. }
  46964. else {
  46965. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46966. }
  46967. }
  46968. else {
  46969. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46970. }
  46971. }
  46972. else if (event.detail) {
  46973. delta = -event.detail / _this.wheelPrecision;
  46974. }
  46975. if (delta)
  46976. _this.camera.inertialRadiusOffset += delta;
  46977. if (event.preventDefault) {
  46978. if (!noPreventDefault) {
  46979. event.preventDefault();
  46980. }
  46981. }
  46982. };
  46983. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46984. };
  46985. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46986. if (this._observer && element) {
  46987. this.camera.getScene().onPointerObservable.remove(this._observer);
  46988. this._observer = null;
  46989. this._wheel = null;
  46990. }
  46991. };
  46992. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46993. return "ArcRotateCameraMouseWheelInput";
  46994. };
  46995. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46996. return "mousewheel";
  46997. };
  46998. __decorate([
  46999. BABYLON.serialize()
  47000. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47001. __decorate([
  47002. BABYLON.serialize()
  47003. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47004. return ArcRotateCameraMouseWheelInput;
  47005. }());
  47006. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47007. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47008. })(BABYLON || (BABYLON = {}));
  47009. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47010. var BABYLON;
  47011. (function (BABYLON) {
  47012. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47013. function ArcRotateCameraPointersInput() {
  47014. this.buttons = [0, 1, 2];
  47015. this.angularSensibilityX = 1000.0;
  47016. this.angularSensibilityY = 1000.0;
  47017. this.pinchPrecision = 12.0;
  47018. /**
  47019. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47020. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47021. */
  47022. this.pinchDeltaPercentage = 0;
  47023. this.panningSensibility = 1000.0;
  47024. this.multiTouchPanning = true;
  47025. this.multiTouchPanAndZoom = true;
  47026. this._isPanClick = false;
  47027. this.pinchInwards = true;
  47028. }
  47029. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47030. var _this = this;
  47031. var engine = this.camera.getEngine();
  47032. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47033. var pointA = null;
  47034. var pointB = null;
  47035. var previousPinchSquaredDistance = 0;
  47036. var initialDistance = 0;
  47037. var twoFingerActivityCount = 0;
  47038. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47039. this._pointerInput = function (p, s) {
  47040. var evt = p.event;
  47041. var isTouch = p.event.pointerType === "touch";
  47042. if (engine.isInVRExclusivePointerMode) {
  47043. return;
  47044. }
  47045. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47046. return;
  47047. }
  47048. var srcElement = (evt.srcElement || evt.target);
  47049. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47050. try {
  47051. srcElement.setPointerCapture(evt.pointerId);
  47052. }
  47053. catch (e) {
  47054. //Nothing to do with the error. Execution will continue.
  47055. }
  47056. // Manage panning with pan button click
  47057. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47058. // manage pointers
  47059. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47060. if (pointA === null) {
  47061. pointA = cacheSoloPointer;
  47062. }
  47063. else if (pointB === null) {
  47064. pointB = cacheSoloPointer;
  47065. }
  47066. if (!noPreventDefault) {
  47067. evt.preventDefault();
  47068. element.focus();
  47069. }
  47070. }
  47071. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47072. _this.camera.restoreState();
  47073. }
  47074. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47075. try {
  47076. srcElement.releasePointerCapture(evt.pointerId);
  47077. }
  47078. catch (e) {
  47079. //Nothing to do with the error.
  47080. }
  47081. cacheSoloPointer = null;
  47082. previousPinchSquaredDistance = 0;
  47083. previousMultiTouchPanPosition.isPaning = false;
  47084. previousMultiTouchPanPosition.isPinching = false;
  47085. twoFingerActivityCount = 0;
  47086. initialDistance = 0;
  47087. if (!isTouch) {
  47088. pointB = null; // Mouse and pen are mono pointer
  47089. }
  47090. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47091. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47092. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47093. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47094. if (engine._badOS) {
  47095. pointA = pointB = null;
  47096. }
  47097. else {
  47098. //only remove the impacted pointer in case of multitouch allowing on most
  47099. //platforms switching from rotate to zoom and pan seamlessly.
  47100. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47101. pointA = pointB;
  47102. pointB = null;
  47103. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47104. }
  47105. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47106. pointB = null;
  47107. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47108. }
  47109. else {
  47110. pointA = pointB = null;
  47111. }
  47112. }
  47113. if (!noPreventDefault) {
  47114. evt.preventDefault();
  47115. }
  47116. }
  47117. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47118. if (!noPreventDefault) {
  47119. evt.preventDefault();
  47120. }
  47121. // One button down
  47122. if (pointA && pointB === null && cacheSoloPointer) {
  47123. if (_this.panningSensibility !== 0 &&
  47124. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47125. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47126. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47127. }
  47128. else {
  47129. var offsetX = evt.clientX - cacheSoloPointer.x;
  47130. var offsetY = evt.clientY - cacheSoloPointer.y;
  47131. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47132. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47133. }
  47134. cacheSoloPointer.x = evt.clientX;
  47135. cacheSoloPointer.y = evt.clientY;
  47136. }
  47137. // Two buttons down: pinch/pan
  47138. else if (pointA && pointB) {
  47139. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47140. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47141. ed.x = evt.clientX;
  47142. ed.y = evt.clientY;
  47143. var direction = _this.pinchInwards ? 1 : -1;
  47144. var distX = pointA.x - pointB.x;
  47145. var distY = pointA.y - pointB.y;
  47146. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47147. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47148. if (previousPinchSquaredDistance === 0) {
  47149. initialDistance = pinchDistance;
  47150. previousPinchSquaredDistance = pinchSquaredDistance;
  47151. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47152. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47153. return;
  47154. }
  47155. if (_this.multiTouchPanAndZoom) {
  47156. if (_this.pinchDeltaPercentage) {
  47157. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47158. }
  47159. else {
  47160. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47161. (_this.pinchPrecision *
  47162. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47163. direction);
  47164. }
  47165. if (_this.panningSensibility !== 0) {
  47166. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47167. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47168. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47169. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47170. previousMultiTouchPanPosition.x = pointersCenterX;
  47171. previousMultiTouchPanPosition.y = pointersCenterY;
  47172. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47173. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47174. }
  47175. }
  47176. else {
  47177. twoFingerActivityCount++;
  47178. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47179. if (_this.pinchDeltaPercentage) {
  47180. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47181. }
  47182. else {
  47183. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47184. (_this.pinchPrecision *
  47185. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47186. direction);
  47187. }
  47188. previousMultiTouchPanPosition.isPaning = false;
  47189. previousMultiTouchPanPosition.isPinching = true;
  47190. }
  47191. else {
  47192. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47193. if (!previousMultiTouchPanPosition.isPaning) {
  47194. previousMultiTouchPanPosition.isPaning = true;
  47195. previousMultiTouchPanPosition.isPinching = false;
  47196. previousMultiTouchPanPosition.x = ed.x;
  47197. previousMultiTouchPanPosition.y = ed.y;
  47198. return;
  47199. }
  47200. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47201. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47202. }
  47203. }
  47204. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47205. previousMultiTouchPanPosition.x = ed.x;
  47206. previousMultiTouchPanPosition.y = ed.y;
  47207. }
  47208. }
  47209. previousPinchSquaredDistance = pinchSquaredDistance;
  47210. }
  47211. }
  47212. };
  47213. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47214. this._onContextMenu = function (evt) {
  47215. evt.preventDefault();
  47216. };
  47217. if (!this.camera._useCtrlForPanning) {
  47218. element.addEventListener("contextmenu", this._onContextMenu, false);
  47219. }
  47220. this._onLostFocus = function () {
  47221. //this._keys = [];
  47222. pointA = pointB = null;
  47223. previousPinchSquaredDistance = 0;
  47224. previousMultiTouchPanPosition.isPaning = false;
  47225. previousMultiTouchPanPosition.isPinching = false;
  47226. twoFingerActivityCount = 0;
  47227. cacheSoloPointer = null;
  47228. initialDistance = 0;
  47229. };
  47230. this._onMouseMove = function (evt) {
  47231. if (!engine.isPointerLock) {
  47232. return;
  47233. }
  47234. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47235. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47236. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47237. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47238. if (!noPreventDefault) {
  47239. evt.preventDefault();
  47240. }
  47241. };
  47242. this._onGestureStart = function (e) {
  47243. if (window.MSGesture === undefined) {
  47244. return;
  47245. }
  47246. if (!_this._MSGestureHandler) {
  47247. _this._MSGestureHandler = new MSGesture();
  47248. _this._MSGestureHandler.target = element;
  47249. }
  47250. _this._MSGestureHandler.addPointer(e.pointerId);
  47251. };
  47252. this._onGesture = function (e) {
  47253. _this.camera.radius *= e.scale;
  47254. if (e.preventDefault) {
  47255. if (!noPreventDefault) {
  47256. e.stopPropagation();
  47257. e.preventDefault();
  47258. }
  47259. }
  47260. };
  47261. element.addEventListener("mousemove", this._onMouseMove, false);
  47262. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47263. element.addEventListener("MSGestureChange", this._onGesture, false);
  47264. BABYLON.Tools.RegisterTopRootEvents([
  47265. { name: "blur", handler: this._onLostFocus }
  47266. ]);
  47267. };
  47268. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47269. if (this._onLostFocus) {
  47270. BABYLON.Tools.UnregisterTopRootEvents([
  47271. { name: "blur", handler: this._onLostFocus }
  47272. ]);
  47273. }
  47274. if (element && this._observer) {
  47275. this.camera.getScene().onPointerObservable.remove(this._observer);
  47276. this._observer = null;
  47277. if (this._onContextMenu) {
  47278. element.removeEventListener("contextmenu", this._onContextMenu);
  47279. }
  47280. if (this._onMouseMove) {
  47281. element.removeEventListener("mousemove", this._onMouseMove);
  47282. }
  47283. if (this._onGestureStart) {
  47284. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47285. }
  47286. if (this._onGesture) {
  47287. element.removeEventListener("MSGestureChange", this._onGesture);
  47288. }
  47289. this._isPanClick = false;
  47290. this.pinchInwards = true;
  47291. this._onMouseMove = null;
  47292. this._onGestureStart = null;
  47293. this._onGesture = null;
  47294. this._MSGestureHandler = null;
  47295. this._onLostFocus = null;
  47296. this._onContextMenu = null;
  47297. }
  47298. };
  47299. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47300. return "ArcRotateCameraPointersInput";
  47301. };
  47302. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47303. return "pointers";
  47304. };
  47305. __decorate([
  47306. BABYLON.serialize()
  47307. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47308. __decorate([
  47309. BABYLON.serialize()
  47310. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47311. __decorate([
  47312. BABYLON.serialize()
  47313. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47314. __decorate([
  47315. BABYLON.serialize()
  47316. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47317. __decorate([
  47318. BABYLON.serialize()
  47319. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47320. __decorate([
  47321. BABYLON.serialize()
  47322. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47323. __decorate([
  47324. BABYLON.serialize()
  47325. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47326. __decorate([
  47327. BABYLON.serialize()
  47328. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47329. return ArcRotateCameraPointersInput;
  47330. }());
  47331. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47332. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47333. })(BABYLON || (BABYLON = {}));
  47334. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47335. var BABYLON;
  47336. (function (BABYLON) {
  47337. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47338. __extends(ArcRotateCameraInputsManager, _super);
  47339. function ArcRotateCameraInputsManager(camera) {
  47340. return _super.call(this, camera) || this;
  47341. }
  47342. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47343. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47344. return this;
  47345. };
  47346. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47347. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47348. return this;
  47349. };
  47350. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47351. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47352. return this;
  47353. };
  47354. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47355. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47356. return this;
  47357. };
  47358. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47359. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47360. return this;
  47361. };
  47362. return ArcRotateCameraInputsManager;
  47363. }(BABYLON.CameraInputsManager));
  47364. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47365. })(BABYLON || (BABYLON = {}));
  47366. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47367. var BABYLON;
  47368. (function (BABYLON) {
  47369. var ArcRotateCamera = /** @class */ (function (_super) {
  47370. __extends(ArcRotateCamera, _super);
  47371. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47372. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47373. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47374. _this.inertialAlphaOffset = 0;
  47375. _this.inertialBetaOffset = 0;
  47376. _this.inertialRadiusOffset = 0;
  47377. _this.lowerAlphaLimit = null;
  47378. _this.upperAlphaLimit = null;
  47379. _this.lowerBetaLimit = 0.01;
  47380. _this.upperBetaLimit = Math.PI;
  47381. _this.lowerRadiusLimit = null;
  47382. _this.upperRadiusLimit = null;
  47383. _this.inertialPanningX = 0;
  47384. _this.inertialPanningY = 0;
  47385. _this.pinchToPanMaxDistance = 20;
  47386. _this.panningDistanceLimit = null;
  47387. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47388. _this.panningInertia = 0.9;
  47389. //-- end properties for backward compatibility for inputs
  47390. _this.zoomOnFactor = 1;
  47391. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47392. _this.allowUpsideDown = true;
  47393. _this._viewMatrix = new BABYLON.Matrix();
  47394. // Panning
  47395. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47396. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47397. _this.checkCollisions = false;
  47398. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47399. _this._previousPosition = BABYLON.Vector3.Zero();
  47400. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47401. _this._newPosition = BABYLON.Vector3.Zero();
  47402. _this._computationVector = BABYLON.Vector3.Zero();
  47403. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47404. if (collidedMesh === void 0) { collidedMesh = null; }
  47405. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47406. newPosition.multiplyInPlace(_this._collider._radius);
  47407. }
  47408. if (!collidedMesh) {
  47409. _this._previousPosition.copyFrom(_this.position);
  47410. }
  47411. else {
  47412. _this.setPosition(newPosition);
  47413. if (_this.onCollide) {
  47414. _this.onCollide(collidedMesh);
  47415. }
  47416. }
  47417. // Recompute because of constraints
  47418. var cosa = Math.cos(_this.alpha);
  47419. var sina = Math.sin(_this.alpha);
  47420. var cosb = Math.cos(_this.beta);
  47421. var sinb = Math.sin(_this.beta);
  47422. if (sinb === 0) {
  47423. sinb = 0.0001;
  47424. }
  47425. var target = _this._getTargetPosition();
  47426. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47427. target.addToRef(_this._computationVector, _this._newPosition);
  47428. _this.position.copyFrom(_this._newPosition);
  47429. var up = _this.upVector;
  47430. if (_this.allowUpsideDown && _this.beta < 0) {
  47431. up = up.clone();
  47432. up = up.negate();
  47433. }
  47434. _this._computeViewMatrix(_this.position, target, up);
  47435. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47436. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47437. _this._collisionTriggered = false;
  47438. };
  47439. _this._target = BABYLON.Vector3.Zero();
  47440. if (target) {
  47441. _this.setTarget(target);
  47442. }
  47443. _this.alpha = alpha;
  47444. _this.beta = beta;
  47445. _this.radius = radius;
  47446. _this.getViewMatrix();
  47447. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47448. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47449. return _this;
  47450. }
  47451. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47452. get: function () {
  47453. return this._target;
  47454. },
  47455. set: function (value) {
  47456. this.setTarget(value);
  47457. },
  47458. enumerable: true,
  47459. configurable: true
  47460. });
  47461. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47462. //-- begin properties for backward compatibility for inputs
  47463. get: function () {
  47464. var pointers = this.inputs.attached["pointers"];
  47465. if (pointers)
  47466. return pointers.angularSensibilityX;
  47467. return 0;
  47468. },
  47469. set: function (value) {
  47470. var pointers = this.inputs.attached["pointers"];
  47471. if (pointers) {
  47472. pointers.angularSensibilityX = value;
  47473. }
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47479. get: function () {
  47480. var pointers = this.inputs.attached["pointers"];
  47481. if (pointers)
  47482. return pointers.angularSensibilityY;
  47483. return 0;
  47484. },
  47485. set: function (value) {
  47486. var pointers = this.inputs.attached["pointers"];
  47487. if (pointers) {
  47488. pointers.angularSensibilityY = value;
  47489. }
  47490. },
  47491. enumerable: true,
  47492. configurable: true
  47493. });
  47494. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47495. get: function () {
  47496. var pointers = this.inputs.attached["pointers"];
  47497. if (pointers)
  47498. return pointers.pinchPrecision;
  47499. return 0;
  47500. },
  47501. set: function (value) {
  47502. var pointers = this.inputs.attached["pointers"];
  47503. if (pointers) {
  47504. pointers.pinchPrecision = value;
  47505. }
  47506. },
  47507. enumerable: true,
  47508. configurable: true
  47509. });
  47510. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47511. get: function () {
  47512. var pointers = this.inputs.attached["pointers"];
  47513. if (pointers)
  47514. return pointers.pinchDeltaPercentage;
  47515. return 0;
  47516. },
  47517. set: function (value) {
  47518. var pointers = this.inputs.attached["pointers"];
  47519. if (pointers) {
  47520. pointers.pinchDeltaPercentage = value;
  47521. }
  47522. },
  47523. enumerable: true,
  47524. configurable: true
  47525. });
  47526. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47527. get: function () {
  47528. var pointers = this.inputs.attached["pointers"];
  47529. if (pointers)
  47530. return pointers.panningSensibility;
  47531. return 0;
  47532. },
  47533. set: function (value) {
  47534. var pointers = this.inputs.attached["pointers"];
  47535. if (pointers) {
  47536. pointers.panningSensibility = value;
  47537. }
  47538. },
  47539. enumerable: true,
  47540. configurable: true
  47541. });
  47542. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47543. get: function () {
  47544. var keyboard = this.inputs.attached["keyboard"];
  47545. if (keyboard)
  47546. return keyboard.keysUp;
  47547. return [];
  47548. },
  47549. set: function (value) {
  47550. var keyboard = this.inputs.attached["keyboard"];
  47551. if (keyboard)
  47552. keyboard.keysUp = value;
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47558. get: function () {
  47559. var keyboard = this.inputs.attached["keyboard"];
  47560. if (keyboard)
  47561. return keyboard.keysDown;
  47562. return [];
  47563. },
  47564. set: function (value) {
  47565. var keyboard = this.inputs.attached["keyboard"];
  47566. if (keyboard)
  47567. keyboard.keysDown = value;
  47568. },
  47569. enumerable: true,
  47570. configurable: true
  47571. });
  47572. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47573. get: function () {
  47574. var keyboard = this.inputs.attached["keyboard"];
  47575. if (keyboard)
  47576. return keyboard.keysLeft;
  47577. return [];
  47578. },
  47579. set: function (value) {
  47580. var keyboard = this.inputs.attached["keyboard"];
  47581. if (keyboard)
  47582. keyboard.keysLeft = value;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47588. get: function () {
  47589. var keyboard = this.inputs.attached["keyboard"];
  47590. if (keyboard)
  47591. return keyboard.keysRight;
  47592. return [];
  47593. },
  47594. set: function (value) {
  47595. var keyboard = this.inputs.attached["keyboard"];
  47596. if (keyboard)
  47597. keyboard.keysRight = value;
  47598. },
  47599. enumerable: true,
  47600. configurable: true
  47601. });
  47602. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47603. get: function () {
  47604. var mousewheel = this.inputs.attached["mousewheel"];
  47605. if (mousewheel)
  47606. return mousewheel.wheelPrecision;
  47607. return 0;
  47608. },
  47609. set: function (value) {
  47610. var mousewheel = this.inputs.attached["mousewheel"];
  47611. if (mousewheel)
  47612. mousewheel.wheelPrecision = value;
  47613. },
  47614. enumerable: true,
  47615. configurable: true
  47616. });
  47617. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47618. get: function () {
  47619. var mousewheel = this.inputs.attached["mousewheel"];
  47620. if (mousewheel)
  47621. return mousewheel.wheelDeltaPercentage;
  47622. return 0;
  47623. },
  47624. set: function (value) {
  47625. var mousewheel = this.inputs.attached["mousewheel"];
  47626. if (mousewheel)
  47627. mousewheel.wheelDeltaPercentage = value;
  47628. },
  47629. enumerable: true,
  47630. configurable: true
  47631. });
  47632. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47633. get: function () {
  47634. return this._bouncingBehavior;
  47635. },
  47636. enumerable: true,
  47637. configurable: true
  47638. });
  47639. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47640. get: function () {
  47641. return this._bouncingBehavior != null;
  47642. },
  47643. set: function (value) {
  47644. if (value === this.useBouncingBehavior) {
  47645. return;
  47646. }
  47647. if (value) {
  47648. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47649. this.addBehavior(this._bouncingBehavior);
  47650. }
  47651. else if (this._bouncingBehavior) {
  47652. this.removeBehavior(this._bouncingBehavior);
  47653. this._bouncingBehavior = null;
  47654. }
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47660. get: function () {
  47661. return this._framingBehavior;
  47662. },
  47663. enumerable: true,
  47664. configurable: true
  47665. });
  47666. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47667. get: function () {
  47668. return this._framingBehavior != null;
  47669. },
  47670. set: function (value) {
  47671. if (value === this.useFramingBehavior) {
  47672. return;
  47673. }
  47674. if (value) {
  47675. this._framingBehavior = new BABYLON.FramingBehavior();
  47676. this.addBehavior(this._framingBehavior);
  47677. }
  47678. else if (this._framingBehavior) {
  47679. this.removeBehavior(this._framingBehavior);
  47680. this._framingBehavior = null;
  47681. }
  47682. },
  47683. enumerable: true,
  47684. configurable: true
  47685. });
  47686. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47687. get: function () {
  47688. return this._autoRotationBehavior;
  47689. },
  47690. enumerable: true,
  47691. configurable: true
  47692. });
  47693. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47694. get: function () {
  47695. return this._autoRotationBehavior != null;
  47696. },
  47697. set: function (value) {
  47698. if (value === this.useAutoRotationBehavior) {
  47699. return;
  47700. }
  47701. if (value) {
  47702. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47703. this.addBehavior(this._autoRotationBehavior);
  47704. }
  47705. else if (this._autoRotationBehavior) {
  47706. this.removeBehavior(this._autoRotationBehavior);
  47707. this._autoRotationBehavior = null;
  47708. }
  47709. },
  47710. enumerable: true,
  47711. configurable: true
  47712. });
  47713. // Cache
  47714. ArcRotateCamera.prototype._initCache = function () {
  47715. _super.prototype._initCache.call(this);
  47716. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47717. this._cache.alpha = undefined;
  47718. this._cache.beta = undefined;
  47719. this._cache.radius = undefined;
  47720. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47721. };
  47722. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47723. if (!ignoreParentClass) {
  47724. _super.prototype._updateCache.call(this);
  47725. }
  47726. this._cache._target.copyFrom(this._getTargetPosition());
  47727. this._cache.alpha = this.alpha;
  47728. this._cache.beta = this.beta;
  47729. this._cache.radius = this.radius;
  47730. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47731. };
  47732. ArcRotateCamera.prototype._getTargetPosition = function () {
  47733. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47734. var pos = this._targetHost.getAbsolutePosition();
  47735. if (this._targetBoundingCenter) {
  47736. pos.addToRef(this._targetBoundingCenter, this._target);
  47737. }
  47738. else {
  47739. this._target.copyFrom(pos);
  47740. }
  47741. }
  47742. var lockedTargetPosition = this._getLockedTargetPosition();
  47743. if (lockedTargetPosition) {
  47744. return lockedTargetPosition;
  47745. }
  47746. return this._target;
  47747. };
  47748. ArcRotateCamera.prototype.storeState = function () {
  47749. this._storedAlpha = this.alpha;
  47750. this._storedBeta = this.beta;
  47751. this._storedRadius = this.radius;
  47752. this._storedTarget = this._getTargetPosition().clone();
  47753. return _super.prototype.storeState.call(this);
  47754. };
  47755. /**
  47756. * Restored camera state. You must call storeState() first
  47757. */
  47758. ArcRotateCamera.prototype._restoreStateValues = function () {
  47759. if (!_super.prototype._restoreStateValues.call(this)) {
  47760. return false;
  47761. }
  47762. this.alpha = this._storedAlpha;
  47763. this.beta = this._storedBeta;
  47764. this.radius = this._storedRadius;
  47765. this.setTarget(this._storedTarget.clone());
  47766. this.inertialAlphaOffset = 0;
  47767. this.inertialBetaOffset = 0;
  47768. this.inertialRadiusOffset = 0;
  47769. this.inertialPanningX = 0;
  47770. this.inertialPanningY = 0;
  47771. return true;
  47772. };
  47773. // Synchronized
  47774. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47775. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47776. return false;
  47777. return this._cache._target.equals(this._getTargetPosition())
  47778. && this._cache.alpha === this.alpha
  47779. && this._cache.beta === this.beta
  47780. && this._cache.radius === this.radius
  47781. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47782. };
  47783. // Methods
  47784. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47785. var _this = this;
  47786. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47787. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47788. this._useCtrlForPanning = useCtrlForPanning;
  47789. this._panningMouseButton = panningMouseButton;
  47790. this.inputs.attachElement(element, noPreventDefault);
  47791. this._reset = function () {
  47792. _this.inertialAlphaOffset = 0;
  47793. _this.inertialBetaOffset = 0;
  47794. _this.inertialRadiusOffset = 0;
  47795. _this.inertialPanningX = 0;
  47796. _this.inertialPanningY = 0;
  47797. };
  47798. };
  47799. ArcRotateCamera.prototype.detachControl = function (element) {
  47800. this.inputs.detachElement(element);
  47801. if (this._reset) {
  47802. this._reset();
  47803. }
  47804. };
  47805. ArcRotateCamera.prototype._checkInputs = function () {
  47806. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47807. if (this._collisionTriggered) {
  47808. return;
  47809. }
  47810. this.inputs.checkInputs();
  47811. // Inertia
  47812. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47813. var inertialAlphaOffset = this.inertialAlphaOffset;
  47814. if (this.beta <= 0)
  47815. inertialAlphaOffset *= -1;
  47816. if (this.getScene().useRightHandedSystem)
  47817. inertialAlphaOffset *= -1;
  47818. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47819. inertialAlphaOffset *= -1;
  47820. this.alpha += inertialAlphaOffset;
  47821. this.beta += this.inertialBetaOffset;
  47822. this.radius -= this.inertialRadiusOffset;
  47823. this.inertialAlphaOffset *= this.inertia;
  47824. this.inertialBetaOffset *= this.inertia;
  47825. this.inertialRadiusOffset *= this.inertia;
  47826. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47827. this.inertialAlphaOffset = 0;
  47828. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47829. this.inertialBetaOffset = 0;
  47830. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47831. this.inertialRadiusOffset = 0;
  47832. }
  47833. // Panning inertia
  47834. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47835. if (!this._localDirection) {
  47836. this._localDirection = BABYLON.Vector3.Zero();
  47837. this._transformedDirection = BABYLON.Vector3.Zero();
  47838. }
  47839. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47840. this._localDirection.multiplyInPlace(this.panningAxis);
  47841. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47842. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47843. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47844. if (!this.panningAxis.y) {
  47845. this._transformedDirection.y = 0;
  47846. }
  47847. if (!this._targetHost) {
  47848. if (this.panningDistanceLimit) {
  47849. this._transformedDirection.addInPlace(this._target);
  47850. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47851. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47852. this._target.copyFrom(this._transformedDirection);
  47853. }
  47854. }
  47855. else {
  47856. this._target.addInPlace(this._transformedDirection);
  47857. }
  47858. }
  47859. this.inertialPanningX *= this.panningInertia;
  47860. this.inertialPanningY *= this.panningInertia;
  47861. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47862. this.inertialPanningX = 0;
  47863. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47864. this.inertialPanningY = 0;
  47865. }
  47866. // Limits
  47867. this._checkLimits();
  47868. _super.prototype._checkInputs.call(this);
  47869. };
  47870. ArcRotateCamera.prototype._checkLimits = function () {
  47871. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47872. if (this.allowUpsideDown && this.beta > Math.PI) {
  47873. this.beta = this.beta - (2 * Math.PI);
  47874. }
  47875. }
  47876. else {
  47877. if (this.beta < this.lowerBetaLimit) {
  47878. this.beta = this.lowerBetaLimit;
  47879. }
  47880. }
  47881. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47882. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47883. this.beta = this.beta + (2 * Math.PI);
  47884. }
  47885. }
  47886. else {
  47887. if (this.beta > this.upperBetaLimit) {
  47888. this.beta = this.upperBetaLimit;
  47889. }
  47890. }
  47891. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47892. this.alpha = this.lowerAlphaLimit;
  47893. }
  47894. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47895. this.alpha = this.upperAlphaLimit;
  47896. }
  47897. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47898. this.radius = this.lowerRadiusLimit;
  47899. }
  47900. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47901. this.radius = this.upperRadiusLimit;
  47902. }
  47903. };
  47904. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47905. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47906. this.radius = this._computationVector.length();
  47907. if (this.radius === 0) {
  47908. this.radius = 0.0001; // Just to avoid division by zero
  47909. }
  47910. // Alpha
  47911. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47912. if (this._computationVector.z < 0) {
  47913. this.alpha = 2 * Math.PI - this.alpha;
  47914. }
  47915. // Beta
  47916. this.beta = Math.acos(this._computationVector.y / this.radius);
  47917. this._checkLimits();
  47918. };
  47919. ArcRotateCamera.prototype.setPosition = function (position) {
  47920. if (this.position.equals(position)) {
  47921. return;
  47922. }
  47923. this.position.copyFrom(position);
  47924. this.rebuildAnglesAndRadius();
  47925. };
  47926. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47927. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47928. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47929. if (target.getBoundingInfo) {
  47930. if (toBoundingCenter) {
  47931. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47932. }
  47933. else {
  47934. this._targetBoundingCenter = null;
  47935. }
  47936. this._targetHost = target;
  47937. this._target = this._getTargetPosition();
  47938. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47939. }
  47940. else {
  47941. var newTarget = target;
  47942. var currentTarget = this._getTargetPosition();
  47943. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47944. return;
  47945. }
  47946. this._targetHost = null;
  47947. this._target = newTarget;
  47948. this._targetBoundingCenter = null;
  47949. this.onMeshTargetChangedObservable.notifyObservers(null);
  47950. }
  47951. this.rebuildAnglesAndRadius();
  47952. };
  47953. ArcRotateCamera.prototype._getViewMatrix = function () {
  47954. // Compute
  47955. var cosa = Math.cos(this.alpha);
  47956. var sina = Math.sin(this.alpha);
  47957. var cosb = Math.cos(this.beta);
  47958. var sinb = Math.sin(this.beta);
  47959. if (sinb === 0) {
  47960. sinb = 0.0001;
  47961. }
  47962. var target = this._getTargetPosition();
  47963. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47964. target.addToRef(this._computationVector, this._newPosition);
  47965. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47966. if (!this._collider) {
  47967. this._collider = new BABYLON.Collider();
  47968. }
  47969. this._collider._radius = this.collisionRadius;
  47970. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47971. this._collisionTriggered = true;
  47972. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47973. }
  47974. else {
  47975. this.position.copyFrom(this._newPosition);
  47976. var up = this.upVector;
  47977. if (this.allowUpsideDown && sinb < 0) {
  47978. up = up.clone();
  47979. up = up.negate();
  47980. }
  47981. this._computeViewMatrix(this.position, target, up);
  47982. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47983. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47984. }
  47985. this._currentTarget = target;
  47986. return this._viewMatrix;
  47987. };
  47988. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47989. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47990. meshes = meshes || this.getScene().meshes;
  47991. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47992. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47993. this.radius = distance * this.zoomOnFactor;
  47994. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47995. };
  47996. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47997. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47998. var meshesOrMinMaxVector;
  47999. var distance;
  48000. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48001. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48002. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48003. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48004. }
  48005. else { //minMaxVector and distance
  48006. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48007. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48008. distance = minMaxVectorAndDistance.distance;
  48009. }
  48010. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48011. if (!doNotUpdateMaxZ) {
  48012. this.maxZ = distance * 2;
  48013. }
  48014. };
  48015. /**
  48016. * @override
  48017. * Override Camera.createRigCamera
  48018. */
  48019. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48020. var alphaShift = 0;
  48021. switch (this.cameraRigMode) {
  48022. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48023. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48024. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48025. case BABYLON.Camera.RIG_MODE_VR:
  48026. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48027. break;
  48028. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48029. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48030. break;
  48031. }
  48032. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48033. rigCam._cameraRigParams = {};
  48034. return rigCam;
  48035. };
  48036. /**
  48037. * @override
  48038. * Override Camera._updateRigCameras
  48039. */
  48040. ArcRotateCamera.prototype._updateRigCameras = function () {
  48041. var camLeft = this._rigCameras[0];
  48042. var camRight = this._rigCameras[1];
  48043. camLeft.beta = camRight.beta = this.beta;
  48044. camLeft.radius = camRight.radius = this.radius;
  48045. switch (this.cameraRigMode) {
  48046. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48047. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48048. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48049. case BABYLON.Camera.RIG_MODE_VR:
  48050. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48051. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48052. break;
  48053. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48054. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48055. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48056. break;
  48057. }
  48058. _super.prototype._updateRigCameras.call(this);
  48059. };
  48060. ArcRotateCamera.prototype.dispose = function () {
  48061. this.inputs.clear();
  48062. _super.prototype.dispose.call(this);
  48063. };
  48064. ArcRotateCamera.prototype.getClassName = function () {
  48065. return "ArcRotateCamera";
  48066. };
  48067. __decorate([
  48068. BABYLON.serialize()
  48069. ], ArcRotateCamera.prototype, "alpha", void 0);
  48070. __decorate([
  48071. BABYLON.serialize()
  48072. ], ArcRotateCamera.prototype, "beta", void 0);
  48073. __decorate([
  48074. BABYLON.serialize()
  48075. ], ArcRotateCamera.prototype, "radius", void 0);
  48076. __decorate([
  48077. BABYLON.serializeAsVector3("target")
  48078. ], ArcRotateCamera.prototype, "_target", void 0);
  48079. __decorate([
  48080. BABYLON.serialize()
  48081. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48082. __decorate([
  48083. BABYLON.serialize()
  48084. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48085. __decorate([
  48086. BABYLON.serialize()
  48087. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48088. __decorate([
  48089. BABYLON.serialize()
  48090. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48091. __decorate([
  48092. BABYLON.serialize()
  48093. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48094. __decorate([
  48095. BABYLON.serialize()
  48096. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48097. __decorate([
  48098. BABYLON.serialize()
  48099. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48100. __decorate([
  48101. BABYLON.serialize()
  48102. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48103. __decorate([
  48104. BABYLON.serialize()
  48105. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48106. __decorate([
  48107. BABYLON.serialize()
  48108. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48109. __decorate([
  48110. BABYLON.serialize()
  48111. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48112. __decorate([
  48113. BABYLON.serialize()
  48114. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48115. __decorate([
  48116. BABYLON.serialize()
  48117. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48118. __decorate([
  48119. BABYLON.serializeAsVector3()
  48120. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48121. __decorate([
  48122. BABYLON.serialize()
  48123. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48124. __decorate([
  48125. BABYLON.serialize()
  48126. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48127. __decorate([
  48128. BABYLON.serialize()
  48129. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48130. return ArcRotateCamera;
  48131. }(BABYLON.TargetCamera));
  48132. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48133. })(BABYLON || (BABYLON = {}));
  48134. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48135. var BABYLON;
  48136. (function (BABYLON) {
  48137. /**
  48138. * The HemisphericLight simulates the ambient environment light,
  48139. * so the passed direction is the light reflection direction, not the incoming direction.
  48140. */
  48141. var HemisphericLight = /** @class */ (function (_super) {
  48142. __extends(HemisphericLight, _super);
  48143. /**
  48144. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48145. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48146. * The HemisphericLight can't cast shadows.
  48147. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48148. * @param name The friendly name of the light
  48149. * @param direction The direction of the light reflection
  48150. * @param scene The scene the light belongs to
  48151. */
  48152. function HemisphericLight(name, direction, scene) {
  48153. var _this = _super.call(this, name, scene) || this;
  48154. /**
  48155. * The groundColor is the light in the opposite direction to the one specified during creation.
  48156. * 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.
  48157. */
  48158. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48159. _this.direction = direction || BABYLON.Vector3.Up();
  48160. return _this;
  48161. }
  48162. HemisphericLight.prototype._buildUniformLayout = function () {
  48163. this._uniformBuffer.addUniform("vLightData", 4);
  48164. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48165. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48166. this._uniformBuffer.addUniform("vLightGround", 3);
  48167. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48168. this._uniformBuffer.addUniform("depthValues", 2);
  48169. this._uniformBuffer.create();
  48170. };
  48171. /**
  48172. * Returns the string "HemisphericLight".
  48173. * @return The class name
  48174. */
  48175. HemisphericLight.prototype.getClassName = function () {
  48176. return "HemisphericLight";
  48177. };
  48178. /**
  48179. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48180. * Returns the updated direction.
  48181. * @param target The target the direction should point to
  48182. * @return The computed direction
  48183. */
  48184. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48185. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48186. return this.direction;
  48187. };
  48188. /**
  48189. * Returns the shadow generator associated to the light.
  48190. * @returns Always null for hemispheric lights because it does not support shadows.
  48191. */
  48192. HemisphericLight.prototype.getShadowGenerator = function () {
  48193. return null;
  48194. };
  48195. /**
  48196. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48197. * @param effect The effect to update
  48198. * @param lightIndex The index of the light in the effect to update
  48199. * @returns The hemispheric light
  48200. */
  48201. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48202. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48203. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48204. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48205. return this;
  48206. };
  48207. /**
  48208. * @hidden internal use only.
  48209. */
  48210. HemisphericLight.prototype._getWorldMatrix = function () {
  48211. if (!this._worldMatrix) {
  48212. this._worldMatrix = BABYLON.Matrix.Identity();
  48213. }
  48214. return this._worldMatrix;
  48215. };
  48216. /**
  48217. * Returns the integer 3.
  48218. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48219. */
  48220. HemisphericLight.prototype.getTypeID = function () {
  48221. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48222. };
  48223. __decorate([
  48224. BABYLON.serializeAsColor3()
  48225. ], HemisphericLight.prototype, "groundColor", void 0);
  48226. __decorate([
  48227. BABYLON.serializeAsVector3()
  48228. ], HemisphericLight.prototype, "direction", void 0);
  48229. return HemisphericLight;
  48230. }(BABYLON.Light));
  48231. BABYLON.HemisphericLight = HemisphericLight;
  48232. })(BABYLON || (BABYLON = {}));
  48233. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48234. var BABYLON;
  48235. (function (BABYLON) {
  48236. /**
  48237. * Base implementation IShadowLight
  48238. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48239. */
  48240. var ShadowLight = /** @class */ (function (_super) {
  48241. __extends(ShadowLight, _super);
  48242. function ShadowLight() {
  48243. var _this = _super !== null && _super.apply(this, arguments) || this;
  48244. _this._needProjectionMatrixCompute = true;
  48245. return _this;
  48246. }
  48247. ShadowLight.prototype._setPosition = function (value) {
  48248. this._position = value;
  48249. };
  48250. Object.defineProperty(ShadowLight.prototype, "position", {
  48251. /**
  48252. * Sets the position the shadow will be casted from. Also use as the light position for both
  48253. * point and spot lights.
  48254. */
  48255. get: function () {
  48256. return this._position;
  48257. },
  48258. /**
  48259. * Sets the position the shadow will be casted from. Also use as the light position for both
  48260. * point and spot lights.
  48261. */
  48262. set: function (value) {
  48263. this._setPosition(value);
  48264. },
  48265. enumerable: true,
  48266. configurable: true
  48267. });
  48268. ShadowLight.prototype._setDirection = function (value) {
  48269. this._direction = value;
  48270. };
  48271. Object.defineProperty(ShadowLight.prototype, "direction", {
  48272. /**
  48273. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48274. * Also use as the light direction on spot and directional lights.
  48275. */
  48276. get: function () {
  48277. return this._direction;
  48278. },
  48279. /**
  48280. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48281. * Also use as the light direction on spot and directional lights.
  48282. */
  48283. set: function (value) {
  48284. this._setDirection(value);
  48285. },
  48286. enumerable: true,
  48287. configurable: true
  48288. });
  48289. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48290. /**
  48291. * Gets the shadow projection clipping minimum z value.
  48292. */
  48293. get: function () {
  48294. return this._shadowMinZ;
  48295. },
  48296. /**
  48297. * Sets the shadow projection clipping minimum z value.
  48298. */
  48299. set: function (value) {
  48300. this._shadowMinZ = value;
  48301. this.forceProjectionMatrixCompute();
  48302. },
  48303. enumerable: true,
  48304. configurable: true
  48305. });
  48306. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48307. /**
  48308. * Sets the shadow projection clipping maximum z value.
  48309. */
  48310. get: function () {
  48311. return this._shadowMaxZ;
  48312. },
  48313. /**
  48314. * Gets the shadow projection clipping maximum z value.
  48315. */
  48316. set: function (value) {
  48317. this._shadowMaxZ = value;
  48318. this.forceProjectionMatrixCompute();
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. /**
  48324. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48325. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48326. */
  48327. ShadowLight.prototype.computeTransformedInformation = function () {
  48328. if (this.parent && this.parent.getWorldMatrix) {
  48329. if (!this.transformedPosition) {
  48330. this.transformedPosition = BABYLON.Vector3.Zero();
  48331. }
  48332. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48333. // In case the direction is present.
  48334. if (this.direction) {
  48335. if (!this.transformedDirection) {
  48336. this.transformedDirection = BABYLON.Vector3.Zero();
  48337. }
  48338. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48339. }
  48340. return true;
  48341. }
  48342. return false;
  48343. };
  48344. /**
  48345. * Return the depth scale used for the shadow map.
  48346. * @returns the depth scale.
  48347. */
  48348. ShadowLight.prototype.getDepthScale = function () {
  48349. return 50.0;
  48350. };
  48351. /**
  48352. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48353. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48354. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48355. */
  48356. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48357. return this.transformedDirection ? this.transformedDirection : this.direction;
  48358. };
  48359. /**
  48360. * Returns the ShadowLight absolute position in the World.
  48361. * @returns the position vector in world space
  48362. */
  48363. ShadowLight.prototype.getAbsolutePosition = function () {
  48364. return this.transformedPosition ? this.transformedPosition : this.position;
  48365. };
  48366. /**
  48367. * Sets the ShadowLight direction toward the passed target.
  48368. * @param target The point tot target in local space
  48369. * @returns the updated ShadowLight direction
  48370. */
  48371. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48372. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48373. return this.direction;
  48374. };
  48375. /**
  48376. * Returns the light rotation in euler definition.
  48377. * @returns the x y z rotation in local space.
  48378. */
  48379. ShadowLight.prototype.getRotation = function () {
  48380. this.direction.normalize();
  48381. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48382. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48383. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48384. };
  48385. /**
  48386. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48387. * @returns true if a cube texture needs to be use
  48388. */
  48389. ShadowLight.prototype.needCube = function () {
  48390. return false;
  48391. };
  48392. /**
  48393. * Detects if the projection matrix requires to be recomputed this frame.
  48394. * @returns true if it requires to be recomputed otherwise, false.
  48395. */
  48396. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48397. return this._needProjectionMatrixCompute;
  48398. };
  48399. /**
  48400. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48401. */
  48402. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48403. this._needProjectionMatrixCompute = true;
  48404. };
  48405. /**
  48406. * Get the world matrix of the sahdow lights.
  48407. * @hidden Internal Use Only
  48408. */
  48409. ShadowLight.prototype._getWorldMatrix = function () {
  48410. if (!this._worldMatrix) {
  48411. this._worldMatrix = BABYLON.Matrix.Identity();
  48412. }
  48413. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48414. return this._worldMatrix;
  48415. };
  48416. /**
  48417. * Gets the minZ used for shadow according to both the scene and the light.
  48418. * @param activeCamera The camera we are returning the min for
  48419. * @returns the depth min z
  48420. */
  48421. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48422. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48423. };
  48424. /**
  48425. * Gets the maxZ used for shadow according to both the scene and the light.
  48426. * @param activeCamera The camera we are returning the max for
  48427. * @returns the depth max z
  48428. */
  48429. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48430. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48431. };
  48432. /**
  48433. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48434. * @param matrix The materix to updated with the projection information
  48435. * @param viewMatrix The transform matrix of the light
  48436. * @param renderList The list of mesh to render in the map
  48437. * @returns The current light
  48438. */
  48439. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48440. if (this.customProjectionMatrixBuilder) {
  48441. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48442. }
  48443. else {
  48444. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48445. }
  48446. return this;
  48447. };
  48448. __decorate([
  48449. BABYLON.serializeAsVector3()
  48450. ], ShadowLight.prototype, "position", null);
  48451. __decorate([
  48452. BABYLON.serializeAsVector3()
  48453. ], ShadowLight.prototype, "direction", null);
  48454. __decorate([
  48455. BABYLON.serialize()
  48456. ], ShadowLight.prototype, "shadowMinZ", null);
  48457. __decorate([
  48458. BABYLON.serialize()
  48459. ], ShadowLight.prototype, "shadowMaxZ", null);
  48460. return ShadowLight;
  48461. }(BABYLON.Light));
  48462. BABYLON.ShadowLight = ShadowLight;
  48463. })(BABYLON || (BABYLON = {}));
  48464. //# sourceMappingURL=babylon.shadowLight.js.map
  48465. var BABYLON;
  48466. (function (BABYLON) {
  48467. /**
  48468. * A point light is a light defined by an unique point in world space.
  48469. * The light is emitted in every direction from this point.
  48470. * A good example of a point light is a standard light bulb.
  48471. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48472. */
  48473. var PointLight = /** @class */ (function (_super) {
  48474. __extends(PointLight, _super);
  48475. /**
  48476. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48477. * A PointLight emits the light in every direction.
  48478. * It can cast shadows.
  48479. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48480. * ```javascript
  48481. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48482. * ```
  48483. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48484. * @param name The light friendly name
  48485. * @param position The position of the point light in the scene
  48486. * @param scene The scene the lights belongs to
  48487. */
  48488. function PointLight(name, position, scene) {
  48489. var _this = _super.call(this, name, scene) || this;
  48490. _this._shadowAngle = Math.PI / 2;
  48491. _this.position = position;
  48492. return _this;
  48493. }
  48494. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48495. /**
  48496. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48497. * This specifies what angle the shadow will use to be created.
  48498. *
  48499. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48500. */
  48501. get: function () {
  48502. return this._shadowAngle;
  48503. },
  48504. /**
  48505. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48506. * This specifies what angle the shadow will use to be created.
  48507. *
  48508. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48509. */
  48510. set: function (value) {
  48511. this._shadowAngle = value;
  48512. this.forceProjectionMatrixCompute();
  48513. },
  48514. enumerable: true,
  48515. configurable: true
  48516. });
  48517. Object.defineProperty(PointLight.prototype, "direction", {
  48518. /**
  48519. * Gets the direction if it has been set.
  48520. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48521. */
  48522. get: function () {
  48523. return this._direction;
  48524. },
  48525. /**
  48526. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48527. */
  48528. set: function (value) {
  48529. var previousNeedCube = this.needCube();
  48530. this._direction = value;
  48531. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48532. this._shadowGenerator.recreateShadowMap();
  48533. }
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. /**
  48539. * Returns the string "PointLight"
  48540. * @returns the class name
  48541. */
  48542. PointLight.prototype.getClassName = function () {
  48543. return "PointLight";
  48544. };
  48545. /**
  48546. * Returns the integer 0.
  48547. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48548. */
  48549. PointLight.prototype.getTypeID = function () {
  48550. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48551. };
  48552. /**
  48553. * Specifies wether or not the shadowmap should be a cube texture.
  48554. * @returns true if the shadowmap needs to be a cube texture.
  48555. */
  48556. PointLight.prototype.needCube = function () {
  48557. return !this.direction;
  48558. };
  48559. /**
  48560. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48561. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48562. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48563. */
  48564. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48565. if (this.direction) {
  48566. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48567. }
  48568. else {
  48569. switch (faceIndex) {
  48570. case 0:
  48571. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48572. case 1:
  48573. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48574. case 2:
  48575. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48576. case 3:
  48577. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48578. case 4:
  48579. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48580. case 5:
  48581. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48582. }
  48583. }
  48584. return BABYLON.Vector3.Zero();
  48585. };
  48586. /**
  48587. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48588. * - fov = PI / 2
  48589. * - aspect ratio : 1.0
  48590. * - z-near and far equal to the active camera minZ and maxZ.
  48591. * Returns the PointLight.
  48592. */
  48593. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48594. var activeCamera = this.getScene().activeCamera;
  48595. if (!activeCamera) {
  48596. return;
  48597. }
  48598. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48599. };
  48600. PointLight.prototype._buildUniformLayout = function () {
  48601. this._uniformBuffer.addUniform("vLightData", 4);
  48602. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48603. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48604. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48605. this._uniformBuffer.addUniform("depthValues", 2);
  48606. this._uniformBuffer.create();
  48607. };
  48608. /**
  48609. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48610. * @param effect The effect to update
  48611. * @param lightIndex The index of the light in the effect to update
  48612. * @returns The point light
  48613. */
  48614. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48615. if (this.computeTransformedInformation()) {
  48616. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48617. return this;
  48618. }
  48619. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48620. return this;
  48621. };
  48622. __decorate([
  48623. BABYLON.serialize()
  48624. ], PointLight.prototype, "shadowAngle", null);
  48625. return PointLight;
  48626. }(BABYLON.ShadowLight));
  48627. BABYLON.PointLight = PointLight;
  48628. })(BABYLON || (BABYLON = {}));
  48629. //# sourceMappingURL=babylon.pointLight.js.map
  48630. var BABYLON;
  48631. (function (BABYLON) {
  48632. /**
  48633. * A directional light is defined by a direction (what a surprise!).
  48634. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48635. * 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.
  48636. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48637. */
  48638. var DirectionalLight = /** @class */ (function (_super) {
  48639. __extends(DirectionalLight, _super);
  48640. /**
  48641. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48642. * The directional light is emitted from everywhere in the given direction.
  48643. * It can cast shawdows.
  48644. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48645. * @param name The friendly name of the light
  48646. * @param direction The direction of the light
  48647. * @param scene The scene the light belongs to
  48648. */
  48649. function DirectionalLight(name, direction, scene) {
  48650. var _this = _super.call(this, name, scene) || this;
  48651. _this._shadowFrustumSize = 0;
  48652. _this._shadowOrthoScale = 0.1;
  48653. /**
  48654. * Automatically compute the projection matrix to best fit (including all the casters)
  48655. * on each frame.
  48656. */
  48657. _this.autoUpdateExtends = true;
  48658. // Cache
  48659. _this._orthoLeft = Number.MAX_VALUE;
  48660. _this._orthoRight = Number.MIN_VALUE;
  48661. _this._orthoTop = Number.MIN_VALUE;
  48662. _this._orthoBottom = Number.MAX_VALUE;
  48663. _this.position = direction.scale(-1.0);
  48664. _this.direction = direction;
  48665. return _this;
  48666. }
  48667. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48668. /**
  48669. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48670. */
  48671. get: function () {
  48672. return this._shadowFrustumSize;
  48673. },
  48674. /**
  48675. * Specifies a fix frustum size for the shadow generation.
  48676. */
  48677. set: function (value) {
  48678. this._shadowFrustumSize = value;
  48679. this.forceProjectionMatrixCompute();
  48680. },
  48681. enumerable: true,
  48682. configurable: true
  48683. });
  48684. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48685. /**
  48686. * Gets the shadow projection scale against the optimal computed one.
  48687. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48688. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48689. */
  48690. get: function () {
  48691. return this._shadowOrthoScale;
  48692. },
  48693. /**
  48694. * Sets the shadow projection scale against the optimal computed one.
  48695. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48696. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48697. */
  48698. set: function (value) {
  48699. this._shadowOrthoScale = value;
  48700. this.forceProjectionMatrixCompute();
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. /**
  48706. * Returns the string "DirectionalLight".
  48707. * @return The class name
  48708. */
  48709. DirectionalLight.prototype.getClassName = function () {
  48710. return "DirectionalLight";
  48711. };
  48712. /**
  48713. * Returns the integer 1.
  48714. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48715. */
  48716. DirectionalLight.prototype.getTypeID = function () {
  48717. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48718. };
  48719. /**
  48720. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48721. * Returns the DirectionalLight Shadow projection matrix.
  48722. */
  48723. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48724. if (this.shadowFrustumSize > 0) {
  48725. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48726. }
  48727. else {
  48728. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48729. }
  48730. };
  48731. /**
  48732. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48733. * Returns the DirectionalLight Shadow projection matrix.
  48734. */
  48735. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48736. var activeCamera = this.getScene().activeCamera;
  48737. if (!activeCamera) {
  48738. return;
  48739. }
  48740. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48741. };
  48742. /**
  48743. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48744. * Returns the DirectionalLight Shadow projection matrix.
  48745. */
  48746. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48747. var activeCamera = this.getScene().activeCamera;
  48748. if (!activeCamera) {
  48749. return;
  48750. }
  48751. // Check extends
  48752. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48753. var tempVector3 = BABYLON.Vector3.Zero();
  48754. this._orthoLeft = Number.MAX_VALUE;
  48755. this._orthoRight = Number.MIN_VALUE;
  48756. this._orthoTop = Number.MIN_VALUE;
  48757. this._orthoBottom = Number.MAX_VALUE;
  48758. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48759. var mesh = renderList[meshIndex];
  48760. if (!mesh) {
  48761. continue;
  48762. }
  48763. var boundingInfo = mesh.getBoundingInfo();
  48764. var boundingBox = boundingInfo.boundingBox;
  48765. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48766. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48767. if (tempVector3.x < this._orthoLeft)
  48768. this._orthoLeft = tempVector3.x;
  48769. if (tempVector3.y < this._orthoBottom)
  48770. this._orthoBottom = tempVector3.y;
  48771. if (tempVector3.x > this._orthoRight)
  48772. this._orthoRight = tempVector3.x;
  48773. if (tempVector3.y > this._orthoTop)
  48774. this._orthoTop = tempVector3.y;
  48775. }
  48776. }
  48777. }
  48778. var xOffset = this._orthoRight - this._orthoLeft;
  48779. var yOffset = this._orthoTop - this._orthoBottom;
  48780. 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);
  48781. };
  48782. DirectionalLight.prototype._buildUniformLayout = function () {
  48783. this._uniformBuffer.addUniform("vLightData", 4);
  48784. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48785. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48786. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48787. this._uniformBuffer.addUniform("depthValues", 2);
  48788. this._uniformBuffer.create();
  48789. };
  48790. /**
  48791. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48792. * @param effect The effect to update
  48793. * @param lightIndex The index of the light in the effect to update
  48794. * @returns The directional light
  48795. */
  48796. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48797. if (this.computeTransformedInformation()) {
  48798. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48799. return this;
  48800. }
  48801. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48802. return this;
  48803. };
  48804. /**
  48805. * Gets the minZ used for shadow according to both the scene and the light.
  48806. *
  48807. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48808. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48809. * @param activeCamera The camera we are returning the min for
  48810. * @returns the depth min z
  48811. */
  48812. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48813. return 1;
  48814. };
  48815. /**
  48816. * Gets the maxZ used for shadow according to both the scene and the light.
  48817. *
  48818. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48819. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48820. * @param activeCamera The camera we are returning the max for
  48821. * @returns the depth max z
  48822. */
  48823. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48824. return 1;
  48825. };
  48826. __decorate([
  48827. BABYLON.serialize()
  48828. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48829. __decorate([
  48830. BABYLON.serialize()
  48831. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48832. __decorate([
  48833. BABYLON.serialize()
  48834. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48835. return DirectionalLight;
  48836. }(BABYLON.ShadowLight));
  48837. BABYLON.DirectionalLight = DirectionalLight;
  48838. })(BABYLON || (BABYLON = {}));
  48839. //# sourceMappingURL=babylon.directionalLight.js.map
  48840. var BABYLON;
  48841. (function (BABYLON) {
  48842. /**
  48843. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48844. * These values define a cone of light starting from the position, emitting toward the direction.
  48845. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48846. * and the exponent defines the speed of the decay of the light with distance (reach).
  48847. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48848. */
  48849. var SpotLight = /** @class */ (function (_super) {
  48850. __extends(SpotLight, _super);
  48851. /**
  48852. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48853. * It can cast shadows.
  48854. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48855. * @param name The light friendly name
  48856. * @param position The position of the spot light in the scene
  48857. * @param direction The direction of the light in the scene
  48858. * @param angle The cone angle of the light in Radians
  48859. * @param exponent The light decay speed with the distance from the emission spot
  48860. * @param scene The scene the lights belongs to
  48861. */
  48862. function SpotLight(name, position, direction, angle, exponent, scene) {
  48863. var _this = _super.call(this, name, scene) || this;
  48864. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48865. _this._projectionTextureLightNear = 1e-6;
  48866. _this._projectionTextureLightFar = 1000.0;
  48867. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48868. _this._projectionTextureViewLightDirty = true;
  48869. _this._projectionTextureProjectionLightDirty = true;
  48870. _this._projectionTextureDirty = true;
  48871. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48872. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48873. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48874. _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);
  48875. _this.position = position;
  48876. _this.direction = direction;
  48877. _this.angle = angle;
  48878. _this.exponent = exponent;
  48879. return _this;
  48880. }
  48881. Object.defineProperty(SpotLight.prototype, "angle", {
  48882. /**
  48883. * Gets the cone angle of the spot light in Radians.
  48884. */
  48885. get: function () {
  48886. return this._angle;
  48887. },
  48888. /**
  48889. * Sets the cone angle of the spot light in Radians.
  48890. */
  48891. set: function (value) {
  48892. this._angle = value;
  48893. this._projectionTextureProjectionLightDirty = true;
  48894. this.forceProjectionMatrixCompute();
  48895. },
  48896. enumerable: true,
  48897. configurable: true
  48898. });
  48899. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48900. /**
  48901. * Allows scaling the angle of the light for shadow generation only.
  48902. */
  48903. get: function () {
  48904. return this._shadowAngleScale;
  48905. },
  48906. /**
  48907. * Allows scaling the angle of the light for shadow generation only.
  48908. */
  48909. set: function (value) {
  48910. this._shadowAngleScale = value;
  48911. this.forceProjectionMatrixCompute();
  48912. },
  48913. enumerable: true,
  48914. configurable: true
  48915. });
  48916. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48917. /**
  48918. * Allows reading the projecton texture
  48919. */
  48920. get: function () {
  48921. return this._projectionTextureMatrix;
  48922. },
  48923. enumerable: true,
  48924. configurable: true
  48925. });
  48926. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48927. /**
  48928. * Gets the near clip of the Spotlight for texture projection.
  48929. */
  48930. get: function () {
  48931. return this._projectionTextureLightNear;
  48932. },
  48933. /**
  48934. * Sets the near clip of the Spotlight for texture projection.
  48935. */
  48936. set: function (value) {
  48937. this._projectionTextureLightNear = value;
  48938. this._projectionTextureProjectionLightDirty = true;
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48944. /**
  48945. * Gets the far clip of the Spotlight for texture projection.
  48946. */
  48947. get: function () {
  48948. return this._projectionTextureLightFar;
  48949. },
  48950. /**
  48951. * Sets the far clip of the Spotlight for texture projection.
  48952. */
  48953. set: function (value) {
  48954. this._projectionTextureLightFar = value;
  48955. this._projectionTextureProjectionLightDirty = true;
  48956. },
  48957. enumerable: true,
  48958. configurable: true
  48959. });
  48960. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48961. /**
  48962. * Gets the Up vector of the Spotlight for texture projection.
  48963. */
  48964. get: function () {
  48965. return this._projectionTextureUpDirection;
  48966. },
  48967. /**
  48968. * Sets the Up vector of the Spotlight for texture projection.
  48969. */
  48970. set: function (value) {
  48971. this._projectionTextureUpDirection = value;
  48972. this._projectionTextureProjectionLightDirty = true;
  48973. },
  48974. enumerable: true,
  48975. configurable: true
  48976. });
  48977. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48978. /**
  48979. * Gets the projection texture of the light.
  48980. */
  48981. get: function () {
  48982. return this._projectionTexture;
  48983. },
  48984. /**
  48985. * Sets the projection texture of the light.
  48986. */
  48987. set: function (value) {
  48988. this._projectionTexture = value;
  48989. this._projectionTextureDirty = true;
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. /**
  48995. * Returns the string "SpotLight".
  48996. * @returns the class name
  48997. */
  48998. SpotLight.prototype.getClassName = function () {
  48999. return "SpotLight";
  49000. };
  49001. /**
  49002. * Returns the integer 2.
  49003. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49004. */
  49005. SpotLight.prototype.getTypeID = function () {
  49006. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49007. };
  49008. /**
  49009. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49010. */
  49011. SpotLight.prototype._setDirection = function (value) {
  49012. _super.prototype._setDirection.call(this, value);
  49013. this._projectionTextureViewLightDirty = true;
  49014. };
  49015. /**
  49016. * Overrides the position setter to recompute the projection texture view light Matrix.
  49017. */
  49018. SpotLight.prototype._setPosition = function (value) {
  49019. _super.prototype._setPosition.call(this, value);
  49020. this._projectionTextureViewLightDirty = true;
  49021. };
  49022. /**
  49023. * 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.
  49024. * Returns the SpotLight.
  49025. */
  49026. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49027. var activeCamera = this.getScene().activeCamera;
  49028. if (!activeCamera) {
  49029. return;
  49030. }
  49031. this._shadowAngleScale = this._shadowAngleScale || 1;
  49032. var angle = this._shadowAngleScale * this._angle;
  49033. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49034. };
  49035. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49036. this._projectionTextureViewLightDirty = false;
  49037. this._projectionTextureDirty = true;
  49038. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49039. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49040. };
  49041. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49042. this._projectionTextureProjectionLightDirty = false;
  49043. this._projectionTextureDirty = true;
  49044. var light_far = this.projectionTextureLightFar;
  49045. var light_near = this.projectionTextureLightNear;
  49046. var P = light_far / (light_far - light_near);
  49047. var Q = -P * light_near;
  49048. var S = 1.0 / Math.tan(this._angle / 2.0);
  49049. var A = 1.0;
  49050. 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);
  49051. };
  49052. /**
  49053. * Main function for light texture projection matrix computing.
  49054. */
  49055. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49056. this._projectionTextureDirty = false;
  49057. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49058. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49059. };
  49060. SpotLight.prototype._buildUniformLayout = function () {
  49061. this._uniformBuffer.addUniform("vLightData", 4);
  49062. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49063. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49064. this._uniformBuffer.addUniform("vLightDirection", 3);
  49065. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49066. this._uniformBuffer.addUniform("depthValues", 2);
  49067. this._uniformBuffer.create();
  49068. };
  49069. /**
  49070. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49071. * @param effect The effect to update
  49072. * @param lightIndex The index of the light in the effect to update
  49073. * @returns The spot light
  49074. */
  49075. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49076. var normalizeDirection;
  49077. if (this.computeTransformedInformation()) {
  49078. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49079. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49080. }
  49081. else {
  49082. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49083. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49084. }
  49085. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49086. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49087. if (this._projectionTextureViewLightDirty) {
  49088. this._computeProjectionTextureViewLightMatrix();
  49089. }
  49090. if (this._projectionTextureProjectionLightDirty) {
  49091. this._computeProjectionTextureProjectionLightMatrix();
  49092. }
  49093. if (this._projectionTextureDirty) {
  49094. this._computeProjectionTextureMatrix();
  49095. }
  49096. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49097. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49098. }
  49099. return this;
  49100. };
  49101. /**
  49102. * Disposes the light and the associated resources.
  49103. */
  49104. SpotLight.prototype.dispose = function () {
  49105. _super.prototype.dispose.call(this);
  49106. if (this._projectionTexture) {
  49107. this._projectionTexture.dispose();
  49108. }
  49109. };
  49110. __decorate([
  49111. BABYLON.serialize()
  49112. ], SpotLight.prototype, "angle", null);
  49113. __decorate([
  49114. BABYLON.serialize()
  49115. ], SpotLight.prototype, "shadowAngleScale", null);
  49116. __decorate([
  49117. BABYLON.serialize()
  49118. ], SpotLight.prototype, "exponent", void 0);
  49119. __decorate([
  49120. BABYLON.serialize()
  49121. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49122. __decorate([
  49123. BABYLON.serialize()
  49124. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49125. __decorate([
  49126. BABYLON.serialize()
  49127. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49128. __decorate([
  49129. BABYLON.serializeAsTexture("projectedLightTexture")
  49130. ], SpotLight.prototype, "_projectionTexture", void 0);
  49131. return SpotLight;
  49132. }(BABYLON.ShadowLight));
  49133. BABYLON.SpotLight = SpotLight;
  49134. })(BABYLON || (BABYLON = {}));
  49135. //# sourceMappingURL=babylon.spotLight.js.map
  49136. var BABYLON;
  49137. (function (BABYLON) {
  49138. /**
  49139. * Class used to override all child animations of a given target
  49140. */
  49141. var AnimationPropertiesOverride = /** @class */ (function () {
  49142. function AnimationPropertiesOverride() {
  49143. /**
  49144. * Gets or sets a value indicating if animation blending must be used
  49145. */
  49146. this.enableBlending = false;
  49147. /**
  49148. * Gets or sets the blending speed to use when enableBlending is true
  49149. */
  49150. this.blendingSpeed = 0.01;
  49151. /**
  49152. * Gets or sets the default loop mode to use
  49153. */
  49154. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49155. }
  49156. return AnimationPropertiesOverride;
  49157. }());
  49158. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49159. })(BABYLON || (BABYLON = {}));
  49160. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49161. var BABYLON;
  49162. (function (BABYLON) {
  49163. /**
  49164. * Represents the range of an animation
  49165. */
  49166. var AnimationRange = /** @class */ (function () {
  49167. /**
  49168. * Initializes the range of an animation
  49169. * @param name The name of the animation range
  49170. * @param from The starting frame of the animation
  49171. * @param to The ending frame of the animation
  49172. */
  49173. function AnimationRange(
  49174. /**The name of the animation range**/
  49175. name,
  49176. /**The starting frame of the animation */
  49177. from,
  49178. /**The ending frame of the animation*/
  49179. to) {
  49180. this.name = name;
  49181. this.from = from;
  49182. this.to = to;
  49183. }
  49184. /**
  49185. * Makes a copy of the animation range
  49186. * @returns A copy of the animation range
  49187. */
  49188. AnimationRange.prototype.clone = function () {
  49189. return new AnimationRange(this.name, this.from, this.to);
  49190. };
  49191. return AnimationRange;
  49192. }());
  49193. BABYLON.AnimationRange = AnimationRange;
  49194. /**
  49195. * Composed of a frame, and an action function
  49196. */
  49197. var AnimationEvent = /** @class */ (function () {
  49198. /**
  49199. * Initializes the animation event
  49200. * @param frame The frame for which the event is triggered
  49201. * @param action The event to perform when triggered
  49202. * @param onlyOnce Specifies if the event should be triggered only once
  49203. */
  49204. function AnimationEvent(
  49205. /** The frame for which the event is triggered **/
  49206. frame,
  49207. /** The event to perform when triggered **/
  49208. action,
  49209. /** Specifies if the event should be triggered only once**/
  49210. onlyOnce) {
  49211. this.frame = frame;
  49212. this.action = action;
  49213. this.onlyOnce = onlyOnce;
  49214. /**
  49215. * Specifies if the animation event is done
  49216. */
  49217. this.isDone = false;
  49218. }
  49219. /** @hidden */
  49220. AnimationEvent.prototype._clone = function () {
  49221. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49222. };
  49223. return AnimationEvent;
  49224. }());
  49225. BABYLON.AnimationEvent = AnimationEvent;
  49226. /**
  49227. * A cursor which tracks a point on a path
  49228. */
  49229. var PathCursor = /** @class */ (function () {
  49230. /**
  49231. * Initializes the path cursor
  49232. * @param path The path to track
  49233. */
  49234. function PathCursor(path) {
  49235. this.path = path;
  49236. /**
  49237. * Stores path cursor callbacks for when an onchange event is triggered
  49238. */
  49239. this._onchange = new Array();
  49240. /**
  49241. * The value of the path cursor
  49242. */
  49243. this.value = 0;
  49244. /**
  49245. * The animation array of the path cursor
  49246. */
  49247. this.animations = new Array();
  49248. }
  49249. /**
  49250. * Gets the cursor point on the path
  49251. * @returns A point on the path cursor at the cursor location
  49252. */
  49253. PathCursor.prototype.getPoint = function () {
  49254. var point = this.path.getPointAtLengthPosition(this.value);
  49255. return new BABYLON.Vector3(point.x, 0, point.y);
  49256. };
  49257. /**
  49258. * Moves the cursor ahead by the step amount
  49259. * @param step The amount to move the cursor forward
  49260. * @returns This path cursor
  49261. */
  49262. PathCursor.prototype.moveAhead = function (step) {
  49263. if (step === void 0) { step = 0.002; }
  49264. this.move(step);
  49265. return this;
  49266. };
  49267. /**
  49268. * Moves the cursor behind by the step amount
  49269. * @param step The amount to move the cursor back
  49270. * @returns This path cursor
  49271. */
  49272. PathCursor.prototype.moveBack = function (step) {
  49273. if (step === void 0) { step = 0.002; }
  49274. this.move(-step);
  49275. return this;
  49276. };
  49277. /**
  49278. * Moves the cursor by the step amount
  49279. * If the step amount is greater than one, an exception is thrown
  49280. * @param step The amount to move the cursor
  49281. * @returns This path cursor
  49282. */
  49283. PathCursor.prototype.move = function (step) {
  49284. if (Math.abs(step) > 1) {
  49285. throw "step size should be less than 1.";
  49286. }
  49287. this.value += step;
  49288. this.ensureLimits();
  49289. this.raiseOnChange();
  49290. return this;
  49291. };
  49292. /**
  49293. * Ensures that the value is limited between zero and one
  49294. * @returns This path cursor
  49295. */
  49296. PathCursor.prototype.ensureLimits = function () {
  49297. while (this.value > 1) {
  49298. this.value -= 1;
  49299. }
  49300. while (this.value < 0) {
  49301. this.value += 1;
  49302. }
  49303. return this;
  49304. };
  49305. /**
  49306. * Runs onchange callbacks on change (used by the animation engine)
  49307. * @returns This path cursor
  49308. */
  49309. PathCursor.prototype.raiseOnChange = function () {
  49310. var _this = this;
  49311. this._onchange.forEach(function (f) { return f(_this); });
  49312. return this;
  49313. };
  49314. /**
  49315. * Executes a function on change
  49316. * @param f A path cursor onchange callback
  49317. * @returns This path cursor
  49318. */
  49319. PathCursor.prototype.onchange = function (f) {
  49320. this._onchange.push(f);
  49321. return this;
  49322. };
  49323. return PathCursor;
  49324. }());
  49325. BABYLON.PathCursor = PathCursor;
  49326. /**
  49327. * Enum for the animation key frame interpolation type
  49328. */
  49329. var AnimationKeyInterpolation;
  49330. (function (AnimationKeyInterpolation) {
  49331. /**
  49332. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49333. */
  49334. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49335. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49336. /**
  49337. * Class used to store any kind of animation
  49338. */
  49339. var Animation = /** @class */ (function () {
  49340. /**
  49341. * Initializes the animation
  49342. * @param name Name of the animation
  49343. * @param targetProperty Property to animate
  49344. * @param framePerSecond The frames per second of the animation
  49345. * @param dataType The data type of the animation
  49346. * @param loopMode The loop mode of the animation
  49347. * @param enableBlendings Specifies if blending should be enabled
  49348. */
  49349. function Animation(
  49350. /**Name of the animation */
  49351. name,
  49352. /**Property to animate */
  49353. targetProperty,
  49354. /**The frames per second of the animation */
  49355. framePerSecond,
  49356. /**The data type of the animation */
  49357. dataType,
  49358. /**The loop mode of the animation */
  49359. loopMode,
  49360. /**Specifies if blending should be enabled */
  49361. enableBlending) {
  49362. this.name = name;
  49363. this.targetProperty = targetProperty;
  49364. this.framePerSecond = framePerSecond;
  49365. this.dataType = dataType;
  49366. this.loopMode = loopMode;
  49367. this.enableBlending = enableBlending;
  49368. /**
  49369. * @hidden Internal use only
  49370. */
  49371. this._runtimeAnimations = new Array();
  49372. /**
  49373. * The set of event that will be linked to this animation
  49374. */
  49375. this._events = new Array();
  49376. /**
  49377. * Stores the blending speed of the animation
  49378. */
  49379. this.blendingSpeed = 0.01;
  49380. /**
  49381. * Stores the animation ranges for the animation
  49382. */
  49383. this._ranges = {};
  49384. this.targetPropertyPath = targetProperty.split(".");
  49385. this.dataType = dataType;
  49386. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49387. }
  49388. /**
  49389. * @hidden Internal use
  49390. */
  49391. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49392. var dataType = undefined;
  49393. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49394. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49395. }
  49396. else if (from instanceof BABYLON.Quaternion) {
  49397. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49398. }
  49399. else if (from instanceof BABYLON.Vector3) {
  49400. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49401. }
  49402. else if (from instanceof BABYLON.Vector2) {
  49403. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49404. }
  49405. else if (from instanceof BABYLON.Color3) {
  49406. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49407. }
  49408. else if (from instanceof BABYLON.Size) {
  49409. dataType = Animation.ANIMATIONTYPE_SIZE;
  49410. }
  49411. if (dataType == undefined) {
  49412. return null;
  49413. }
  49414. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49415. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49416. animation.setKeys(keys);
  49417. if (easingFunction !== undefined) {
  49418. animation.setEasingFunction(easingFunction);
  49419. }
  49420. return animation;
  49421. };
  49422. /**
  49423. * Sets up an animation
  49424. * @param property The property to animate
  49425. * @param animationType The animation type to apply
  49426. * @param framePerSecond The frames per second of the animation
  49427. * @param easingFunction The easing function used in the animation
  49428. * @returns The created animation
  49429. */
  49430. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49431. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49432. animation.setEasingFunction(easingFunction);
  49433. return animation;
  49434. };
  49435. /**
  49436. * Create and start an animation on a node
  49437. * @param name defines the name of the global animation that will be run on all nodes
  49438. * @param node defines the root node where the animation will take place
  49439. * @param targetProperty defines property to animate
  49440. * @param framePerSecond defines the number of frame per second yo use
  49441. * @param totalFrame defines the number of frames in total
  49442. * @param from defines the initial value
  49443. * @param to defines the final value
  49444. * @param loopMode defines which loop mode you want to use (off by default)
  49445. * @param easingFunction defines the easing function to use (linear by default)
  49446. * @param onAnimationEnd defines the callback to call when animation end
  49447. * @returns the animatable created for this animation
  49448. */
  49449. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49450. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49451. if (!animation) {
  49452. return null;
  49453. }
  49454. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49455. };
  49456. /**
  49457. * Create and start an animation on a node and its descendants
  49458. * @param name defines the name of the global animation that will be run on all nodes
  49459. * @param node defines the root node where the animation will take place
  49460. * @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
  49461. * @param targetProperty defines property to animate
  49462. * @param framePerSecond defines the number of frame per second to use
  49463. * @param totalFrame defines the number of frames in total
  49464. * @param from defines the initial value
  49465. * @param to defines the final value
  49466. * @param loopMode defines which loop mode you want to use (off by default)
  49467. * @param easingFunction defines the easing function to use (linear by default)
  49468. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49469. * @returns the list of animatables created for all nodes
  49470. * @example https://www.babylonjs-playground.com/#MH0VLI
  49471. */
  49472. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49473. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49474. if (!animation) {
  49475. return null;
  49476. }
  49477. var scene = node.getScene();
  49478. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49479. };
  49480. /**
  49481. * Creates a new animation, merges it with the existing animations and starts it
  49482. * @param name Name of the animation
  49483. * @param node Node which contains the scene that begins the animations
  49484. * @param targetProperty Specifies which property to animate
  49485. * @param framePerSecond The frames per second of the animation
  49486. * @param totalFrame The total number of frames
  49487. * @param from The frame at the beginning of the animation
  49488. * @param to The frame at the end of the animation
  49489. * @param loopMode Specifies the loop mode of the animation
  49490. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49491. * @param onAnimationEnd Callback to run once the animation is complete
  49492. * @returns Nullable animation
  49493. */
  49494. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49495. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49496. if (!animation) {
  49497. return null;
  49498. }
  49499. node.animations.push(animation);
  49500. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49501. };
  49502. /**
  49503. * Transition property of an host to the target Value
  49504. * @param property The property to transition
  49505. * @param targetValue The target Value of the property
  49506. * @param host The object where the property to animate belongs
  49507. * @param scene Scene used to run the animation
  49508. * @param frameRate Framerate (in frame/s) to use
  49509. * @param transition The transition type we want to use
  49510. * @param duration The duration of the animation, in milliseconds
  49511. * @param onAnimationEnd Callback trigger at the end of the animation
  49512. * @returns Nullable animation
  49513. */
  49514. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49515. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49516. if (duration <= 0) {
  49517. host[property] = targetValue;
  49518. if (onAnimationEnd) {
  49519. onAnimationEnd();
  49520. }
  49521. return null;
  49522. }
  49523. var endFrame = frameRate * (duration / 1000);
  49524. transition.setKeys([{
  49525. frame: 0,
  49526. value: host[property].clone ? host[property].clone() : host[property]
  49527. },
  49528. {
  49529. frame: endFrame,
  49530. value: targetValue
  49531. }]);
  49532. if (!host.animations) {
  49533. host.animations = [];
  49534. }
  49535. host.animations.push(transition);
  49536. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49537. animation.onAnimationEnd = onAnimationEnd;
  49538. return animation;
  49539. };
  49540. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49541. /**
  49542. * Return the array of runtime animations currently using this animation
  49543. */
  49544. get: function () {
  49545. return this._runtimeAnimations;
  49546. },
  49547. enumerable: true,
  49548. configurable: true
  49549. });
  49550. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49551. /**
  49552. * Specifies if any of the runtime animations are currently running
  49553. */
  49554. get: function () {
  49555. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49556. var runtimeAnimation = _a[_i];
  49557. if (!runtimeAnimation.isStopped) {
  49558. return true;
  49559. }
  49560. }
  49561. return false;
  49562. },
  49563. enumerable: true,
  49564. configurable: true
  49565. });
  49566. // Methods
  49567. /**
  49568. * Converts the animation to a string
  49569. * @param fullDetails support for multiple levels of logging within scene loading
  49570. * @returns String form of the animation
  49571. */
  49572. Animation.prototype.toString = function (fullDetails) {
  49573. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49574. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49575. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49576. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49577. if (fullDetails) {
  49578. ret += ", Ranges: {";
  49579. var first = true;
  49580. for (var name in this._ranges) {
  49581. if (first) {
  49582. ret += ", ";
  49583. first = false;
  49584. }
  49585. ret += name;
  49586. }
  49587. ret += "}";
  49588. }
  49589. return ret;
  49590. };
  49591. /**
  49592. * Add an event to this animation
  49593. * @param event Event to add
  49594. */
  49595. Animation.prototype.addEvent = function (event) {
  49596. this._events.push(event);
  49597. };
  49598. /**
  49599. * Remove all events found at the given frame
  49600. * @param frame The frame to remove events from
  49601. */
  49602. Animation.prototype.removeEvents = function (frame) {
  49603. for (var index = 0; index < this._events.length; index++) {
  49604. if (this._events[index].frame === frame) {
  49605. this._events.splice(index, 1);
  49606. index--;
  49607. }
  49608. }
  49609. };
  49610. /**
  49611. * Retrieves all the events from the animation
  49612. * @returns Events from the animation
  49613. */
  49614. Animation.prototype.getEvents = function () {
  49615. return this._events;
  49616. };
  49617. /**
  49618. * Creates an animation range
  49619. * @param name Name of the animation range
  49620. * @param from Starting frame of the animation range
  49621. * @param to Ending frame of the animation
  49622. */
  49623. Animation.prototype.createRange = function (name, from, to) {
  49624. // check name not already in use; could happen for bones after serialized
  49625. if (!this._ranges[name]) {
  49626. this._ranges[name] = new AnimationRange(name, from, to);
  49627. }
  49628. };
  49629. /**
  49630. * Deletes an animation range by name
  49631. * @param name Name of the animation range to delete
  49632. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49633. */
  49634. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49635. if (deleteFrames === void 0) { deleteFrames = true; }
  49636. var range = this._ranges[name];
  49637. if (!range) {
  49638. return;
  49639. }
  49640. if (deleteFrames) {
  49641. var from = range.from;
  49642. var to = range.to;
  49643. // this loop MUST go high to low for multiple splices to work
  49644. for (var key = this._keys.length - 1; key >= 0; key--) {
  49645. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49646. this._keys.splice(key, 1);
  49647. }
  49648. }
  49649. }
  49650. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49651. };
  49652. /**
  49653. * Gets the animation range by name, or null if not defined
  49654. * @param name Name of the animation range
  49655. * @returns Nullable animation range
  49656. */
  49657. Animation.prototype.getRange = function (name) {
  49658. return this._ranges[name];
  49659. };
  49660. /**
  49661. * Gets the key frames from the animation
  49662. * @returns The key frames of the animation
  49663. */
  49664. Animation.prototype.getKeys = function () {
  49665. return this._keys;
  49666. };
  49667. /**
  49668. * Gets the highest frame rate of the animation
  49669. * @returns Highest frame rate of the animation
  49670. */
  49671. Animation.prototype.getHighestFrame = function () {
  49672. var ret = 0;
  49673. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49674. if (ret < this._keys[key].frame) {
  49675. ret = this._keys[key].frame;
  49676. }
  49677. }
  49678. return ret;
  49679. };
  49680. /**
  49681. * Gets the easing function of the animation
  49682. * @returns Easing function of the animation
  49683. */
  49684. Animation.prototype.getEasingFunction = function () {
  49685. return this._easingFunction;
  49686. };
  49687. /**
  49688. * Sets the easing function of the animation
  49689. * @param easingFunction A custom mathematical formula for animation
  49690. */
  49691. Animation.prototype.setEasingFunction = function (easingFunction) {
  49692. this._easingFunction = easingFunction;
  49693. };
  49694. /**
  49695. * Interpolates a scalar linearly
  49696. * @param startValue Start value of the animation curve
  49697. * @param endValue End value of the animation curve
  49698. * @param gradient Scalar amount to interpolate
  49699. * @returns Interpolated scalar value
  49700. */
  49701. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49702. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49703. };
  49704. /**
  49705. * Interpolates a scalar cubically
  49706. * @param startValue Start value of the animation curve
  49707. * @param outTangent End tangent of the animation
  49708. * @param endValue End value of the animation curve
  49709. * @param inTangent Start tangent of the animation curve
  49710. * @param gradient Scalar amount to interpolate
  49711. * @returns Interpolated scalar value
  49712. */
  49713. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49714. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49715. };
  49716. /**
  49717. * Interpolates a quaternion using a spherical linear interpolation
  49718. * @param startValue Start value of the animation curve
  49719. * @param endValue End value of the animation curve
  49720. * @param gradient Scalar amount to interpolate
  49721. * @returns Interpolated quaternion value
  49722. */
  49723. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49724. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49725. };
  49726. /**
  49727. * Interpolates a quaternion cubically
  49728. * @param startValue Start value of the animation curve
  49729. * @param outTangent End tangent of the animation curve
  49730. * @param endValue End value of the animation curve
  49731. * @param inTangent Start tangent of the animation curve
  49732. * @param gradient Scalar amount to interpolate
  49733. * @returns Interpolated quaternion value
  49734. */
  49735. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49736. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49737. };
  49738. /**
  49739. * Interpolates a Vector3 linearl
  49740. * @param startValue Start value of the animation curve
  49741. * @param endValue End value of the animation curve
  49742. * @param gradient Scalar amount to interpolate
  49743. * @returns Interpolated scalar value
  49744. */
  49745. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49746. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49747. };
  49748. /**
  49749. * Interpolates a Vector3 cubically
  49750. * @param startValue Start value of the animation curve
  49751. * @param outTangent End tangent of the animation
  49752. * @param endValue End value of the animation curve
  49753. * @param inTangent Start tangent of the animation curve
  49754. * @param gradient Scalar amount to interpolate
  49755. * @returns InterpolatedVector3 value
  49756. */
  49757. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49758. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49759. };
  49760. /**
  49761. * Interpolates a Vector2 linearly
  49762. * @param startValue Start value of the animation curve
  49763. * @param endValue End value of the animation curve
  49764. * @param gradient Scalar amount to interpolate
  49765. * @returns Interpolated Vector2 value
  49766. */
  49767. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49768. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49769. };
  49770. /**
  49771. * Interpolates a Vector2 cubically
  49772. * @param startValue Start value of the animation curve
  49773. * @param outTangent End tangent of the animation
  49774. * @param endValue End value of the animation curve
  49775. * @param inTangent Start tangent of the animation curve
  49776. * @param gradient Scalar amount to interpolate
  49777. * @returns Interpolated Vector2 value
  49778. */
  49779. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49780. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49781. };
  49782. /**
  49783. * Interpolates a size linearly
  49784. * @param startValue Start value of the animation curve
  49785. * @param endValue End value of the animation curve
  49786. * @param gradient Scalar amount to interpolate
  49787. * @returns Interpolated Size value
  49788. */
  49789. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49790. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49791. };
  49792. /**
  49793. * Interpolates a Color3 linearly
  49794. * @param startValue Start value of the animation curve
  49795. * @param endValue End value of the animation curve
  49796. * @param gradient Scalar amount to interpolate
  49797. * @returns Interpolated Color3 value
  49798. */
  49799. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49800. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49801. };
  49802. /**
  49803. * @hidden Internal use only
  49804. */
  49805. Animation.prototype._getKeyValue = function (value) {
  49806. if (typeof value === "function") {
  49807. return value();
  49808. }
  49809. return value;
  49810. };
  49811. /**
  49812. * @hidden Internal use only
  49813. */
  49814. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49815. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49816. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49817. }
  49818. var keys = this.getKeys();
  49819. // Try to get a hash to find the right key
  49820. 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));
  49821. if (keys[startKeyIndex].frame >= currentFrame) {
  49822. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49823. startKeyIndex--;
  49824. }
  49825. }
  49826. for (var key = startKeyIndex; key < keys.length; key++) {
  49827. var endKey = keys[key + 1];
  49828. if (endKey.frame >= currentFrame) {
  49829. var startKey = keys[key];
  49830. var startValue = this._getKeyValue(startKey.value);
  49831. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49832. return startValue;
  49833. }
  49834. var endValue = this._getKeyValue(endKey.value);
  49835. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49836. var frameDelta = endKey.frame - startKey.frame;
  49837. // gradient : percent of currentFrame between the frame inf and the frame sup
  49838. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49839. // check for easingFunction and correction of gradient
  49840. var easingFunction = this.getEasingFunction();
  49841. if (easingFunction != null) {
  49842. gradient = easingFunction.ease(gradient);
  49843. }
  49844. switch (this.dataType) {
  49845. // Float
  49846. case Animation.ANIMATIONTYPE_FLOAT:
  49847. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49848. switch (loopMode) {
  49849. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49850. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49851. return floatValue;
  49852. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49853. return offsetValue * repeatCount + floatValue;
  49854. }
  49855. break;
  49856. // Quaternion
  49857. case Animation.ANIMATIONTYPE_QUATERNION:
  49858. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49859. switch (loopMode) {
  49860. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49861. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49862. return quatValue;
  49863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49864. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49865. }
  49866. return quatValue;
  49867. // Vector3
  49868. case Animation.ANIMATIONTYPE_VECTOR3:
  49869. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49870. switch (loopMode) {
  49871. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49872. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49873. return vec3Value;
  49874. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49875. return vec3Value.add(offsetValue.scale(repeatCount));
  49876. }
  49877. // Vector2
  49878. case Animation.ANIMATIONTYPE_VECTOR2:
  49879. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49880. switch (loopMode) {
  49881. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49882. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49883. return vec2Value;
  49884. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49885. return vec2Value.add(offsetValue.scale(repeatCount));
  49886. }
  49887. // Size
  49888. case Animation.ANIMATIONTYPE_SIZE:
  49889. switch (loopMode) {
  49890. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49891. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49892. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49893. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49894. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49895. }
  49896. // Color3
  49897. case Animation.ANIMATIONTYPE_COLOR3:
  49898. switch (loopMode) {
  49899. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49900. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49901. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49902. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49903. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49904. }
  49905. // Matrix
  49906. case Animation.ANIMATIONTYPE_MATRIX:
  49907. switch (loopMode) {
  49908. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49909. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49910. if (Animation.AllowMatricesInterpolation) {
  49911. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49912. }
  49913. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49914. return startValue;
  49915. }
  49916. default:
  49917. break;
  49918. }
  49919. break;
  49920. }
  49921. }
  49922. return this._getKeyValue(keys[keys.length - 1].value);
  49923. };
  49924. /**
  49925. * Defines the function to use to interpolate matrices
  49926. * @param startValue defines the start matrix
  49927. * @param endValue defines the end matrix
  49928. * @param gradient defines the gradient between both matrices
  49929. * @param result defines an optional target matrix where to store the interpolation
  49930. * @returns the interpolated matrix
  49931. */
  49932. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49933. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49934. if (result) {
  49935. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49936. return result;
  49937. }
  49938. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49939. }
  49940. if (result) {
  49941. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49942. return result;
  49943. }
  49944. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49945. };
  49946. /**
  49947. * Makes a copy of the animation
  49948. * @returns Cloned animation
  49949. */
  49950. Animation.prototype.clone = function () {
  49951. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49952. clone.enableBlending = this.enableBlending;
  49953. clone.blendingSpeed = this.blendingSpeed;
  49954. if (this._keys) {
  49955. clone.setKeys(this._keys);
  49956. }
  49957. if (this._ranges) {
  49958. clone._ranges = {};
  49959. for (var name in this._ranges) {
  49960. var range = this._ranges[name];
  49961. if (!range) {
  49962. continue;
  49963. }
  49964. clone._ranges[name] = range.clone();
  49965. }
  49966. }
  49967. return clone;
  49968. };
  49969. /**
  49970. * Sets the key frames of the animation
  49971. * @param values The animation key frames to set
  49972. */
  49973. Animation.prototype.setKeys = function (values) {
  49974. this._keys = values.slice(0);
  49975. };
  49976. /**
  49977. * Serializes the animation to an object
  49978. * @returns Serialized object
  49979. */
  49980. Animation.prototype.serialize = function () {
  49981. var serializationObject = {};
  49982. serializationObject.name = this.name;
  49983. serializationObject.property = this.targetProperty;
  49984. serializationObject.framePerSecond = this.framePerSecond;
  49985. serializationObject.dataType = this.dataType;
  49986. serializationObject.loopBehavior = this.loopMode;
  49987. serializationObject.enableBlending = this.enableBlending;
  49988. serializationObject.blendingSpeed = this.blendingSpeed;
  49989. var dataType = this.dataType;
  49990. serializationObject.keys = [];
  49991. var keys = this.getKeys();
  49992. for (var index = 0; index < keys.length; index++) {
  49993. var animationKey = keys[index];
  49994. var key = {};
  49995. key.frame = animationKey.frame;
  49996. switch (dataType) {
  49997. case Animation.ANIMATIONTYPE_FLOAT:
  49998. key.values = [animationKey.value];
  49999. break;
  50000. case Animation.ANIMATIONTYPE_QUATERNION:
  50001. case Animation.ANIMATIONTYPE_MATRIX:
  50002. case Animation.ANIMATIONTYPE_VECTOR3:
  50003. case Animation.ANIMATIONTYPE_COLOR3:
  50004. key.values = animationKey.value.asArray();
  50005. break;
  50006. }
  50007. serializationObject.keys.push(key);
  50008. }
  50009. serializationObject.ranges = [];
  50010. for (var name in this._ranges) {
  50011. var source = this._ranges[name];
  50012. if (!source) {
  50013. continue;
  50014. }
  50015. var range = {};
  50016. range.name = name;
  50017. range.from = source.from;
  50018. range.to = source.to;
  50019. serializationObject.ranges.push(range);
  50020. }
  50021. return serializationObject;
  50022. };
  50023. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50024. /**
  50025. * Get the float animation type
  50026. */
  50027. get: function () {
  50028. return Animation._ANIMATIONTYPE_FLOAT;
  50029. },
  50030. enumerable: true,
  50031. configurable: true
  50032. });
  50033. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50034. /**
  50035. * Get the Vector3 animation type
  50036. */
  50037. get: function () {
  50038. return Animation._ANIMATIONTYPE_VECTOR3;
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50044. /**
  50045. * Get the Vectpr2 animation type
  50046. */
  50047. get: function () {
  50048. return Animation._ANIMATIONTYPE_VECTOR2;
  50049. },
  50050. enumerable: true,
  50051. configurable: true
  50052. });
  50053. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50054. /**
  50055. * Get the Size animation type
  50056. */
  50057. get: function () {
  50058. return Animation._ANIMATIONTYPE_SIZE;
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50064. /**
  50065. * Get the Quaternion animation type
  50066. */
  50067. get: function () {
  50068. return Animation._ANIMATIONTYPE_QUATERNION;
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50074. /**
  50075. * Get the Matrix animation type
  50076. */
  50077. get: function () {
  50078. return Animation._ANIMATIONTYPE_MATRIX;
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50084. /**
  50085. * Get the Color3 animation type
  50086. */
  50087. get: function () {
  50088. return Animation._ANIMATIONTYPE_COLOR3;
  50089. },
  50090. enumerable: true,
  50091. configurable: true
  50092. });
  50093. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50094. /**
  50095. * Get the Relative Loop Mode
  50096. */
  50097. get: function () {
  50098. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50104. /**
  50105. * Get the Cycle Loop Mode
  50106. */
  50107. get: function () {
  50108. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50114. /**
  50115. * Get the Constant Loop Mode
  50116. */
  50117. get: function () {
  50118. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. /** @hidden */
  50124. Animation._UniversalLerp = function (left, right, amount) {
  50125. var constructor = left.constructor;
  50126. if (constructor.Lerp) { // Lerp supported
  50127. return constructor.Lerp(left, right, amount);
  50128. }
  50129. else if (constructor.Slerp) { // Slerp supported
  50130. return constructor.Slerp(left, right, amount);
  50131. }
  50132. else if (left.toFixed) { // Number
  50133. return left * (1.0 - amount) + amount * right;
  50134. }
  50135. else { // Blending not supported
  50136. return right;
  50137. }
  50138. };
  50139. /**
  50140. * Parses an animation object and creates an animation
  50141. * @param parsedAnimation Parsed animation object
  50142. * @returns Animation object
  50143. */
  50144. Animation.Parse = function (parsedAnimation) {
  50145. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50146. var dataType = parsedAnimation.dataType;
  50147. var keys = [];
  50148. var data;
  50149. var index;
  50150. if (parsedAnimation.enableBlending) {
  50151. animation.enableBlending = parsedAnimation.enableBlending;
  50152. }
  50153. if (parsedAnimation.blendingSpeed) {
  50154. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50155. }
  50156. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50157. var key = parsedAnimation.keys[index];
  50158. var inTangent;
  50159. var outTangent;
  50160. switch (dataType) {
  50161. case Animation.ANIMATIONTYPE_FLOAT:
  50162. data = key.values[0];
  50163. if (key.values.length >= 1) {
  50164. inTangent = key.values[1];
  50165. }
  50166. if (key.values.length >= 2) {
  50167. outTangent = key.values[2];
  50168. }
  50169. break;
  50170. case Animation.ANIMATIONTYPE_QUATERNION:
  50171. data = BABYLON.Quaternion.FromArray(key.values);
  50172. if (key.values.length >= 8) {
  50173. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50174. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50175. inTangent = _inTangent;
  50176. }
  50177. }
  50178. if (key.values.length >= 12) {
  50179. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50180. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50181. outTangent = _outTangent;
  50182. }
  50183. }
  50184. break;
  50185. case Animation.ANIMATIONTYPE_MATRIX:
  50186. data = BABYLON.Matrix.FromArray(key.values);
  50187. break;
  50188. case Animation.ANIMATIONTYPE_COLOR3:
  50189. data = BABYLON.Color3.FromArray(key.values);
  50190. break;
  50191. case Animation.ANIMATIONTYPE_VECTOR3:
  50192. default:
  50193. data = BABYLON.Vector3.FromArray(key.values);
  50194. break;
  50195. }
  50196. var keyData = {};
  50197. keyData.frame = key.frame;
  50198. keyData.value = data;
  50199. if (inTangent != undefined) {
  50200. keyData.inTangent = inTangent;
  50201. }
  50202. if (outTangent != undefined) {
  50203. keyData.outTangent = outTangent;
  50204. }
  50205. keys.push(keyData);
  50206. }
  50207. animation.setKeys(keys);
  50208. if (parsedAnimation.ranges) {
  50209. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50210. data = parsedAnimation.ranges[index];
  50211. animation.createRange(data.name, data.from, data.to);
  50212. }
  50213. }
  50214. return animation;
  50215. };
  50216. /**
  50217. * Appends the serialized animations from the source animations
  50218. * @param source Source containing the animations
  50219. * @param destination Target to store the animations
  50220. */
  50221. Animation.AppendSerializedAnimations = function (source, destination) {
  50222. if (source.animations) {
  50223. destination.animations = [];
  50224. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50225. var animation = source.animations[animationIndex];
  50226. destination.animations.push(animation.serialize());
  50227. }
  50228. }
  50229. };
  50230. /**
  50231. * Use matrix interpolation instead of using direct key value when animating matrices
  50232. */
  50233. Animation.AllowMatricesInterpolation = false;
  50234. /**
  50235. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50236. */
  50237. Animation.AllowMatrixDecomposeForInterpolation = true;
  50238. // Statics
  50239. /**
  50240. * Float animation type
  50241. */
  50242. Animation._ANIMATIONTYPE_FLOAT = 0;
  50243. /**
  50244. * Vector3 animation type
  50245. */
  50246. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50247. /**
  50248. * Quaternion animation type
  50249. */
  50250. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50251. /**
  50252. * Matrix animation type
  50253. */
  50254. Animation._ANIMATIONTYPE_MATRIX = 3;
  50255. /**
  50256. * Color3 animation type
  50257. */
  50258. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50259. /**
  50260. * Vector2 animation type
  50261. */
  50262. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50263. /**
  50264. * Size animation type
  50265. */
  50266. Animation._ANIMATIONTYPE_SIZE = 6;
  50267. /**
  50268. * Relative Loop Mode
  50269. */
  50270. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50271. /**
  50272. * Cycle Loop Mode
  50273. */
  50274. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50275. /**
  50276. * Constant Loop Mode
  50277. */
  50278. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50279. return Animation;
  50280. }());
  50281. BABYLON.Animation = Animation;
  50282. })(BABYLON || (BABYLON = {}));
  50283. //# sourceMappingURL=babylon.animation.js.map
  50284. var BABYLON;
  50285. (function (BABYLON) {
  50286. /**
  50287. * This class defines the direct association between an animation and a target
  50288. */
  50289. var TargetedAnimation = /** @class */ (function () {
  50290. function TargetedAnimation() {
  50291. }
  50292. return TargetedAnimation;
  50293. }());
  50294. BABYLON.TargetedAnimation = TargetedAnimation;
  50295. /**
  50296. * Use this class to create coordinated animations on multiple targets
  50297. */
  50298. var AnimationGroup = /** @class */ (function () {
  50299. function AnimationGroup(name, scene) {
  50300. if (scene === void 0) { scene = null; }
  50301. this.name = name;
  50302. this._targetedAnimations = new Array();
  50303. this._animatables = new Array();
  50304. this._from = Number.MAX_VALUE;
  50305. this._to = -Number.MAX_VALUE;
  50306. this._speedRatio = 1;
  50307. this.onAnimationEndObservable = new BABYLON.Observable();
  50308. /**
  50309. * This observable will notify when all animations have ended.
  50310. */
  50311. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50312. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50313. this._scene.animationGroups.push(this);
  50314. }
  50315. Object.defineProperty(AnimationGroup.prototype, "from", {
  50316. /**
  50317. * Gets the first frame
  50318. */
  50319. get: function () {
  50320. return this._from;
  50321. },
  50322. enumerable: true,
  50323. configurable: true
  50324. });
  50325. Object.defineProperty(AnimationGroup.prototype, "to", {
  50326. /**
  50327. * Gets the last frame
  50328. */
  50329. get: function () {
  50330. return this._to;
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50336. /**
  50337. * Define if the animations are started
  50338. */
  50339. get: function () {
  50340. return this._isStarted;
  50341. },
  50342. enumerable: true,
  50343. configurable: true
  50344. });
  50345. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50346. /**
  50347. * Gets or sets the speed ratio to use for all animations
  50348. */
  50349. get: function () {
  50350. return this._speedRatio;
  50351. },
  50352. /**
  50353. * Gets or sets the speed ratio to use for all animations
  50354. */
  50355. set: function (value) {
  50356. if (this._speedRatio === value) {
  50357. return;
  50358. }
  50359. this._speedRatio = value;
  50360. for (var index = 0; index < this._animatables.length; index++) {
  50361. var animatable = this._animatables[index];
  50362. animatable.speedRatio = this._speedRatio;
  50363. }
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50369. /**
  50370. * Gets the targeted animations for this animation group
  50371. */
  50372. get: function () {
  50373. return this._targetedAnimations;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50379. /**
  50380. * returning the list of animatables controlled by this animation group.
  50381. */
  50382. get: function () {
  50383. return this._animatables;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. /**
  50389. * Add an animation (with its target) in the group
  50390. * @param animation defines the animation we want to add
  50391. * @param target defines the target of the animation
  50392. * @returns the {BABYLON.TargetedAnimation} object
  50393. */
  50394. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50395. var targetedAnimation = {
  50396. animation: animation,
  50397. target: target
  50398. };
  50399. var keys = animation.getKeys();
  50400. if (this._from > keys[0].frame) {
  50401. this._from = keys[0].frame;
  50402. }
  50403. if (this._to < keys[keys.length - 1].frame) {
  50404. this._to = keys[keys.length - 1].frame;
  50405. }
  50406. this._targetedAnimations.push(targetedAnimation);
  50407. return targetedAnimation;
  50408. };
  50409. /**
  50410. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50411. * It can add constant keys at begin or end
  50412. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50413. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50414. */
  50415. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50416. if (beginFrame === void 0) { beginFrame = null; }
  50417. if (endFrame === void 0) { endFrame = null; }
  50418. if (beginFrame == null)
  50419. beginFrame = this._from;
  50420. if (endFrame == null)
  50421. endFrame = this._to;
  50422. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50423. var targetedAnimation = this._targetedAnimations[index];
  50424. var keys = targetedAnimation.animation.getKeys();
  50425. var startKey = keys[0];
  50426. var endKey = keys[keys.length - 1];
  50427. if (startKey.frame > beginFrame) {
  50428. var newKey = {
  50429. frame: beginFrame,
  50430. value: startKey.value,
  50431. inTangent: startKey.inTangent,
  50432. outTangent: startKey.outTangent,
  50433. interpolation: startKey.interpolation
  50434. };
  50435. keys.splice(0, 0, newKey);
  50436. }
  50437. if (endKey.frame < endFrame) {
  50438. var newKey = {
  50439. frame: endFrame,
  50440. value: endKey.value,
  50441. inTangent: endKey.outTangent,
  50442. outTangent: endKey.outTangent,
  50443. interpolation: endKey.interpolation
  50444. };
  50445. keys.push(newKey);
  50446. }
  50447. }
  50448. this._from = beginFrame;
  50449. this._to = endFrame;
  50450. return this;
  50451. };
  50452. /**
  50453. * Start all animations on given targets
  50454. * @param loop defines if animations must loop
  50455. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50456. * @param from defines the from key (optional)
  50457. * @param to defines the to key (optional)
  50458. * @returns the current animation group
  50459. */
  50460. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50461. var _this = this;
  50462. if (loop === void 0) { loop = false; }
  50463. if (speedRatio === void 0) { speedRatio = 1; }
  50464. if (this._isStarted || this._targetedAnimations.length === 0) {
  50465. return this;
  50466. }
  50467. var _loop_1 = function (targetedAnimation) {
  50468. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50469. animatable.onAnimationEnd = function () {
  50470. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50471. _this._checkAnimationGroupEnded(animatable);
  50472. };
  50473. this_1._animatables.push(animatable);
  50474. };
  50475. var this_1 = this;
  50476. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50477. var targetedAnimation = _a[_i];
  50478. _loop_1(targetedAnimation);
  50479. }
  50480. this._speedRatio = speedRatio;
  50481. this._isStarted = true;
  50482. return this;
  50483. };
  50484. /**
  50485. * Pause all animations
  50486. */
  50487. AnimationGroup.prototype.pause = function () {
  50488. if (!this._isStarted) {
  50489. return this;
  50490. }
  50491. for (var index = 0; index < this._animatables.length; index++) {
  50492. var animatable = this._animatables[index];
  50493. animatable.pause();
  50494. }
  50495. return this;
  50496. };
  50497. /**
  50498. * Play all animations to initial state
  50499. * This function will start() the animations if they were not started or will restart() them if they were paused
  50500. * @param loop defines if animations must loop
  50501. */
  50502. AnimationGroup.prototype.play = function (loop) {
  50503. // only if all animatables are ready and exist
  50504. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50505. if (loop !== undefined) {
  50506. for (var index = 0; index < this._animatables.length; index++) {
  50507. var animatable = this._animatables[index];
  50508. animatable.loopAnimation = loop;
  50509. }
  50510. }
  50511. this.restart();
  50512. }
  50513. else {
  50514. this.stop();
  50515. this.start(loop, this._speedRatio);
  50516. }
  50517. return this;
  50518. };
  50519. /**
  50520. * Reset all animations to initial state
  50521. */
  50522. AnimationGroup.prototype.reset = function () {
  50523. if (!this._isStarted) {
  50524. return this;
  50525. }
  50526. for (var index = 0; index < this._animatables.length; index++) {
  50527. var animatable = this._animatables[index];
  50528. animatable.reset();
  50529. }
  50530. return this;
  50531. };
  50532. /**
  50533. * Restart animations from key 0
  50534. */
  50535. AnimationGroup.prototype.restart = function () {
  50536. if (!this._isStarted) {
  50537. return this;
  50538. }
  50539. for (var index = 0; index < this._animatables.length; index++) {
  50540. var animatable = this._animatables[index];
  50541. animatable.restart();
  50542. }
  50543. return this;
  50544. };
  50545. /**
  50546. * Stop all animations
  50547. */
  50548. AnimationGroup.prototype.stop = function () {
  50549. if (!this._isStarted) {
  50550. return this;
  50551. }
  50552. for (var index = 0; index < this._animatables.length; index++) {
  50553. var animatable = this._animatables[index];
  50554. animatable.stop();
  50555. }
  50556. this._isStarted = false;
  50557. return this;
  50558. };
  50559. /**
  50560. * Set animation weight for all animatables
  50561. * @param weight defines the weight to use
  50562. * @return the animationGroup
  50563. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50564. */
  50565. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50566. for (var index = 0; index < this._animatables.length; index++) {
  50567. var animatable = this._animatables[index];
  50568. animatable.weight = weight;
  50569. }
  50570. return this;
  50571. };
  50572. /**
  50573. * Synchronize and normalize all animatables with a source animatable
  50574. * @param root defines the root animatable to synchronize with
  50575. * @return the animationGroup
  50576. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50577. */
  50578. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50579. for (var index = 0; index < this._animatables.length; index++) {
  50580. var animatable = this._animatables[index];
  50581. animatable.syncWith(root);
  50582. }
  50583. return this;
  50584. };
  50585. /**
  50586. * Goes to a specific frame in this animation group
  50587. * @param frame the frame number to go to
  50588. * @return the animationGroup
  50589. */
  50590. AnimationGroup.prototype.goToFrame = function (frame) {
  50591. if (!this._isStarted) {
  50592. return this;
  50593. }
  50594. for (var index = 0; index < this._animatables.length; index++) {
  50595. var animatable = this._animatables[index];
  50596. animatable.goToFrame(frame);
  50597. }
  50598. return this;
  50599. };
  50600. /**
  50601. * Dispose all associated resources
  50602. */
  50603. AnimationGroup.prototype.dispose = function () {
  50604. this._targetedAnimations = [];
  50605. this._animatables = [];
  50606. var index = this._scene.animationGroups.indexOf(this);
  50607. if (index > -1) {
  50608. this._scene.animationGroups.splice(index, 1);
  50609. }
  50610. };
  50611. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50612. // animatable should be taken out of the array
  50613. var idx = this._animatables.indexOf(animatable);
  50614. if (idx > -1) {
  50615. this._animatables.splice(idx, 1);
  50616. }
  50617. // all animatables were removed? animation group ended!
  50618. if (this._animatables.length === 0) {
  50619. this._isStarted = false;
  50620. this.onAnimationGroupEndObservable.notifyObservers(this);
  50621. }
  50622. };
  50623. return AnimationGroup;
  50624. }());
  50625. BABYLON.AnimationGroup = AnimationGroup;
  50626. })(BABYLON || (BABYLON = {}));
  50627. //# sourceMappingURL=babylon.animationGroup.js.map
  50628. var BABYLON;
  50629. (function (BABYLON) {
  50630. /**
  50631. * Defines a runtime animation
  50632. */
  50633. var RuntimeAnimation = /** @class */ (function () {
  50634. /**
  50635. * Create a new RuntimeAnimation object
  50636. * @param target defines the target of the animation
  50637. * @param animation defines the source animation object
  50638. * @param scene defines the hosting scene
  50639. * @param host defines the initiating Animatable
  50640. */
  50641. function RuntimeAnimation(target, animation, scene, host) {
  50642. var _this = this;
  50643. this._events = new Array();
  50644. /**
  50645. * The current frame of the runtime animation
  50646. */
  50647. this._currentFrame = 0;
  50648. /**
  50649. * The original value of the runtime animation
  50650. */
  50651. this._originalValue = new Array();
  50652. /**
  50653. * The offsets cache of the runtime animation
  50654. */
  50655. this._offsetsCache = {};
  50656. /**
  50657. * The high limits cache of the runtime animation
  50658. */
  50659. this._highLimitsCache = {};
  50660. /**
  50661. * Specifies if the runtime animation has been stopped
  50662. */
  50663. this._stopped = false;
  50664. /**
  50665. * The blending factor of the runtime animation
  50666. */
  50667. this._blendingFactor = 0;
  50668. /**
  50669. * The target path of the runtime animation
  50670. */
  50671. this._targetPath = "";
  50672. /**
  50673. * The weight of the runtime animation
  50674. */
  50675. this._weight = 1.0;
  50676. /**
  50677. * The ratio offset of the runtime animation
  50678. */
  50679. this._ratioOffset = 0;
  50680. /**
  50681. * The previous delay of the runtime animation
  50682. */
  50683. this._previousDelay = 0;
  50684. /**
  50685. * The previous ratio of the runtime animation
  50686. */
  50687. this._previousRatio = 0;
  50688. this._animation = animation;
  50689. this._target = target;
  50690. this._scene = scene;
  50691. this._host = host;
  50692. animation._runtimeAnimations.push(this);
  50693. // Cloning events locally
  50694. var events = animation.getEvents();
  50695. if (events && events.length > 0) {
  50696. events.forEach(function (e) {
  50697. _this._events.push(e._clone());
  50698. });
  50699. }
  50700. }
  50701. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50702. /**
  50703. * Gets the current frame of the runtime animation
  50704. */
  50705. get: function () {
  50706. return this._currentFrame;
  50707. },
  50708. enumerable: true,
  50709. configurable: true
  50710. });
  50711. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50712. /**
  50713. * Gets the weight of the runtime animation
  50714. */
  50715. get: function () {
  50716. return this._weight;
  50717. },
  50718. enumerable: true,
  50719. configurable: true
  50720. });
  50721. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50722. /**
  50723. * Gets the current value of the runtime animation
  50724. */
  50725. get: function () {
  50726. return this._currentValue;
  50727. },
  50728. enumerable: true,
  50729. configurable: true
  50730. });
  50731. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50732. /**
  50733. * Gets the target path of the runtime animation
  50734. */
  50735. get: function () {
  50736. return this._targetPath;
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50742. /**
  50743. * Gets the actual target of the runtime animation
  50744. */
  50745. get: function () {
  50746. return this._activeTarget;
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50752. /**
  50753. * Gets the animation from the runtime animation
  50754. */
  50755. get: function () {
  50756. return this._animation;
  50757. },
  50758. enumerable: true,
  50759. configurable: true
  50760. });
  50761. /**
  50762. * Resets the runtime animation to the beginning
  50763. * @param restoreOriginal defines whether to restore the target property to the original value
  50764. */
  50765. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50766. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50767. if (restoreOriginal) {
  50768. if (this._target instanceof Array) {
  50769. var index = 0;
  50770. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50771. var target = _a[_i];
  50772. if (this._originalValue[index] !== undefined) {
  50773. this._setValue(target, this._originalValue[index], -1);
  50774. }
  50775. index++;
  50776. }
  50777. }
  50778. else {
  50779. if (this._originalValue[0] !== undefined) {
  50780. this._setValue(this._target, this._originalValue[0], -1);
  50781. }
  50782. }
  50783. }
  50784. this._offsetsCache = {};
  50785. this._highLimitsCache = {};
  50786. this._currentFrame = 0;
  50787. this._blendingFactor = 0;
  50788. this._originalValue = new Array();
  50789. // Events
  50790. for (var index = 0; index < this._events.length; index++) {
  50791. this._events[index].isDone = false;
  50792. }
  50793. };
  50794. /**
  50795. * Specifies if the runtime animation is stopped
  50796. * @returns Boolean specifying if the runtime animation is stopped
  50797. */
  50798. RuntimeAnimation.prototype.isStopped = function () {
  50799. return this._stopped;
  50800. };
  50801. /**
  50802. * Disposes of the runtime animation
  50803. */
  50804. RuntimeAnimation.prototype.dispose = function () {
  50805. var index = this._animation.runtimeAnimations.indexOf(this);
  50806. if (index > -1) {
  50807. this._animation.runtimeAnimations.splice(index, 1);
  50808. }
  50809. };
  50810. /**
  50811. * Interpolates the animation from the current frame
  50812. * @param currentFrame The frame to interpolate the animation to
  50813. * @param repeatCount The number of times that the animation should loop
  50814. * @param loopMode The type of looping mode to use
  50815. * @param offsetValue Animation offset value
  50816. * @param highLimitValue The high limit value
  50817. * @returns The interpolated value
  50818. */
  50819. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50820. this._currentFrame = currentFrame;
  50821. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50822. this._workValue = BABYLON.Matrix.Zero();
  50823. }
  50824. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50825. };
  50826. /**
  50827. * Apply the interpolated value to the target
  50828. * @param currentValue defines the value computed by the animation
  50829. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50830. */
  50831. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50832. if (weight === void 0) { weight = 1.0; }
  50833. if (this._target instanceof Array) {
  50834. var index = 0;
  50835. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50836. var target = _a[_i];
  50837. this._setValue(target, currentValue, weight, index);
  50838. index++;
  50839. }
  50840. }
  50841. else {
  50842. this._setValue(this._target, currentValue, weight);
  50843. }
  50844. };
  50845. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50846. if (targetIndex === void 0) { targetIndex = 0; }
  50847. // Set value
  50848. var path;
  50849. var destination;
  50850. var targetPropertyPath = this._animation.targetPropertyPath;
  50851. if (targetPropertyPath.length > 1) {
  50852. var property = target[targetPropertyPath[0]];
  50853. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50854. property = property[targetPropertyPath[index]];
  50855. }
  50856. path = targetPropertyPath[targetPropertyPath.length - 1];
  50857. destination = property;
  50858. }
  50859. else {
  50860. path = targetPropertyPath[0];
  50861. destination = target;
  50862. }
  50863. this._targetPath = path;
  50864. this._activeTarget = destination;
  50865. this._weight = weight;
  50866. if (this._originalValue[targetIndex] === undefined) {
  50867. var originalValue = void 0;
  50868. if (destination.getRestPose && path === "_matrix") { // For bones
  50869. originalValue = destination.getRestPose();
  50870. }
  50871. else {
  50872. originalValue = destination[path];
  50873. }
  50874. if (originalValue && originalValue.clone) {
  50875. this._originalValue[targetIndex] = originalValue.clone();
  50876. }
  50877. else {
  50878. this._originalValue[targetIndex] = originalValue;
  50879. }
  50880. }
  50881. // Blending
  50882. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50883. if (enableBlending && this._blendingFactor <= 1.0) {
  50884. if (!this._originalBlendValue) {
  50885. var originalValue = destination[path];
  50886. if (originalValue.clone) {
  50887. this._originalBlendValue = originalValue.clone();
  50888. }
  50889. else {
  50890. this._originalBlendValue = originalValue;
  50891. }
  50892. }
  50893. if (this._originalBlendValue.m) { // Matrix
  50894. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50895. if (this._currentValue) {
  50896. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50897. }
  50898. else {
  50899. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50900. }
  50901. }
  50902. else {
  50903. if (this._currentValue) {
  50904. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50905. }
  50906. else {
  50907. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50908. }
  50909. }
  50910. }
  50911. else {
  50912. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50913. }
  50914. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50915. this._blendingFactor += blendingSpeed;
  50916. }
  50917. else {
  50918. this._currentValue = currentValue;
  50919. }
  50920. if (weight !== -1.0) {
  50921. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50922. }
  50923. else {
  50924. destination[path] = this._currentValue;
  50925. }
  50926. if (target.markAsDirty) {
  50927. target.markAsDirty(this._animation.targetProperty);
  50928. }
  50929. };
  50930. /**
  50931. * Gets the loop pmode of the runtime animation
  50932. * @returns Loop Mode
  50933. */
  50934. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50935. if (this._target && this._target.animationPropertiesOverride) {
  50936. return this._target.animationPropertiesOverride.loopMode;
  50937. }
  50938. return this._animation.loopMode;
  50939. };
  50940. /**
  50941. * Move the current animation to a given frame
  50942. * @param frame defines the frame to move to
  50943. */
  50944. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50945. var keys = this._animation.getKeys();
  50946. if (frame < keys[0].frame) {
  50947. frame = keys[0].frame;
  50948. }
  50949. else if (frame > keys[keys.length - 1].frame) {
  50950. frame = keys[keys.length - 1].frame;
  50951. }
  50952. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50953. this.setValue(currentValue, -1);
  50954. };
  50955. /**
  50956. * @hidden Internal use only
  50957. */
  50958. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50959. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50960. this._ratioOffset = this._previousRatio - newRatio;
  50961. };
  50962. /**
  50963. * Execute the current animation
  50964. * @param delay defines the delay to add to the current frame
  50965. * @param from defines the lower bound of the animation range
  50966. * @param to defines the upper bound of the animation range
  50967. * @param loop defines if the current animation must loop
  50968. * @param speedRatio defines the current speed ratio
  50969. * @param weight defines the weight of the animation (default is -1 so no weight)
  50970. * @returns a boolean indicating if the animation has ended
  50971. */
  50972. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50973. if (weight === void 0) { weight = -1.0; }
  50974. var targetPropertyPath = this._animation.targetPropertyPath;
  50975. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50976. this._stopped = true;
  50977. return false;
  50978. }
  50979. var returnValue = true;
  50980. var keys = this._animation.getKeys();
  50981. // Adding a start key at frame 0 if missing
  50982. if (keys[0].frame !== 0) {
  50983. var newKey = { frame: 0, value: keys[0].value };
  50984. keys.splice(0, 0, newKey);
  50985. }
  50986. // Check limits
  50987. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50988. from = keys[0].frame;
  50989. }
  50990. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50991. to = keys[keys.length - 1].frame;
  50992. }
  50993. //to and from cannot be the same key
  50994. if (from === to) {
  50995. if (from > keys[0].frame) {
  50996. from--;
  50997. }
  50998. else if (to < keys[keys.length - 1].frame) {
  50999. to++;
  51000. }
  51001. }
  51002. // Compute ratio
  51003. var range = to - from;
  51004. var offsetValue;
  51005. // ratio represents the frame delta between from and to
  51006. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51007. var highLimitValue = 0;
  51008. this._previousDelay = delay;
  51009. this._previousRatio = ratio;
  51010. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51011. returnValue = false;
  51012. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51013. }
  51014. else {
  51015. // Get max value if required
  51016. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51017. var keyOffset = to.toString() + from.toString();
  51018. if (!this._offsetsCache[keyOffset]) {
  51019. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51020. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51021. switch (this._animation.dataType) {
  51022. // Float
  51023. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51024. this._offsetsCache[keyOffset] = toValue - fromValue;
  51025. break;
  51026. // Quaternion
  51027. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51028. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51029. break;
  51030. // Vector3
  51031. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51032. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51033. // Vector2
  51034. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51035. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51036. // Size
  51037. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51038. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51039. // Color3
  51040. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51041. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51042. default:
  51043. break;
  51044. }
  51045. this._highLimitsCache[keyOffset] = toValue;
  51046. }
  51047. highLimitValue = this._highLimitsCache[keyOffset];
  51048. offsetValue = this._offsetsCache[keyOffset];
  51049. }
  51050. }
  51051. if (offsetValue === undefined) {
  51052. switch (this._animation.dataType) {
  51053. // Float
  51054. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51055. offsetValue = 0;
  51056. break;
  51057. // Quaternion
  51058. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51059. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51060. break;
  51061. // Vector3
  51062. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51063. offsetValue = BABYLON.Vector3.Zero();
  51064. break;
  51065. // Vector2
  51066. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51067. offsetValue = BABYLON.Vector2.Zero();
  51068. break;
  51069. // Size
  51070. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51071. offsetValue = BABYLON.Size.Zero();
  51072. break;
  51073. // Color3
  51074. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51075. offsetValue = BABYLON.Color3.Black();
  51076. }
  51077. }
  51078. // Compute value
  51079. var repeatCount = (ratio / range) >> 0;
  51080. var currentFrame = returnValue ? from + ratio % range : to;
  51081. // Need to normalize?
  51082. if (this._host && this._host.syncRoot) {
  51083. var syncRoot = this._host.syncRoot;
  51084. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51085. currentFrame = from + (to - from) * hostNormalizedFrame;
  51086. }
  51087. // Reset events if looping
  51088. var events = this._events;
  51089. if (range > 0 && this.currentFrame > currentFrame ||
  51090. range < 0 && this.currentFrame < currentFrame) {
  51091. // Need to reset animation events
  51092. for (var index = 0; index < events.length; index++) {
  51093. if (!events[index].onlyOnce) {
  51094. // reset event, the animation is looping
  51095. events[index].isDone = false;
  51096. }
  51097. }
  51098. }
  51099. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51100. // Set value
  51101. this.setValue(currentValue, weight);
  51102. // Check events
  51103. for (var index = 0; index < events.length; index++) {
  51104. // Make sure current frame has passed event frame and that event frame is within the current range
  51105. // Also, handle both forward and reverse animations
  51106. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51107. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51108. var event = events[index];
  51109. if (!event.isDone) {
  51110. // If event should be done only once, remove it.
  51111. if (event.onlyOnce) {
  51112. events.splice(index, 1);
  51113. index--;
  51114. }
  51115. event.isDone = true;
  51116. event.action();
  51117. } // Don't do anything if the event has already be done.
  51118. }
  51119. }
  51120. if (!returnValue) {
  51121. this._stopped = true;
  51122. }
  51123. return returnValue;
  51124. };
  51125. return RuntimeAnimation;
  51126. }());
  51127. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51128. })(BABYLON || (BABYLON = {}));
  51129. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51130. var BABYLON;
  51131. (function (BABYLON) {
  51132. var Animatable = /** @class */ (function () {
  51133. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51134. if (fromFrame === void 0) { fromFrame = 0; }
  51135. if (toFrame === void 0) { toFrame = 100; }
  51136. if (loopAnimation === void 0) { loopAnimation = false; }
  51137. if (speedRatio === void 0) { speedRatio = 1.0; }
  51138. this.target = target;
  51139. this.fromFrame = fromFrame;
  51140. this.toFrame = toFrame;
  51141. this.loopAnimation = loopAnimation;
  51142. this.onAnimationEnd = onAnimationEnd;
  51143. this._localDelayOffset = null;
  51144. this._pausedDelay = null;
  51145. this._runtimeAnimations = new Array();
  51146. this._paused = false;
  51147. this._speedRatio = 1;
  51148. this._weight = -1.0;
  51149. this.animationStarted = false;
  51150. /**
  51151. * Observer raised when the animation ends
  51152. */
  51153. this.onAnimationEndObservable = new BABYLON.Observable();
  51154. this._scene = scene;
  51155. if (animations) {
  51156. this.appendAnimations(target, animations);
  51157. }
  51158. this._speedRatio = speedRatio;
  51159. scene._activeAnimatables.push(this);
  51160. }
  51161. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51162. /**
  51163. * Gets the root Animatable used to synchronize and normalize animations
  51164. */
  51165. get: function () {
  51166. return this._syncRoot;
  51167. },
  51168. enumerable: true,
  51169. configurable: true
  51170. });
  51171. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51172. /**
  51173. * Gets the current frame of the first RuntimeAnimation
  51174. * Used to synchronize Animatables
  51175. */
  51176. get: function () {
  51177. if (this._runtimeAnimations.length === 0) {
  51178. return 0;
  51179. }
  51180. return this._runtimeAnimations[0].currentFrame;
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(Animatable.prototype, "weight", {
  51186. /**
  51187. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51188. */
  51189. get: function () {
  51190. return this._weight;
  51191. },
  51192. set: function (value) {
  51193. if (value === -1) { // -1 is ok and means no weight
  51194. this._weight = -1;
  51195. return;
  51196. }
  51197. // Else weight must be in [0, 1] range
  51198. this._weight = Math.min(Math.max(value, 0), 1.0);
  51199. },
  51200. enumerable: true,
  51201. configurable: true
  51202. });
  51203. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51204. /**
  51205. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51206. */
  51207. get: function () {
  51208. return this._speedRatio;
  51209. },
  51210. set: function (value) {
  51211. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51212. var animation = this._runtimeAnimations[index];
  51213. animation._prepareForSpeedRatioChange(value);
  51214. }
  51215. this._speedRatio = value;
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. // Methods
  51221. /**
  51222. * Synchronize and normalize current Animatable with a source Animatable
  51223. * This is useful when using animation weights and when animations are not of the same length
  51224. * @param root defines the root Animatable to synchronize with
  51225. * @returns the current Animatable
  51226. */
  51227. Animatable.prototype.syncWith = function (root) {
  51228. this._syncRoot = root;
  51229. if (root) {
  51230. // Make sure this animatable will animate after the root
  51231. var index = this._scene._activeAnimatables.indexOf(this);
  51232. if (index > -1) {
  51233. this._scene._activeAnimatables.splice(index, 1);
  51234. this._scene._activeAnimatables.push(this);
  51235. }
  51236. }
  51237. return this;
  51238. };
  51239. Animatable.prototype.getAnimations = function () {
  51240. return this._runtimeAnimations;
  51241. };
  51242. Animatable.prototype.appendAnimations = function (target, animations) {
  51243. for (var index = 0; index < animations.length; index++) {
  51244. var animation = animations[index];
  51245. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51246. }
  51247. };
  51248. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51249. var runtimeAnimations = this._runtimeAnimations;
  51250. for (var index = 0; index < runtimeAnimations.length; index++) {
  51251. if (runtimeAnimations[index].animation.targetProperty === property) {
  51252. return runtimeAnimations[index].animation;
  51253. }
  51254. }
  51255. return null;
  51256. };
  51257. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51258. var runtimeAnimations = this._runtimeAnimations;
  51259. for (var index = 0; index < runtimeAnimations.length; index++) {
  51260. if (runtimeAnimations[index].animation.targetProperty === property) {
  51261. return runtimeAnimations[index];
  51262. }
  51263. }
  51264. return null;
  51265. };
  51266. Animatable.prototype.reset = function () {
  51267. var runtimeAnimations = this._runtimeAnimations;
  51268. for (var index = 0; index < runtimeAnimations.length; index++) {
  51269. runtimeAnimations[index].reset(true);
  51270. }
  51271. this._localDelayOffset = null;
  51272. this._pausedDelay = null;
  51273. };
  51274. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51275. var runtimeAnimations = this._runtimeAnimations;
  51276. for (var index = 0; index < runtimeAnimations.length; index++) {
  51277. runtimeAnimations[index].animation.enableBlending = true;
  51278. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51279. }
  51280. };
  51281. Animatable.prototype.disableBlending = function () {
  51282. var runtimeAnimations = this._runtimeAnimations;
  51283. for (var index = 0; index < runtimeAnimations.length; index++) {
  51284. runtimeAnimations[index].animation.enableBlending = false;
  51285. }
  51286. };
  51287. Animatable.prototype.goToFrame = function (frame) {
  51288. var runtimeAnimations = this._runtimeAnimations;
  51289. if (runtimeAnimations[0]) {
  51290. var fps = runtimeAnimations[0].animation.framePerSecond;
  51291. var currentFrame = runtimeAnimations[0].currentFrame;
  51292. var adjustTime = frame - currentFrame;
  51293. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51294. if (this._localDelayOffset === null) {
  51295. this._localDelayOffset = 0;
  51296. }
  51297. this._localDelayOffset -= delay;
  51298. }
  51299. for (var index = 0; index < runtimeAnimations.length; index++) {
  51300. runtimeAnimations[index].goToFrame(frame);
  51301. }
  51302. };
  51303. Animatable.prototype.pause = function () {
  51304. if (this._paused) {
  51305. return;
  51306. }
  51307. this._paused = true;
  51308. };
  51309. Animatable.prototype.restart = function () {
  51310. this._paused = false;
  51311. };
  51312. Animatable.prototype._raiseOnAnimationEnd = function () {
  51313. if (this.onAnimationEnd) {
  51314. this.onAnimationEnd();
  51315. }
  51316. this.onAnimationEndObservable.notifyObservers(this);
  51317. };
  51318. Animatable.prototype.stop = function (animationName) {
  51319. if (animationName) {
  51320. var idx = this._scene._activeAnimatables.indexOf(this);
  51321. if (idx > -1) {
  51322. var runtimeAnimations = this._runtimeAnimations;
  51323. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51324. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51325. continue;
  51326. }
  51327. runtimeAnimations[index].dispose();
  51328. runtimeAnimations.splice(index, 1);
  51329. }
  51330. if (runtimeAnimations.length == 0) {
  51331. this._scene._activeAnimatables.splice(idx, 1);
  51332. this._raiseOnAnimationEnd();
  51333. }
  51334. }
  51335. }
  51336. else {
  51337. var index = this._scene._activeAnimatables.indexOf(this);
  51338. if (index > -1) {
  51339. this._scene._activeAnimatables.splice(index, 1);
  51340. var runtimeAnimations = this._runtimeAnimations;
  51341. for (var index = 0; index < runtimeAnimations.length; index++) {
  51342. runtimeAnimations[index].dispose();
  51343. }
  51344. this._raiseOnAnimationEnd();
  51345. }
  51346. }
  51347. };
  51348. /**
  51349. * Wait asynchronously for the animation to end
  51350. * @returns a promise which will be fullfilled when the animation ends
  51351. */
  51352. Animatable.prototype.waitAsync = function () {
  51353. var _this = this;
  51354. return new Promise(function (resolve, reject) {
  51355. _this.onAnimationEndObservable.add(function () {
  51356. resolve(_this);
  51357. }, undefined, undefined, _this, true);
  51358. });
  51359. };
  51360. /** @hidden */
  51361. Animatable.prototype._animate = function (delay) {
  51362. if (this._paused) {
  51363. this.animationStarted = false;
  51364. if (this._pausedDelay === null) {
  51365. this._pausedDelay = delay;
  51366. }
  51367. return true;
  51368. }
  51369. if (this._localDelayOffset === null) {
  51370. this._localDelayOffset = delay;
  51371. this._pausedDelay = null;
  51372. }
  51373. else if (this._pausedDelay !== null) {
  51374. this._localDelayOffset += delay - this._pausedDelay;
  51375. this._pausedDelay = null;
  51376. }
  51377. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51378. return true;
  51379. }
  51380. // Animating
  51381. var running = false;
  51382. var runtimeAnimations = this._runtimeAnimations;
  51383. var index;
  51384. for (index = 0; index < runtimeAnimations.length; index++) {
  51385. var animation = runtimeAnimations[index];
  51386. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51387. running = running || isRunning;
  51388. }
  51389. this.animationStarted = running;
  51390. if (!running) {
  51391. // Remove from active animatables
  51392. index = this._scene._activeAnimatables.indexOf(this);
  51393. this._scene._activeAnimatables.splice(index, 1);
  51394. // Dispose all runtime animations
  51395. for (index = 0; index < runtimeAnimations.length; index++) {
  51396. runtimeAnimations[index].dispose();
  51397. }
  51398. this._raiseOnAnimationEnd();
  51399. this.onAnimationEnd = null;
  51400. this.onAnimationEndObservable.clear();
  51401. }
  51402. return running;
  51403. };
  51404. return Animatable;
  51405. }());
  51406. BABYLON.Animatable = Animatable;
  51407. })(BABYLON || (BABYLON = {}));
  51408. //# sourceMappingURL=babylon.animatable.js.map
  51409. var BABYLON;
  51410. (function (BABYLON) {
  51411. var EasingFunction = /** @class */ (function () {
  51412. function EasingFunction() {
  51413. // Properties
  51414. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51415. }
  51416. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51417. get: function () {
  51418. return EasingFunction._EASINGMODE_EASEIN;
  51419. },
  51420. enumerable: true,
  51421. configurable: true
  51422. });
  51423. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51424. get: function () {
  51425. return EasingFunction._EASINGMODE_EASEOUT;
  51426. },
  51427. enumerable: true,
  51428. configurable: true
  51429. });
  51430. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51431. get: function () {
  51432. return EasingFunction._EASINGMODE_EASEINOUT;
  51433. },
  51434. enumerable: true,
  51435. configurable: true
  51436. });
  51437. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51438. var n = Math.min(Math.max(easingMode, 0), 2);
  51439. this._easingMode = n;
  51440. };
  51441. EasingFunction.prototype.getEasingMode = function () {
  51442. return this._easingMode;
  51443. };
  51444. EasingFunction.prototype.easeInCore = function (gradient) {
  51445. throw new Error('You must implement this method');
  51446. };
  51447. EasingFunction.prototype.ease = function (gradient) {
  51448. switch (this._easingMode) {
  51449. case EasingFunction.EASINGMODE_EASEIN:
  51450. return this.easeInCore(gradient);
  51451. case EasingFunction.EASINGMODE_EASEOUT:
  51452. return (1 - this.easeInCore(1 - gradient));
  51453. }
  51454. if (gradient >= 0.5) {
  51455. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51456. }
  51457. return (this.easeInCore(gradient * 2) * 0.5);
  51458. };
  51459. //Statics
  51460. EasingFunction._EASINGMODE_EASEIN = 0;
  51461. EasingFunction._EASINGMODE_EASEOUT = 1;
  51462. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51463. return EasingFunction;
  51464. }());
  51465. BABYLON.EasingFunction = EasingFunction;
  51466. var CircleEase = /** @class */ (function (_super) {
  51467. __extends(CircleEase, _super);
  51468. function CircleEase() {
  51469. return _super !== null && _super.apply(this, arguments) || this;
  51470. }
  51471. CircleEase.prototype.easeInCore = function (gradient) {
  51472. gradient = Math.max(0, Math.min(1, gradient));
  51473. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51474. };
  51475. return CircleEase;
  51476. }(EasingFunction));
  51477. BABYLON.CircleEase = CircleEase;
  51478. var BackEase = /** @class */ (function (_super) {
  51479. __extends(BackEase, _super);
  51480. function BackEase(amplitude) {
  51481. if (amplitude === void 0) { amplitude = 1; }
  51482. var _this = _super.call(this) || this;
  51483. _this.amplitude = amplitude;
  51484. return _this;
  51485. }
  51486. BackEase.prototype.easeInCore = function (gradient) {
  51487. var num = Math.max(0, this.amplitude);
  51488. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51489. };
  51490. return BackEase;
  51491. }(EasingFunction));
  51492. BABYLON.BackEase = BackEase;
  51493. var BounceEase = /** @class */ (function (_super) {
  51494. __extends(BounceEase, _super);
  51495. function BounceEase(bounces, bounciness) {
  51496. if (bounces === void 0) { bounces = 3; }
  51497. if (bounciness === void 0) { bounciness = 2; }
  51498. var _this = _super.call(this) || this;
  51499. _this.bounces = bounces;
  51500. _this.bounciness = bounciness;
  51501. return _this;
  51502. }
  51503. BounceEase.prototype.easeInCore = function (gradient) {
  51504. var y = Math.max(0.0, this.bounces);
  51505. var bounciness = this.bounciness;
  51506. if (bounciness <= 1.0) {
  51507. bounciness = 1.001;
  51508. }
  51509. var num9 = Math.pow(bounciness, y);
  51510. var num5 = 1.0 - bounciness;
  51511. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51512. var num15 = gradient * num4;
  51513. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51514. var num3 = Math.floor(num65);
  51515. var num13 = num3 + 1.0;
  51516. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51517. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51518. var num7 = (num8 + num12) * 0.5;
  51519. var num6 = gradient - num7;
  51520. var num2 = num7 - num8;
  51521. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51522. };
  51523. return BounceEase;
  51524. }(EasingFunction));
  51525. BABYLON.BounceEase = BounceEase;
  51526. var CubicEase = /** @class */ (function (_super) {
  51527. __extends(CubicEase, _super);
  51528. function CubicEase() {
  51529. return _super !== null && _super.apply(this, arguments) || this;
  51530. }
  51531. CubicEase.prototype.easeInCore = function (gradient) {
  51532. return (gradient * gradient * gradient);
  51533. };
  51534. return CubicEase;
  51535. }(EasingFunction));
  51536. BABYLON.CubicEase = CubicEase;
  51537. var ElasticEase = /** @class */ (function (_super) {
  51538. __extends(ElasticEase, _super);
  51539. function ElasticEase(oscillations, springiness) {
  51540. if (oscillations === void 0) { oscillations = 3; }
  51541. if (springiness === void 0) { springiness = 3; }
  51542. var _this = _super.call(this) || this;
  51543. _this.oscillations = oscillations;
  51544. _this.springiness = springiness;
  51545. return _this;
  51546. }
  51547. ElasticEase.prototype.easeInCore = function (gradient) {
  51548. var num2;
  51549. var num3 = Math.max(0.0, this.oscillations);
  51550. var num = Math.max(0.0, this.springiness);
  51551. if (num == 0) {
  51552. num2 = gradient;
  51553. }
  51554. else {
  51555. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51556. }
  51557. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51558. };
  51559. return ElasticEase;
  51560. }(EasingFunction));
  51561. BABYLON.ElasticEase = ElasticEase;
  51562. var ExponentialEase = /** @class */ (function (_super) {
  51563. __extends(ExponentialEase, _super);
  51564. function ExponentialEase(exponent) {
  51565. if (exponent === void 0) { exponent = 2; }
  51566. var _this = _super.call(this) || this;
  51567. _this.exponent = exponent;
  51568. return _this;
  51569. }
  51570. ExponentialEase.prototype.easeInCore = function (gradient) {
  51571. if (this.exponent <= 0) {
  51572. return gradient;
  51573. }
  51574. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51575. };
  51576. return ExponentialEase;
  51577. }(EasingFunction));
  51578. BABYLON.ExponentialEase = ExponentialEase;
  51579. var PowerEase = /** @class */ (function (_super) {
  51580. __extends(PowerEase, _super);
  51581. function PowerEase(power) {
  51582. if (power === void 0) { power = 2; }
  51583. var _this = _super.call(this) || this;
  51584. _this.power = power;
  51585. return _this;
  51586. }
  51587. PowerEase.prototype.easeInCore = function (gradient) {
  51588. var y = Math.max(0.0, this.power);
  51589. return Math.pow(gradient, y);
  51590. };
  51591. return PowerEase;
  51592. }(EasingFunction));
  51593. BABYLON.PowerEase = PowerEase;
  51594. var QuadraticEase = /** @class */ (function (_super) {
  51595. __extends(QuadraticEase, _super);
  51596. function QuadraticEase() {
  51597. return _super !== null && _super.apply(this, arguments) || this;
  51598. }
  51599. QuadraticEase.prototype.easeInCore = function (gradient) {
  51600. return (gradient * gradient);
  51601. };
  51602. return QuadraticEase;
  51603. }(EasingFunction));
  51604. BABYLON.QuadraticEase = QuadraticEase;
  51605. var QuarticEase = /** @class */ (function (_super) {
  51606. __extends(QuarticEase, _super);
  51607. function QuarticEase() {
  51608. return _super !== null && _super.apply(this, arguments) || this;
  51609. }
  51610. QuarticEase.prototype.easeInCore = function (gradient) {
  51611. return (gradient * gradient * gradient * gradient);
  51612. };
  51613. return QuarticEase;
  51614. }(EasingFunction));
  51615. BABYLON.QuarticEase = QuarticEase;
  51616. var QuinticEase = /** @class */ (function (_super) {
  51617. __extends(QuinticEase, _super);
  51618. function QuinticEase() {
  51619. return _super !== null && _super.apply(this, arguments) || this;
  51620. }
  51621. QuinticEase.prototype.easeInCore = function (gradient) {
  51622. return (gradient * gradient * gradient * gradient * gradient);
  51623. };
  51624. return QuinticEase;
  51625. }(EasingFunction));
  51626. BABYLON.QuinticEase = QuinticEase;
  51627. var SineEase = /** @class */ (function (_super) {
  51628. __extends(SineEase, _super);
  51629. function SineEase() {
  51630. return _super !== null && _super.apply(this, arguments) || this;
  51631. }
  51632. SineEase.prototype.easeInCore = function (gradient) {
  51633. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51634. };
  51635. return SineEase;
  51636. }(EasingFunction));
  51637. BABYLON.SineEase = SineEase;
  51638. var BezierCurveEase = /** @class */ (function (_super) {
  51639. __extends(BezierCurveEase, _super);
  51640. function BezierCurveEase(x1, y1, x2, y2) {
  51641. if (x1 === void 0) { x1 = 0; }
  51642. if (y1 === void 0) { y1 = 0; }
  51643. if (x2 === void 0) { x2 = 1; }
  51644. if (y2 === void 0) { y2 = 1; }
  51645. var _this = _super.call(this) || this;
  51646. _this.x1 = x1;
  51647. _this.y1 = y1;
  51648. _this.x2 = x2;
  51649. _this.y2 = y2;
  51650. return _this;
  51651. }
  51652. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51653. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51654. };
  51655. return BezierCurveEase;
  51656. }(EasingFunction));
  51657. BABYLON.BezierCurveEase = BezierCurveEase;
  51658. })(BABYLON || (BABYLON = {}));
  51659. //# sourceMappingURL=babylon.easing.js.map
  51660. var BABYLON;
  51661. (function (BABYLON) {
  51662. /**
  51663. * A Condition applied to an Action
  51664. */
  51665. var Condition = /** @class */ (function () {
  51666. /**
  51667. * Creates a new Condition
  51668. * @param actionManager the manager of the action the condition is applied to
  51669. */
  51670. function Condition(actionManager) {
  51671. this._actionManager = actionManager;
  51672. }
  51673. /**
  51674. * Check if the current condition is valid
  51675. * @returns a boolean
  51676. */
  51677. Condition.prototype.isValid = function () {
  51678. return true;
  51679. };
  51680. /**
  51681. * Internal only
  51682. * @hidden
  51683. */
  51684. Condition.prototype._getProperty = function (propertyPath) {
  51685. return this._actionManager._getProperty(propertyPath);
  51686. };
  51687. /**
  51688. * Internal only
  51689. * @hidden
  51690. */
  51691. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51692. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51693. };
  51694. /**
  51695. * Serialize placeholder for child classes
  51696. * @returns the serialized object
  51697. */
  51698. Condition.prototype.serialize = function () {
  51699. };
  51700. /**
  51701. * Internal only
  51702. * @hidden
  51703. */
  51704. Condition.prototype._serialize = function (serializedCondition) {
  51705. return {
  51706. type: 2,
  51707. children: [],
  51708. name: serializedCondition.name,
  51709. properties: serializedCondition.properties
  51710. };
  51711. };
  51712. return Condition;
  51713. }());
  51714. BABYLON.Condition = Condition;
  51715. /**
  51716. * Defines specific conditional operators as extensions of Condition
  51717. */
  51718. var ValueCondition = /** @class */ (function (_super) {
  51719. __extends(ValueCondition, _super);
  51720. /**
  51721. * Creates a new ValueCondition
  51722. * @param actionManager manager for the action the condition applies to
  51723. * @param target for the action
  51724. * @param propertyPath path to specify the property of the target the conditional operator uses
  51725. * @param value the value compared by the conditional operator against the current value of the property
  51726. * @param operator the conditional operator, default ValueCondition.IsEqual
  51727. */
  51728. function ValueCondition(actionManager, target,
  51729. /** path to specify the property of the target the conditional operator uses */
  51730. propertyPath,
  51731. /** the value compared by the conditional operator against the current value of the property */
  51732. value,
  51733. /** the conditional operator, default ValueCondition.IsEqual */
  51734. operator) {
  51735. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51736. var _this = _super.call(this, actionManager) || this;
  51737. _this.propertyPath = propertyPath;
  51738. _this.value = value;
  51739. _this.operator = operator;
  51740. _this._target = target;
  51741. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51742. _this._property = _this._getProperty(_this.propertyPath);
  51743. return _this;
  51744. }
  51745. Object.defineProperty(ValueCondition, "IsEqual", {
  51746. /**
  51747. * returns the number for IsEqual
  51748. */
  51749. get: function () {
  51750. return ValueCondition._IsEqual;
  51751. },
  51752. enumerable: true,
  51753. configurable: true
  51754. });
  51755. Object.defineProperty(ValueCondition, "IsDifferent", {
  51756. /**
  51757. * Returns the number for IsDifferent
  51758. */
  51759. get: function () {
  51760. return ValueCondition._IsDifferent;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(ValueCondition, "IsGreater", {
  51766. /**
  51767. * Returns the number for IsGreater
  51768. */
  51769. get: function () {
  51770. return ValueCondition._IsGreater;
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. Object.defineProperty(ValueCondition, "IsLesser", {
  51776. /**
  51777. * Returns the number for IsLesser
  51778. */
  51779. get: function () {
  51780. return ValueCondition._IsLesser;
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. /**
  51786. * Compares the given value with the property value for the specified conditional operator
  51787. * @returns the result of the comparison
  51788. */
  51789. ValueCondition.prototype.isValid = function () {
  51790. switch (this.operator) {
  51791. case ValueCondition.IsGreater:
  51792. return this._effectiveTarget[this._property] > this.value;
  51793. case ValueCondition.IsLesser:
  51794. return this._effectiveTarget[this._property] < this.value;
  51795. case ValueCondition.IsEqual:
  51796. case ValueCondition.IsDifferent:
  51797. var check;
  51798. if (this.value.equals) {
  51799. check = this.value.equals(this._effectiveTarget[this._property]);
  51800. }
  51801. else {
  51802. check = this.value === this._effectiveTarget[this._property];
  51803. }
  51804. return this.operator === ValueCondition.IsEqual ? check : !check;
  51805. }
  51806. return false;
  51807. };
  51808. /**
  51809. * Serialize the ValueCondition into a JSON compatible object
  51810. * @returns serialization object
  51811. */
  51812. ValueCondition.prototype.serialize = function () {
  51813. return this._serialize({
  51814. name: "ValueCondition",
  51815. properties: [
  51816. BABYLON.Action._GetTargetProperty(this._target),
  51817. { name: "propertyPath", value: this.propertyPath },
  51818. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51819. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51820. ]
  51821. });
  51822. };
  51823. /**
  51824. * Gets the name of the conditional operator for the ValueCondition
  51825. * @param operator the conditional operator
  51826. * @returns the name
  51827. */
  51828. ValueCondition.GetOperatorName = function (operator) {
  51829. switch (operator) {
  51830. case ValueCondition._IsEqual: return "IsEqual";
  51831. case ValueCondition._IsDifferent: return "IsDifferent";
  51832. case ValueCondition._IsGreater: return "IsGreater";
  51833. case ValueCondition._IsLesser: return "IsLesser";
  51834. default: return "";
  51835. }
  51836. };
  51837. /**
  51838. * Internal only
  51839. * @hidden
  51840. */
  51841. ValueCondition._IsEqual = 0;
  51842. /**
  51843. * Internal only
  51844. * @hidden
  51845. */
  51846. ValueCondition._IsDifferent = 1;
  51847. /**
  51848. * Internal only
  51849. * @hidden
  51850. */
  51851. ValueCondition._IsGreater = 2;
  51852. /**
  51853. * Internal only
  51854. * @hidden
  51855. */
  51856. ValueCondition._IsLesser = 3;
  51857. return ValueCondition;
  51858. }(Condition));
  51859. BABYLON.ValueCondition = ValueCondition;
  51860. /**
  51861. * Defines a predicate condition as an extension of Condition
  51862. */
  51863. var PredicateCondition = /** @class */ (function (_super) {
  51864. __extends(PredicateCondition, _super);
  51865. /**
  51866. * Creates a new PredicateCondition
  51867. * @param actionManager manager for the action the condition applies to
  51868. * @param predicate defines the predicate function used to validate the condition
  51869. */
  51870. function PredicateCondition(actionManager,
  51871. /** defines the predicate function used to validate the condition */
  51872. predicate) {
  51873. var _this = _super.call(this, actionManager) || this;
  51874. _this.predicate = predicate;
  51875. return _this;
  51876. }
  51877. /**
  51878. * @returns the validity of the predicate condition
  51879. */
  51880. PredicateCondition.prototype.isValid = function () {
  51881. return this.predicate();
  51882. };
  51883. return PredicateCondition;
  51884. }(Condition));
  51885. BABYLON.PredicateCondition = PredicateCondition;
  51886. /**
  51887. * Defines a state condition as an extension of Condition
  51888. */
  51889. var StateCondition = /** @class */ (function (_super) {
  51890. __extends(StateCondition, _super);
  51891. /**
  51892. * Creates a new StateCondition
  51893. * @param actionManager manager for the action the condition applies to
  51894. * @param target of the condition
  51895. * @param value to compare with target state
  51896. */
  51897. function StateCondition(actionManager, target, value) {
  51898. var _this = _super.call(this, actionManager) || this;
  51899. _this.value = value;
  51900. _this._target = target;
  51901. return _this;
  51902. }
  51903. /**
  51904. * @returns the validity of the state
  51905. */
  51906. StateCondition.prototype.isValid = function () {
  51907. return this._target.state === this.value;
  51908. };
  51909. /**
  51910. * Serialize the StateCondition into a JSON compatible object
  51911. * @returns serialization object
  51912. */
  51913. StateCondition.prototype.serialize = function () {
  51914. return this._serialize({
  51915. name: "StateCondition",
  51916. properties: [
  51917. BABYLON.Action._GetTargetProperty(this._target),
  51918. { name: "value", value: this.value }
  51919. ]
  51920. });
  51921. };
  51922. return StateCondition;
  51923. }(Condition));
  51924. BABYLON.StateCondition = StateCondition;
  51925. })(BABYLON || (BABYLON = {}));
  51926. //# sourceMappingURL=babylon.condition.js.map
  51927. var BABYLON;
  51928. (function (BABYLON) {
  51929. /**
  51930. * The action to be carried out following a trigger
  51931. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51932. */
  51933. var Action = /** @class */ (function () {
  51934. /**
  51935. * Creates a new Action
  51936. * @param triggerOptions the trigger, with or without parameters, for the action
  51937. * @param condition an optional determinant of action
  51938. */
  51939. function Action(
  51940. /** the trigger, with or without parameters, for the action */
  51941. triggerOptions, condition) {
  51942. this.triggerOptions = triggerOptions;
  51943. /**
  51944. * An event triggered prior to action being executed.
  51945. */
  51946. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51947. if (triggerOptions.parameter) {
  51948. this.trigger = triggerOptions.trigger;
  51949. this._triggerParameter = triggerOptions.parameter;
  51950. }
  51951. else {
  51952. this.trigger = triggerOptions;
  51953. }
  51954. this._nextActiveAction = this;
  51955. this._condition = condition;
  51956. }
  51957. /**
  51958. * Internal only
  51959. * @hidden
  51960. */
  51961. Action.prototype._prepare = function () {
  51962. };
  51963. /**
  51964. * Gets the trigger parameters
  51965. * @returns the trigger parameters
  51966. */
  51967. Action.prototype.getTriggerParameter = function () {
  51968. return this._triggerParameter;
  51969. };
  51970. /**
  51971. * Internal only - executes current action event
  51972. * @hidden
  51973. */
  51974. Action.prototype._executeCurrent = function (evt) {
  51975. if (this._nextActiveAction._condition) {
  51976. var condition = this._nextActiveAction._condition;
  51977. var currentRenderId = this._actionManager.getScene().getRenderId();
  51978. // We cache the current evaluation for the current frame
  51979. if (condition._evaluationId === currentRenderId) {
  51980. if (!condition._currentResult) {
  51981. return;
  51982. }
  51983. }
  51984. else {
  51985. condition._evaluationId = currentRenderId;
  51986. if (!condition.isValid()) {
  51987. condition._currentResult = false;
  51988. return;
  51989. }
  51990. condition._currentResult = true;
  51991. }
  51992. }
  51993. this.onBeforeExecuteObservable.notifyObservers(this);
  51994. this._nextActiveAction.execute(evt);
  51995. this.skipToNextActiveAction();
  51996. };
  51997. /**
  51998. * Execute placeholder for child classes
  51999. * @param evt optional action event
  52000. */
  52001. Action.prototype.execute = function (evt) {
  52002. };
  52003. /**
  52004. * Skips to next active action
  52005. */
  52006. Action.prototype.skipToNextActiveAction = function () {
  52007. if (this._nextActiveAction._child) {
  52008. if (!this._nextActiveAction._child._actionManager) {
  52009. this._nextActiveAction._child._actionManager = this._actionManager;
  52010. }
  52011. this._nextActiveAction = this._nextActiveAction._child;
  52012. }
  52013. else {
  52014. this._nextActiveAction = this;
  52015. }
  52016. };
  52017. /**
  52018. * Adds action to chain of actions, may be a DoNothingAction
  52019. * @param action defines the next action to execute
  52020. * @returns The action passed in
  52021. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52022. */
  52023. Action.prototype.then = function (action) {
  52024. this._child = action;
  52025. action._actionManager = this._actionManager;
  52026. action._prepare();
  52027. return action;
  52028. };
  52029. /**
  52030. * Internal only
  52031. * @hidden
  52032. */
  52033. Action.prototype._getProperty = function (propertyPath) {
  52034. return this._actionManager._getProperty(propertyPath);
  52035. };
  52036. /**
  52037. * Internal only
  52038. * @hidden
  52039. */
  52040. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52041. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52042. };
  52043. /**
  52044. * Serialize placeholder for child classes
  52045. * @param parent of child
  52046. * @returns the serialized object
  52047. */
  52048. Action.prototype.serialize = function (parent) {
  52049. };
  52050. /**
  52051. * Internal only called by serialize
  52052. * @hidden
  52053. */
  52054. Action.prototype._serialize = function (serializedAction, parent) {
  52055. var serializationObject = {
  52056. type: 1,
  52057. children: [],
  52058. name: serializedAction.name,
  52059. properties: serializedAction.properties || []
  52060. };
  52061. // Serialize child
  52062. if (this._child) {
  52063. this._child.serialize(serializationObject);
  52064. }
  52065. // Check if "this" has a condition
  52066. if (this._condition) {
  52067. var serializedCondition = this._condition.serialize();
  52068. serializedCondition.children.push(serializationObject);
  52069. if (parent) {
  52070. parent.children.push(serializedCondition);
  52071. }
  52072. return serializedCondition;
  52073. }
  52074. if (parent) {
  52075. parent.children.push(serializationObject);
  52076. }
  52077. return serializationObject;
  52078. };
  52079. /**
  52080. * Internal only
  52081. * @hidden
  52082. */
  52083. Action._SerializeValueAsString = function (value) {
  52084. if (typeof value === "number") {
  52085. return value.toString();
  52086. }
  52087. if (typeof value === "boolean") {
  52088. return value ? "true" : "false";
  52089. }
  52090. if (value instanceof BABYLON.Vector2) {
  52091. return value.x + ", " + value.y;
  52092. }
  52093. if (value instanceof BABYLON.Vector3) {
  52094. return value.x + ", " + value.y + ", " + value.z;
  52095. }
  52096. if (value instanceof BABYLON.Color3) {
  52097. return value.r + ", " + value.g + ", " + value.b;
  52098. }
  52099. if (value instanceof BABYLON.Color4) {
  52100. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52101. }
  52102. return value; // string
  52103. };
  52104. /**
  52105. * Internal only
  52106. * @hidden
  52107. */
  52108. Action._GetTargetProperty = function (target) {
  52109. return {
  52110. name: "target",
  52111. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52112. : target instanceof BABYLON.Light ? "LightProperties"
  52113. : target instanceof BABYLON.Camera ? "CameraProperties"
  52114. : "SceneProperties",
  52115. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52116. };
  52117. };
  52118. return Action;
  52119. }());
  52120. BABYLON.Action = Action;
  52121. })(BABYLON || (BABYLON = {}));
  52122. //# sourceMappingURL=babylon.action.js.map
  52123. var BABYLON;
  52124. (function (BABYLON) {
  52125. /**
  52126. * ActionEvent is the event being sent when an action is triggered.
  52127. */
  52128. var ActionEvent = /** @class */ (function () {
  52129. /**
  52130. * Creates a new ActionEvent
  52131. * @param source The mesh or sprite that triggered the action
  52132. * @param pointerX The X mouse cursor position at the time of the event
  52133. * @param pointerY The Y mouse cursor position at the time of the event
  52134. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52135. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52136. * @param additionalData additional data for the event
  52137. */
  52138. function ActionEvent(
  52139. /** The mesh or sprite that triggered the action */
  52140. source,
  52141. /** The X mouse cursor position at the time of the event */
  52142. pointerX,
  52143. /** The Y mouse cursor position at the time of the event */
  52144. pointerY,
  52145. /** The mesh that is currently pointed at (can be null) */
  52146. meshUnderPointer,
  52147. /** the original (browser) event that triggered the ActionEvent */
  52148. sourceEvent,
  52149. /** additional data for the event */
  52150. additionalData) {
  52151. this.source = source;
  52152. this.pointerX = pointerX;
  52153. this.pointerY = pointerY;
  52154. this.meshUnderPointer = meshUnderPointer;
  52155. this.sourceEvent = sourceEvent;
  52156. this.additionalData = additionalData;
  52157. }
  52158. /**
  52159. * Helper function to auto-create an ActionEvent from a source mesh.
  52160. * @param source The source mesh that triggered the event
  52161. * @param evt The original (browser) event
  52162. * @param additionalData additional data for the event
  52163. * @returns the new ActionEvent
  52164. */
  52165. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52166. var scene = source.getScene();
  52167. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52168. };
  52169. /**
  52170. * Helper function to auto-create an ActionEvent from a source sprite
  52171. * @param source The source sprite that triggered the event
  52172. * @param scene Scene associated with the sprite
  52173. * @param evt The original (browser) event
  52174. * @param additionalData additional data for the event
  52175. * @returns the new ActionEvent
  52176. */
  52177. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52178. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52179. };
  52180. /**
  52181. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52182. * @param scene the scene where the event occurred
  52183. * @param evt The original (browser) event
  52184. * @returns the new ActionEvent
  52185. */
  52186. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52187. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52188. };
  52189. /**
  52190. * Helper function to auto-create an ActionEvent from a primitive
  52191. * @param prim defines the target primitive
  52192. * @param pointerPos defines the pointer position
  52193. * @param evt The original (browser) event
  52194. * @param additionalData additional data for the event
  52195. * @returns the new ActionEvent
  52196. */
  52197. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52198. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52199. };
  52200. return ActionEvent;
  52201. }());
  52202. BABYLON.ActionEvent = ActionEvent;
  52203. /**
  52204. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52205. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52206. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52207. */
  52208. var ActionManager = /** @class */ (function () {
  52209. /**
  52210. * Creates a new action manager
  52211. * @param scene defines the hosting scene
  52212. */
  52213. function ActionManager(scene) {
  52214. // Members
  52215. /** Gets the list of actions */
  52216. this.actions = new Array();
  52217. /** Gets the cursor to use when hovering items */
  52218. this.hoverCursor = '';
  52219. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52220. scene._actionManagers.push(this);
  52221. }
  52222. Object.defineProperty(ActionManager, "NothingTrigger", {
  52223. /**
  52224. * Nothing
  52225. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52226. */
  52227. get: function () {
  52228. return ActionManager._NothingTrigger;
  52229. },
  52230. enumerable: true,
  52231. configurable: true
  52232. });
  52233. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52234. /**
  52235. * On pick
  52236. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52237. */
  52238. get: function () {
  52239. return ActionManager._OnPickTrigger;
  52240. },
  52241. enumerable: true,
  52242. configurable: true
  52243. });
  52244. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52245. /**
  52246. * On left pick
  52247. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52248. */
  52249. get: function () {
  52250. return ActionManager._OnLeftPickTrigger;
  52251. },
  52252. enumerable: true,
  52253. configurable: true
  52254. });
  52255. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52256. /**
  52257. * On right pick
  52258. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52259. */
  52260. get: function () {
  52261. return ActionManager._OnRightPickTrigger;
  52262. },
  52263. enumerable: true,
  52264. configurable: true
  52265. });
  52266. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52267. /**
  52268. * On center pick
  52269. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52270. */
  52271. get: function () {
  52272. return ActionManager._OnCenterPickTrigger;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52278. /**
  52279. * On pick down
  52280. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52281. */
  52282. get: function () {
  52283. return ActionManager._OnPickDownTrigger;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52289. /**
  52290. * On double pick
  52291. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52292. */
  52293. get: function () {
  52294. return ActionManager._OnDoublePickTrigger;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52300. /**
  52301. * On pick up
  52302. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52303. */
  52304. get: function () {
  52305. return ActionManager._OnPickUpTrigger;
  52306. },
  52307. enumerable: true,
  52308. configurable: true
  52309. });
  52310. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52311. /**
  52312. * On pick out.
  52313. * This trigger will only be raised if you also declared a OnPickDown
  52314. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52315. */
  52316. get: function () {
  52317. return ActionManager._OnPickOutTrigger;
  52318. },
  52319. enumerable: true,
  52320. configurable: true
  52321. });
  52322. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52323. /**
  52324. * On long press
  52325. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52326. */
  52327. get: function () {
  52328. return ActionManager._OnLongPressTrigger;
  52329. },
  52330. enumerable: true,
  52331. configurable: true
  52332. });
  52333. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52334. /**
  52335. * On pointer over
  52336. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52337. */
  52338. get: function () {
  52339. return ActionManager._OnPointerOverTrigger;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52345. /**
  52346. * On pointer out
  52347. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52348. */
  52349. get: function () {
  52350. return ActionManager._OnPointerOutTrigger;
  52351. },
  52352. enumerable: true,
  52353. configurable: true
  52354. });
  52355. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52356. /**
  52357. * On every frame
  52358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52359. */
  52360. get: function () {
  52361. return ActionManager._OnEveryFrameTrigger;
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52367. /**
  52368. * On intersection enter
  52369. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52370. */
  52371. get: function () {
  52372. return ActionManager._OnIntersectionEnterTrigger;
  52373. },
  52374. enumerable: true,
  52375. configurable: true
  52376. });
  52377. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52378. /**
  52379. * On intersection exit
  52380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52381. */
  52382. get: function () {
  52383. return ActionManager._OnIntersectionExitTrigger;
  52384. },
  52385. enumerable: true,
  52386. configurable: true
  52387. });
  52388. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52389. /**
  52390. * On key down
  52391. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52392. */
  52393. get: function () {
  52394. return ActionManager._OnKeyDownTrigger;
  52395. },
  52396. enumerable: true,
  52397. configurable: true
  52398. });
  52399. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52400. /**
  52401. * On key up
  52402. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52403. */
  52404. get: function () {
  52405. return ActionManager._OnKeyUpTrigger;
  52406. },
  52407. enumerable: true,
  52408. configurable: true
  52409. });
  52410. // Methods
  52411. /**
  52412. * Releases all associated resources
  52413. */
  52414. ActionManager.prototype.dispose = function () {
  52415. var index = this._scene._actionManagers.indexOf(this);
  52416. for (var i = 0; i < this.actions.length; i++) {
  52417. var action = this.actions[i];
  52418. ActionManager.Triggers[action.trigger]--;
  52419. if (ActionManager.Triggers[action.trigger] === 0) {
  52420. delete ActionManager.Triggers[action.trigger];
  52421. }
  52422. }
  52423. if (index > -1) {
  52424. this._scene._actionManagers.splice(index, 1);
  52425. }
  52426. };
  52427. /**
  52428. * Gets hosting scene
  52429. * @returns the hosting scene
  52430. */
  52431. ActionManager.prototype.getScene = function () {
  52432. return this._scene;
  52433. };
  52434. /**
  52435. * Does this action manager handles actions of any of the given triggers
  52436. * @param triggers defines the triggers to be tested
  52437. * @return a boolean indicating whether one (or more) of the triggers is handled
  52438. */
  52439. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52440. for (var index = 0; index < this.actions.length; index++) {
  52441. var action = this.actions[index];
  52442. if (triggers.indexOf(action.trigger) > -1) {
  52443. return true;
  52444. }
  52445. }
  52446. return false;
  52447. };
  52448. /**
  52449. * Does this action manager handles actions of a given trigger
  52450. * @param trigger defines the trigger to be tested
  52451. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52452. * @return whether the trigger is handled
  52453. */
  52454. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52455. for (var index = 0; index < this.actions.length; index++) {
  52456. var action = this.actions[index];
  52457. if (action.trigger === trigger) {
  52458. if (parameterPredicate) {
  52459. if (parameterPredicate(action.getTriggerParameter())) {
  52460. return true;
  52461. }
  52462. }
  52463. else {
  52464. return true;
  52465. }
  52466. }
  52467. }
  52468. return false;
  52469. };
  52470. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52471. /**
  52472. * Does this action manager has pointer triggers
  52473. */
  52474. get: function () {
  52475. for (var index = 0; index < this.actions.length; index++) {
  52476. var action = this.actions[index];
  52477. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52478. return true;
  52479. }
  52480. }
  52481. return false;
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52487. /**
  52488. * Does this action manager has pick triggers
  52489. */
  52490. get: function () {
  52491. for (var index = 0; index < this.actions.length; index++) {
  52492. var action = this.actions[index];
  52493. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52494. return true;
  52495. }
  52496. }
  52497. return false;
  52498. },
  52499. enumerable: true,
  52500. configurable: true
  52501. });
  52502. Object.defineProperty(ActionManager, "HasTriggers", {
  52503. /**
  52504. * Does exist one action manager with at least one trigger
  52505. **/
  52506. get: function () {
  52507. for (var t in ActionManager.Triggers) {
  52508. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52509. return true;
  52510. }
  52511. }
  52512. return false;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52518. /**
  52519. * Does exist one action manager with at least one pick trigger
  52520. **/
  52521. get: function () {
  52522. for (var t in ActionManager.Triggers) {
  52523. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52524. var t_int = parseInt(t);
  52525. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52526. return true;
  52527. }
  52528. }
  52529. }
  52530. return false;
  52531. },
  52532. enumerable: true,
  52533. configurable: true
  52534. });
  52535. /**
  52536. * Does exist one action manager that handles actions of a given trigger
  52537. * @param trigger defines the trigger to be tested
  52538. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52539. **/
  52540. ActionManager.HasSpecificTrigger = function (trigger) {
  52541. for (var t in ActionManager.Triggers) {
  52542. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52543. var t_int = parseInt(t);
  52544. if (t_int === trigger) {
  52545. return true;
  52546. }
  52547. }
  52548. }
  52549. return false;
  52550. };
  52551. /**
  52552. * Registers an action to this action manager
  52553. * @param action defines the action to be registered
  52554. * @return the action amended (prepared) after registration
  52555. */
  52556. ActionManager.prototype.registerAction = function (action) {
  52557. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52558. if (this.getScene().actionManager !== this) {
  52559. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52560. return null;
  52561. }
  52562. }
  52563. this.actions.push(action);
  52564. if (ActionManager.Triggers[action.trigger]) {
  52565. ActionManager.Triggers[action.trigger]++;
  52566. }
  52567. else {
  52568. ActionManager.Triggers[action.trigger] = 1;
  52569. }
  52570. action._actionManager = this;
  52571. action._prepare();
  52572. return action;
  52573. };
  52574. /**
  52575. * Unregisters an action to this action manager
  52576. * @param action defines the action to be unregistered
  52577. * @return a boolean indicating whether the action has been unregistered
  52578. */
  52579. ActionManager.prototype.unregisterAction = function (action) {
  52580. var index = this.actions.indexOf(action);
  52581. if (index !== -1) {
  52582. this.actions.splice(index, 1);
  52583. ActionManager.Triggers[action.trigger] -= 1;
  52584. if (ActionManager.Triggers[action.trigger] === 0) {
  52585. delete ActionManager.Triggers[action.trigger];
  52586. }
  52587. delete action._actionManager;
  52588. return true;
  52589. }
  52590. return false;
  52591. };
  52592. /**
  52593. * Process a specific trigger
  52594. * @param trigger defines the trigger to process
  52595. * @param evt defines the event details to be processed
  52596. */
  52597. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52598. for (var index = 0; index < this.actions.length; index++) {
  52599. var action = this.actions[index];
  52600. if (action.trigger === trigger) {
  52601. if (evt) {
  52602. if (trigger === ActionManager.OnKeyUpTrigger
  52603. || trigger === ActionManager.OnKeyDownTrigger) {
  52604. var parameter = action.getTriggerParameter();
  52605. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52606. if (!parameter.toLowerCase) {
  52607. continue;
  52608. }
  52609. var lowerCase = parameter.toLowerCase();
  52610. if (lowerCase !== evt.sourceEvent.key) {
  52611. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52612. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52613. if (actualkey !== lowerCase) {
  52614. continue;
  52615. }
  52616. }
  52617. }
  52618. }
  52619. }
  52620. action._executeCurrent(evt);
  52621. }
  52622. }
  52623. };
  52624. /** @hidden */
  52625. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52626. var properties = propertyPath.split(".");
  52627. for (var index = 0; index < properties.length - 1; index++) {
  52628. target = target[properties[index]];
  52629. }
  52630. return target;
  52631. };
  52632. /** @hidden */
  52633. ActionManager.prototype._getProperty = function (propertyPath) {
  52634. var properties = propertyPath.split(".");
  52635. return properties[properties.length - 1];
  52636. };
  52637. /**
  52638. * Serialize this manager to a JSON object
  52639. * @param name defines the property name to store this manager
  52640. * @returns a JSON representation of this manager
  52641. */
  52642. ActionManager.prototype.serialize = function (name) {
  52643. var root = {
  52644. children: new Array(),
  52645. name: name,
  52646. type: 3,
  52647. properties: new Array() // Empty for root but required
  52648. };
  52649. for (var i = 0; i < this.actions.length; i++) {
  52650. var triggerObject = {
  52651. type: 0,
  52652. children: new Array(),
  52653. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52654. properties: new Array()
  52655. };
  52656. var triggerOptions = this.actions[i].triggerOptions;
  52657. if (triggerOptions && typeof triggerOptions !== "number") {
  52658. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52659. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52660. }
  52661. else {
  52662. var parameter = {};
  52663. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52664. if (triggerOptions.parameter.mesh) {
  52665. parameter._meshId = triggerOptions.parameter.mesh.id;
  52666. }
  52667. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52668. }
  52669. }
  52670. // Serialize child action, recursively
  52671. this.actions[i].serialize(triggerObject);
  52672. // Add serialized trigger
  52673. root.children.push(triggerObject);
  52674. }
  52675. return root;
  52676. };
  52677. /**
  52678. * Creates a new ActionManager from a JSON data
  52679. * @param parsedActions defines the JSON data to read from
  52680. * @param object defines the hosting mesh
  52681. * @param scene defines the hosting scene
  52682. */
  52683. ActionManager.Parse = function (parsedActions, object, scene) {
  52684. var actionManager = new ActionManager(scene);
  52685. if (object === null)
  52686. scene.actionManager = actionManager;
  52687. else
  52688. object.actionManager = actionManager;
  52689. // instanciate a new object
  52690. var instanciate = function (name, params) {
  52691. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52692. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52693. newInstance.constructor.apply(newInstance, params);
  52694. return newInstance;
  52695. };
  52696. var parseParameter = function (name, value, target, propertyPath) {
  52697. if (propertyPath === null) {
  52698. // String, boolean or float
  52699. var floatValue = parseFloat(value);
  52700. if (value === "true" || value === "false")
  52701. return value === "true";
  52702. else
  52703. return isNaN(floatValue) ? value : floatValue;
  52704. }
  52705. var effectiveTarget = propertyPath.split(".");
  52706. var values = value.split(",");
  52707. // Get effective Target
  52708. for (var i = 0; i < effectiveTarget.length; i++) {
  52709. target = target[effectiveTarget[i]];
  52710. }
  52711. // Return appropriate value with its type
  52712. if (typeof (target) === "boolean")
  52713. return values[0] === "true";
  52714. if (typeof (target) === "string")
  52715. return values[0];
  52716. // Parameters with multiple values such as Vector3 etc.
  52717. var split = new Array();
  52718. for (var i = 0; i < values.length; i++)
  52719. split.push(parseFloat(values[i]));
  52720. if (target instanceof BABYLON.Vector3)
  52721. return BABYLON.Vector3.FromArray(split);
  52722. if (target instanceof BABYLON.Vector4)
  52723. return BABYLON.Vector4.FromArray(split);
  52724. if (target instanceof BABYLON.Color3)
  52725. return BABYLON.Color3.FromArray(split);
  52726. if (target instanceof BABYLON.Color4)
  52727. return BABYLON.Color4.FromArray(split);
  52728. return parseFloat(values[0]);
  52729. };
  52730. // traverse graph per trigger
  52731. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52732. if (combineArray === void 0) { combineArray = null; }
  52733. if (parsedAction.detached)
  52734. return;
  52735. var parameters = new Array();
  52736. var target = null;
  52737. var propertyPath = null;
  52738. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52739. // Parameters
  52740. if (parsedAction.type === 2)
  52741. parameters.push(actionManager);
  52742. else
  52743. parameters.push(trigger);
  52744. if (combine) {
  52745. var actions = new Array();
  52746. for (var j = 0; j < parsedAction.combine.length; j++) {
  52747. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52748. }
  52749. parameters.push(actions);
  52750. }
  52751. else {
  52752. for (var i = 0; i < parsedAction.properties.length; i++) {
  52753. var value = parsedAction.properties[i].value;
  52754. var name = parsedAction.properties[i].name;
  52755. var targetType = parsedAction.properties[i].targetType;
  52756. if (name === "target")
  52757. if (targetType !== null && targetType === "SceneProperties")
  52758. value = target = scene;
  52759. else
  52760. value = target = scene.getNodeByName(value);
  52761. else if (name === "parent")
  52762. value = scene.getNodeByName(value);
  52763. else if (name === "sound")
  52764. value = scene.getSoundByName(value);
  52765. else if (name !== "propertyPath") {
  52766. if (parsedAction.type === 2 && name === "operator")
  52767. value = BABYLON.ValueCondition[value];
  52768. else
  52769. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52770. }
  52771. else {
  52772. propertyPath = value;
  52773. }
  52774. parameters.push(value);
  52775. }
  52776. }
  52777. if (combineArray === null) {
  52778. parameters.push(condition);
  52779. }
  52780. else {
  52781. parameters.push(null);
  52782. }
  52783. // If interpolate value action
  52784. if (parsedAction.name === "InterpolateValueAction") {
  52785. var param = parameters[parameters.length - 2];
  52786. parameters[parameters.length - 1] = param;
  52787. parameters[parameters.length - 2] = condition;
  52788. }
  52789. // Action or condition(s) and not CombineAction
  52790. var newAction = instanciate(parsedAction.name, parameters);
  52791. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52792. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52793. if (action)
  52794. action.then(nothing);
  52795. else
  52796. actionManager.registerAction(nothing);
  52797. action = nothing;
  52798. }
  52799. if (combineArray === null) {
  52800. if (newAction instanceof BABYLON.Condition) {
  52801. condition = newAction;
  52802. newAction = action;
  52803. }
  52804. else {
  52805. condition = null;
  52806. if (action)
  52807. action.then(newAction);
  52808. else
  52809. actionManager.registerAction(newAction);
  52810. }
  52811. }
  52812. else {
  52813. combineArray.push(newAction);
  52814. }
  52815. for (var i = 0; i < parsedAction.children.length; i++)
  52816. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52817. };
  52818. // triggers
  52819. for (var i = 0; i < parsedActions.children.length; i++) {
  52820. var triggerParams;
  52821. var trigger = parsedActions.children[i];
  52822. if (trigger.properties.length > 0) {
  52823. var param = trigger.properties[0].value;
  52824. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52825. if (value._meshId) {
  52826. value.mesh = scene.getMeshByID(value._meshId);
  52827. }
  52828. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52829. }
  52830. else
  52831. triggerParams = ActionManager[trigger.name];
  52832. for (var j = 0; j < trigger.children.length; j++) {
  52833. if (!trigger.detached)
  52834. traverse(trigger.children[j], triggerParams, null, null);
  52835. }
  52836. }
  52837. };
  52838. /**
  52839. * Get a trigger name by index
  52840. * @param trigger defines the trigger index
  52841. * @returns a trigger name
  52842. */
  52843. ActionManager.GetTriggerName = function (trigger) {
  52844. switch (trigger) {
  52845. case 0: return "NothingTrigger";
  52846. case 1: return "OnPickTrigger";
  52847. case 2: return "OnLeftPickTrigger";
  52848. case 3: return "OnRightPickTrigger";
  52849. case 4: return "OnCenterPickTrigger";
  52850. case 5: return "OnPickDownTrigger";
  52851. case 6: return "OnPickUpTrigger";
  52852. case 7: return "OnLongPressTrigger";
  52853. case 8: return "OnPointerOverTrigger";
  52854. case 9: return "OnPointerOutTrigger";
  52855. case 10: return "OnEveryFrameTrigger";
  52856. case 11: return "OnIntersectionEnterTrigger";
  52857. case 12: return "OnIntersectionExitTrigger";
  52858. case 13: return "OnKeyDownTrigger";
  52859. case 14: return "OnKeyUpTrigger";
  52860. case 15: return "OnPickOutTrigger";
  52861. default: return "";
  52862. }
  52863. };
  52864. // Statics
  52865. ActionManager._NothingTrigger = 0;
  52866. ActionManager._OnPickTrigger = 1;
  52867. ActionManager._OnLeftPickTrigger = 2;
  52868. ActionManager._OnRightPickTrigger = 3;
  52869. ActionManager._OnCenterPickTrigger = 4;
  52870. ActionManager._OnPickDownTrigger = 5;
  52871. ActionManager._OnDoublePickTrigger = 6;
  52872. ActionManager._OnPickUpTrigger = 7;
  52873. ActionManager._OnLongPressTrigger = 8;
  52874. ActionManager._OnPointerOverTrigger = 9;
  52875. ActionManager._OnPointerOutTrigger = 10;
  52876. ActionManager._OnEveryFrameTrigger = 11;
  52877. ActionManager._OnIntersectionEnterTrigger = 12;
  52878. ActionManager._OnIntersectionExitTrigger = 13;
  52879. ActionManager._OnKeyDownTrigger = 14;
  52880. ActionManager._OnKeyUpTrigger = 15;
  52881. ActionManager._OnPickOutTrigger = 16;
  52882. /** Gets the list of active triggers */
  52883. ActionManager.Triggers = {};
  52884. return ActionManager;
  52885. }());
  52886. BABYLON.ActionManager = ActionManager;
  52887. })(BABYLON || (BABYLON = {}));
  52888. //# sourceMappingURL=babylon.actionManager.js.map
  52889. var BABYLON;
  52890. (function (BABYLON) {
  52891. var InterpolateValueAction = /** @class */ (function (_super) {
  52892. __extends(InterpolateValueAction, _super);
  52893. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52894. if (duration === void 0) { duration = 1000; }
  52895. var _this = _super.call(this, triggerOptions, condition) || this;
  52896. _this.propertyPath = propertyPath;
  52897. _this.value = value;
  52898. _this.duration = duration;
  52899. _this.stopOtherAnimations = stopOtherAnimations;
  52900. _this.onInterpolationDone = onInterpolationDone;
  52901. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52902. _this._target = _this._effectiveTarget = target;
  52903. return _this;
  52904. }
  52905. InterpolateValueAction.prototype._prepare = function () {
  52906. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52907. this._property = this._getProperty(this.propertyPath);
  52908. };
  52909. InterpolateValueAction.prototype.execute = function () {
  52910. var _this = this;
  52911. var scene = this._actionManager.getScene();
  52912. var keys = [
  52913. {
  52914. frame: 0,
  52915. value: this._effectiveTarget[this._property]
  52916. }, {
  52917. frame: 100,
  52918. value: this.value
  52919. }
  52920. ];
  52921. var dataType;
  52922. if (typeof this.value === "number") {
  52923. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52924. }
  52925. else if (this.value instanceof BABYLON.Color3) {
  52926. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52927. }
  52928. else if (this.value instanceof BABYLON.Vector3) {
  52929. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52930. }
  52931. else if (this.value instanceof BABYLON.Matrix) {
  52932. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52933. }
  52934. else if (this.value instanceof BABYLON.Quaternion) {
  52935. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52936. }
  52937. else {
  52938. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52939. return;
  52940. }
  52941. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52942. animation.setKeys(keys);
  52943. if (this.stopOtherAnimations) {
  52944. scene.stopAnimation(this._effectiveTarget);
  52945. }
  52946. var wrapper = function () {
  52947. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52948. if (_this.onInterpolationDone) {
  52949. _this.onInterpolationDone();
  52950. }
  52951. };
  52952. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52953. };
  52954. InterpolateValueAction.prototype.serialize = function (parent) {
  52955. return _super.prototype._serialize.call(this, {
  52956. name: "InterpolateValueAction",
  52957. properties: [
  52958. BABYLON.Action._GetTargetProperty(this._target),
  52959. { name: "propertyPath", value: this.propertyPath },
  52960. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52961. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52962. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52963. ]
  52964. }, parent);
  52965. };
  52966. return InterpolateValueAction;
  52967. }(BABYLON.Action));
  52968. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52969. })(BABYLON || (BABYLON = {}));
  52970. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52971. var BABYLON;
  52972. (function (BABYLON) {
  52973. var SwitchBooleanAction = /** @class */ (function (_super) {
  52974. __extends(SwitchBooleanAction, _super);
  52975. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52976. var _this = _super.call(this, triggerOptions, condition) || this;
  52977. _this.propertyPath = propertyPath;
  52978. _this._target = _this._effectiveTarget = target;
  52979. return _this;
  52980. }
  52981. SwitchBooleanAction.prototype._prepare = function () {
  52982. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52983. this._property = this._getProperty(this.propertyPath);
  52984. };
  52985. SwitchBooleanAction.prototype.execute = function () {
  52986. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52987. };
  52988. SwitchBooleanAction.prototype.serialize = function (parent) {
  52989. return _super.prototype._serialize.call(this, {
  52990. name: "SwitchBooleanAction",
  52991. properties: [
  52992. BABYLON.Action._GetTargetProperty(this._target),
  52993. { name: "propertyPath", value: this.propertyPath }
  52994. ]
  52995. }, parent);
  52996. };
  52997. return SwitchBooleanAction;
  52998. }(BABYLON.Action));
  52999. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53000. var SetStateAction = /** @class */ (function (_super) {
  53001. __extends(SetStateAction, _super);
  53002. function SetStateAction(triggerOptions, target, value, condition) {
  53003. var _this = _super.call(this, triggerOptions, condition) || this;
  53004. _this.value = value;
  53005. _this._target = target;
  53006. return _this;
  53007. }
  53008. SetStateAction.prototype.execute = function () {
  53009. this._target.state = this.value;
  53010. };
  53011. SetStateAction.prototype.serialize = function (parent) {
  53012. return _super.prototype._serialize.call(this, {
  53013. name: "SetStateAction",
  53014. properties: [
  53015. BABYLON.Action._GetTargetProperty(this._target),
  53016. { name: "value", value: this.value }
  53017. ]
  53018. }, parent);
  53019. };
  53020. return SetStateAction;
  53021. }(BABYLON.Action));
  53022. BABYLON.SetStateAction = SetStateAction;
  53023. var SetValueAction = /** @class */ (function (_super) {
  53024. __extends(SetValueAction, _super);
  53025. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53026. var _this = _super.call(this, triggerOptions, condition) || this;
  53027. _this.propertyPath = propertyPath;
  53028. _this.value = value;
  53029. _this._target = _this._effectiveTarget = target;
  53030. return _this;
  53031. }
  53032. SetValueAction.prototype._prepare = function () {
  53033. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53034. this._property = this._getProperty(this.propertyPath);
  53035. };
  53036. SetValueAction.prototype.execute = function () {
  53037. this._effectiveTarget[this._property] = this.value;
  53038. if (this._target.markAsDirty) {
  53039. this._target.markAsDirty(this._property);
  53040. }
  53041. };
  53042. SetValueAction.prototype.serialize = function (parent) {
  53043. return _super.prototype._serialize.call(this, {
  53044. name: "SetValueAction",
  53045. properties: [
  53046. BABYLON.Action._GetTargetProperty(this._target),
  53047. { name: "propertyPath", value: this.propertyPath },
  53048. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53049. ]
  53050. }, parent);
  53051. };
  53052. return SetValueAction;
  53053. }(BABYLON.Action));
  53054. BABYLON.SetValueAction = SetValueAction;
  53055. var IncrementValueAction = /** @class */ (function (_super) {
  53056. __extends(IncrementValueAction, _super);
  53057. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53058. var _this = _super.call(this, triggerOptions, condition) || this;
  53059. _this.propertyPath = propertyPath;
  53060. _this.value = value;
  53061. _this._target = _this._effectiveTarget = target;
  53062. return _this;
  53063. }
  53064. IncrementValueAction.prototype._prepare = function () {
  53065. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53066. this._property = this._getProperty(this.propertyPath);
  53067. if (typeof this._effectiveTarget[this._property] !== "number") {
  53068. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53069. }
  53070. };
  53071. IncrementValueAction.prototype.execute = function () {
  53072. this._effectiveTarget[this._property] += this.value;
  53073. if (this._target.markAsDirty) {
  53074. this._target.markAsDirty(this._property);
  53075. }
  53076. };
  53077. IncrementValueAction.prototype.serialize = function (parent) {
  53078. return _super.prototype._serialize.call(this, {
  53079. name: "IncrementValueAction",
  53080. properties: [
  53081. BABYLON.Action._GetTargetProperty(this._target),
  53082. { name: "propertyPath", value: this.propertyPath },
  53083. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53084. ]
  53085. }, parent);
  53086. };
  53087. return IncrementValueAction;
  53088. }(BABYLON.Action));
  53089. BABYLON.IncrementValueAction = IncrementValueAction;
  53090. var PlayAnimationAction = /** @class */ (function (_super) {
  53091. __extends(PlayAnimationAction, _super);
  53092. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53093. var _this = _super.call(this, triggerOptions, condition) || this;
  53094. _this.from = from;
  53095. _this.to = to;
  53096. _this.loop = loop;
  53097. _this._target = target;
  53098. return _this;
  53099. }
  53100. PlayAnimationAction.prototype._prepare = function () {
  53101. };
  53102. PlayAnimationAction.prototype.execute = function () {
  53103. var scene = this._actionManager.getScene();
  53104. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53105. };
  53106. PlayAnimationAction.prototype.serialize = function (parent) {
  53107. return _super.prototype._serialize.call(this, {
  53108. name: "PlayAnimationAction",
  53109. properties: [
  53110. BABYLON.Action._GetTargetProperty(this._target),
  53111. { name: "from", value: String(this.from) },
  53112. { name: "to", value: String(this.to) },
  53113. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53114. ]
  53115. }, parent);
  53116. };
  53117. return PlayAnimationAction;
  53118. }(BABYLON.Action));
  53119. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53120. var StopAnimationAction = /** @class */ (function (_super) {
  53121. __extends(StopAnimationAction, _super);
  53122. function StopAnimationAction(triggerOptions, target, condition) {
  53123. var _this = _super.call(this, triggerOptions, condition) || this;
  53124. _this._target = target;
  53125. return _this;
  53126. }
  53127. StopAnimationAction.prototype._prepare = function () {
  53128. };
  53129. StopAnimationAction.prototype.execute = function () {
  53130. var scene = this._actionManager.getScene();
  53131. scene.stopAnimation(this._target);
  53132. };
  53133. StopAnimationAction.prototype.serialize = function (parent) {
  53134. return _super.prototype._serialize.call(this, {
  53135. name: "StopAnimationAction",
  53136. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53137. }, parent);
  53138. };
  53139. return StopAnimationAction;
  53140. }(BABYLON.Action));
  53141. BABYLON.StopAnimationAction = StopAnimationAction;
  53142. var DoNothingAction = /** @class */ (function (_super) {
  53143. __extends(DoNothingAction, _super);
  53144. function DoNothingAction(triggerOptions, condition) {
  53145. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53146. return _super.call(this, triggerOptions, condition) || this;
  53147. }
  53148. DoNothingAction.prototype.execute = function () {
  53149. };
  53150. DoNothingAction.prototype.serialize = function (parent) {
  53151. return _super.prototype._serialize.call(this, {
  53152. name: "DoNothingAction",
  53153. properties: []
  53154. }, parent);
  53155. };
  53156. return DoNothingAction;
  53157. }(BABYLON.Action));
  53158. BABYLON.DoNothingAction = DoNothingAction;
  53159. var CombineAction = /** @class */ (function (_super) {
  53160. __extends(CombineAction, _super);
  53161. function CombineAction(triggerOptions, children, condition) {
  53162. var _this = _super.call(this, triggerOptions, condition) || this;
  53163. _this.children = children;
  53164. return _this;
  53165. }
  53166. CombineAction.prototype._prepare = function () {
  53167. for (var index = 0; index < this.children.length; index++) {
  53168. this.children[index]._actionManager = this._actionManager;
  53169. this.children[index]._prepare();
  53170. }
  53171. };
  53172. CombineAction.prototype.execute = function (evt) {
  53173. for (var index = 0; index < this.children.length; index++) {
  53174. this.children[index].execute(evt);
  53175. }
  53176. };
  53177. CombineAction.prototype.serialize = function (parent) {
  53178. var serializationObject = _super.prototype._serialize.call(this, {
  53179. name: "CombineAction",
  53180. properties: [],
  53181. combine: []
  53182. }, parent);
  53183. for (var i = 0; i < this.children.length; i++) {
  53184. serializationObject.combine.push(this.children[i].serialize(null));
  53185. }
  53186. return serializationObject;
  53187. };
  53188. return CombineAction;
  53189. }(BABYLON.Action));
  53190. BABYLON.CombineAction = CombineAction;
  53191. var ExecuteCodeAction = /** @class */ (function (_super) {
  53192. __extends(ExecuteCodeAction, _super);
  53193. function ExecuteCodeAction(triggerOptions, func, condition) {
  53194. var _this = _super.call(this, triggerOptions, condition) || this;
  53195. _this.func = func;
  53196. return _this;
  53197. }
  53198. ExecuteCodeAction.prototype.execute = function (evt) {
  53199. this.func(evt);
  53200. };
  53201. return ExecuteCodeAction;
  53202. }(BABYLON.Action));
  53203. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53204. var SetParentAction = /** @class */ (function (_super) {
  53205. __extends(SetParentAction, _super);
  53206. function SetParentAction(triggerOptions, target, parent, condition) {
  53207. var _this = _super.call(this, triggerOptions, condition) || this;
  53208. _this._target = target;
  53209. _this._parent = parent;
  53210. return _this;
  53211. }
  53212. SetParentAction.prototype._prepare = function () {
  53213. };
  53214. SetParentAction.prototype.execute = function () {
  53215. if (this._target.parent === this._parent) {
  53216. return;
  53217. }
  53218. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53219. invertParentWorldMatrix.invert();
  53220. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53221. this._target.parent = this._parent;
  53222. };
  53223. SetParentAction.prototype.serialize = function (parent) {
  53224. return _super.prototype._serialize.call(this, {
  53225. name: "SetParentAction",
  53226. properties: [
  53227. BABYLON.Action._GetTargetProperty(this._target),
  53228. BABYLON.Action._GetTargetProperty(this._parent),
  53229. ]
  53230. }, parent);
  53231. };
  53232. return SetParentAction;
  53233. }(BABYLON.Action));
  53234. BABYLON.SetParentAction = SetParentAction;
  53235. var PlaySoundAction = /** @class */ (function (_super) {
  53236. __extends(PlaySoundAction, _super);
  53237. function PlaySoundAction(triggerOptions, sound, condition) {
  53238. var _this = _super.call(this, triggerOptions, condition) || this;
  53239. _this._sound = sound;
  53240. return _this;
  53241. }
  53242. PlaySoundAction.prototype._prepare = function () {
  53243. };
  53244. PlaySoundAction.prototype.execute = function () {
  53245. if (this._sound !== undefined)
  53246. this._sound.play();
  53247. };
  53248. PlaySoundAction.prototype.serialize = function (parent) {
  53249. return _super.prototype._serialize.call(this, {
  53250. name: "PlaySoundAction",
  53251. properties: [{ name: "sound", value: this._sound.name }]
  53252. }, parent);
  53253. };
  53254. return PlaySoundAction;
  53255. }(BABYLON.Action));
  53256. BABYLON.PlaySoundAction = PlaySoundAction;
  53257. var StopSoundAction = /** @class */ (function (_super) {
  53258. __extends(StopSoundAction, _super);
  53259. function StopSoundAction(triggerOptions, sound, condition) {
  53260. var _this = _super.call(this, triggerOptions, condition) || this;
  53261. _this._sound = sound;
  53262. return _this;
  53263. }
  53264. StopSoundAction.prototype._prepare = function () {
  53265. };
  53266. StopSoundAction.prototype.execute = function () {
  53267. if (this._sound !== undefined)
  53268. this._sound.stop();
  53269. };
  53270. StopSoundAction.prototype.serialize = function (parent) {
  53271. return _super.prototype._serialize.call(this, {
  53272. name: "StopSoundAction",
  53273. properties: [{ name: "sound", value: this._sound.name }]
  53274. }, parent);
  53275. };
  53276. return StopSoundAction;
  53277. }(BABYLON.Action));
  53278. BABYLON.StopSoundAction = StopSoundAction;
  53279. })(BABYLON || (BABYLON = {}));
  53280. //# sourceMappingURL=babylon.directActions.js.map
  53281. var BABYLON;
  53282. (function (BABYLON) {
  53283. var SpriteManager = /** @class */ (function () {
  53284. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53285. if (epsilon === void 0) { epsilon = 0.01; }
  53286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53287. this.name = name;
  53288. this.sprites = new Array();
  53289. this.renderingGroupId = 0;
  53290. this.layerMask = 0x0FFFFFFF;
  53291. this.fogEnabled = true;
  53292. this.isPickable = false;
  53293. /**
  53294. * An event triggered when the manager is disposed.
  53295. */
  53296. this.onDisposeObservable = new BABYLON.Observable();
  53297. this._vertexBuffers = {};
  53298. this._capacity = capacity;
  53299. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53300. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53301. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53302. if (cellSize.width && cellSize.height) {
  53303. this.cellWidth = cellSize.width;
  53304. this.cellHeight = cellSize.height;
  53305. }
  53306. else if (cellSize !== undefined) {
  53307. this.cellWidth = cellSize;
  53308. this.cellHeight = cellSize;
  53309. }
  53310. else {
  53311. return;
  53312. }
  53313. this._epsilon = epsilon;
  53314. this._scene = scene;
  53315. this._scene.spriteManagers.push(this);
  53316. var indices = [];
  53317. var index = 0;
  53318. for (var count = 0; count < capacity; count++) {
  53319. indices.push(index);
  53320. indices.push(index + 1);
  53321. indices.push(index + 2);
  53322. indices.push(index);
  53323. indices.push(index + 2);
  53324. indices.push(index + 3);
  53325. index += 4;
  53326. }
  53327. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53328. // VBO
  53329. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53330. this._vertexData = new Float32Array(capacity * 16 * 4);
  53331. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53332. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53333. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53334. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53335. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53336. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53337. this._vertexBuffers["options"] = options;
  53338. this._vertexBuffers["cellInfo"] = cellInfo;
  53339. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53340. // Effects
  53341. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53342. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53343. }
  53344. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53345. set: function (callback) {
  53346. if (this._onDisposeObserver) {
  53347. this.onDisposeObservable.remove(this._onDisposeObserver);
  53348. }
  53349. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53350. },
  53351. enumerable: true,
  53352. configurable: true
  53353. });
  53354. Object.defineProperty(SpriteManager.prototype, "texture", {
  53355. get: function () {
  53356. return this._spriteTexture;
  53357. },
  53358. set: function (value) {
  53359. this._spriteTexture = value;
  53360. },
  53361. enumerable: true,
  53362. configurable: true
  53363. });
  53364. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53365. var arrayOffset = index * 16;
  53366. if (offsetX === 0)
  53367. offsetX = this._epsilon;
  53368. else if (offsetX === 1)
  53369. offsetX = 1 - this._epsilon;
  53370. if (offsetY === 0)
  53371. offsetY = this._epsilon;
  53372. else if (offsetY === 1)
  53373. offsetY = 1 - this._epsilon;
  53374. this._vertexData[arrayOffset] = sprite.position.x;
  53375. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53376. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53377. this._vertexData[arrayOffset + 3] = sprite.angle;
  53378. this._vertexData[arrayOffset + 4] = sprite.width;
  53379. this._vertexData[arrayOffset + 5] = sprite.height;
  53380. this._vertexData[arrayOffset + 6] = offsetX;
  53381. this._vertexData[arrayOffset + 7] = offsetY;
  53382. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53383. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53384. var offset = (sprite.cellIndex / rowSize) >> 0;
  53385. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53386. this._vertexData[arrayOffset + 11] = offset;
  53387. // Color
  53388. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53389. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53390. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53391. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53392. };
  53393. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53394. var count = Math.min(this._capacity, this.sprites.length);
  53395. var min = BABYLON.Vector3.Zero();
  53396. var max = BABYLON.Vector3.Zero();
  53397. var distance = Number.MAX_VALUE;
  53398. var currentSprite = null;
  53399. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53400. var cameraView = camera.getViewMatrix();
  53401. for (var index = 0; index < count; index++) {
  53402. var sprite = this.sprites[index];
  53403. if (!sprite) {
  53404. continue;
  53405. }
  53406. if (predicate) {
  53407. if (!predicate(sprite)) {
  53408. continue;
  53409. }
  53410. }
  53411. else if (!sprite.isPickable) {
  53412. continue;
  53413. }
  53414. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53415. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53416. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53417. if (ray.intersectsBoxMinMax(min, max)) {
  53418. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53419. if (distance > currentDistance) {
  53420. distance = currentDistance;
  53421. currentSprite = sprite;
  53422. if (fastCheck) {
  53423. break;
  53424. }
  53425. }
  53426. }
  53427. }
  53428. if (currentSprite) {
  53429. var result = new BABYLON.PickingInfo();
  53430. result.hit = true;
  53431. result.pickedSprite = currentSprite;
  53432. result.distance = distance;
  53433. return result;
  53434. }
  53435. return null;
  53436. };
  53437. SpriteManager.prototype.render = function () {
  53438. // Check
  53439. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53440. return;
  53441. var engine = this._scene.getEngine();
  53442. var baseSize = this._spriteTexture.getBaseSize();
  53443. // Sprites
  53444. var deltaTime = engine.getDeltaTime();
  53445. var max = Math.min(this._capacity, this.sprites.length);
  53446. var rowSize = baseSize.width / this.cellWidth;
  53447. var offset = 0;
  53448. for (var index = 0; index < max; index++) {
  53449. var sprite = this.sprites[index];
  53450. if (!sprite || !sprite.isVisible) {
  53451. continue;
  53452. }
  53453. sprite._animate(deltaTime);
  53454. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53455. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53456. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53457. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53458. }
  53459. this._buffer.update(this._vertexData);
  53460. // Render
  53461. var effect = this._effectBase;
  53462. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53463. effect = this._effectFog;
  53464. }
  53465. engine.enableEffect(effect);
  53466. var viewMatrix = this._scene.getViewMatrix();
  53467. effect.setTexture("diffuseSampler", this._spriteTexture);
  53468. effect.setMatrix("view", viewMatrix);
  53469. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53470. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53471. // Fog
  53472. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53473. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53474. effect.setColor3("vFogColor", this._scene.fogColor);
  53475. }
  53476. // VBOs
  53477. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53478. // Draw order
  53479. engine.setDepthFunctionToLessOrEqual();
  53480. effect.setBool("alphaTest", true);
  53481. engine.setColorWrite(false);
  53482. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53483. engine.setColorWrite(true);
  53484. effect.setBool("alphaTest", false);
  53485. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53486. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53487. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53488. };
  53489. SpriteManager.prototype.dispose = function () {
  53490. if (this._buffer) {
  53491. this._buffer.dispose();
  53492. this._buffer = null;
  53493. }
  53494. if (this._indexBuffer) {
  53495. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53496. this._indexBuffer = null;
  53497. }
  53498. if (this._spriteTexture) {
  53499. this._spriteTexture.dispose();
  53500. this._spriteTexture = null;
  53501. }
  53502. // Remove from scene
  53503. var index = this._scene.spriteManagers.indexOf(this);
  53504. this._scene.spriteManagers.splice(index, 1);
  53505. // Callback
  53506. this.onDisposeObservable.notifyObservers(this);
  53507. this.onDisposeObservable.clear();
  53508. };
  53509. return SpriteManager;
  53510. }());
  53511. BABYLON.SpriteManager = SpriteManager;
  53512. })(BABYLON || (BABYLON = {}));
  53513. //# sourceMappingURL=babylon.spriteManager.js.map
  53514. var BABYLON;
  53515. (function (BABYLON) {
  53516. var Sprite = /** @class */ (function () {
  53517. function Sprite(name, manager) {
  53518. this.name = name;
  53519. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53520. this.width = 1.0;
  53521. this.height = 1.0;
  53522. this.angle = 0;
  53523. this.cellIndex = 0;
  53524. this.invertU = 0;
  53525. this.invertV = 0;
  53526. this.animations = new Array();
  53527. this.isPickable = false;
  53528. this._animationStarted = false;
  53529. this._loopAnimation = false;
  53530. this._fromIndex = 0;
  53531. this._toIndex = 0;
  53532. this._delay = 0;
  53533. this._direction = 1;
  53534. this._time = 0;
  53535. /**
  53536. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53537. */
  53538. this.isVisible = true;
  53539. this._manager = manager;
  53540. this._manager.sprites.push(this);
  53541. this.position = BABYLON.Vector3.Zero();
  53542. }
  53543. Object.defineProperty(Sprite.prototype, "size", {
  53544. get: function () {
  53545. return this.width;
  53546. },
  53547. set: function (value) {
  53548. this.width = value;
  53549. this.height = value;
  53550. },
  53551. enumerable: true,
  53552. configurable: true
  53553. });
  53554. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53555. this._fromIndex = from;
  53556. this._toIndex = to;
  53557. this._loopAnimation = loop;
  53558. this._delay = delay;
  53559. this._animationStarted = true;
  53560. this._direction = from < to ? 1 : -1;
  53561. this.cellIndex = from;
  53562. this._time = 0;
  53563. this._onAnimationEnd = onAnimationEnd;
  53564. };
  53565. Sprite.prototype.stopAnimation = function () {
  53566. this._animationStarted = false;
  53567. };
  53568. Sprite.prototype._animate = function (deltaTime) {
  53569. if (!this._animationStarted)
  53570. return;
  53571. this._time += deltaTime;
  53572. if (this._time > this._delay) {
  53573. this._time = this._time % this._delay;
  53574. this.cellIndex += this._direction;
  53575. if (this.cellIndex > this._toIndex) {
  53576. if (this._loopAnimation) {
  53577. this.cellIndex = this._fromIndex;
  53578. }
  53579. else {
  53580. this.cellIndex = this._toIndex;
  53581. this._animationStarted = false;
  53582. if (this._onAnimationEnd) {
  53583. this._onAnimationEnd();
  53584. }
  53585. if (this.disposeWhenFinishedAnimating) {
  53586. this.dispose();
  53587. }
  53588. }
  53589. }
  53590. }
  53591. };
  53592. Sprite.prototype.dispose = function () {
  53593. for (var i = 0; i < this._manager.sprites.length; i++) {
  53594. if (this._manager.sprites[i] == this) {
  53595. this._manager.sprites.splice(i, 1);
  53596. }
  53597. }
  53598. };
  53599. return Sprite;
  53600. }());
  53601. BABYLON.Sprite = Sprite;
  53602. })(BABYLON || (BABYLON = {}));
  53603. //# sourceMappingURL=babylon.sprite.js.map
  53604. var BABYLON;
  53605. (function (BABYLON) {
  53606. var IntersectionInfo = /** @class */ (function () {
  53607. function IntersectionInfo(bu, bv, distance) {
  53608. this.bu = bu;
  53609. this.bv = bv;
  53610. this.distance = distance;
  53611. this.faceId = 0;
  53612. this.subMeshId = 0;
  53613. }
  53614. return IntersectionInfo;
  53615. }());
  53616. BABYLON.IntersectionInfo = IntersectionInfo;
  53617. /**
  53618. * Information about the result of picking within a scene
  53619. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53620. */
  53621. var PickingInfo = /** @class */ (function () {
  53622. function PickingInfo() {
  53623. /**
  53624. * If the pick collided with an object
  53625. */
  53626. this.hit = false;
  53627. /**
  53628. * Distance away where the pick collided
  53629. */
  53630. this.distance = 0;
  53631. /**
  53632. * The location of pick collision
  53633. */
  53634. this.pickedPoint = null;
  53635. /**
  53636. * The mesh corrisponding the the pick collision
  53637. */
  53638. this.pickedMesh = null;
  53639. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53640. this.bu = 0;
  53641. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53642. this.bv = 0;
  53643. /** The id of the face on the mesh that was picked */
  53644. this.faceId = -1;
  53645. /** Id of the the submesh that was picked */
  53646. this.subMeshId = 0;
  53647. /** If a sprite was picked, this will be the sprite the pick collided with */
  53648. this.pickedSprite = null;
  53649. /**
  53650. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53651. */
  53652. this.originMesh = null;
  53653. /**
  53654. * The ray that was used to perform the picking.
  53655. */
  53656. this.ray = null;
  53657. }
  53658. /**
  53659. * Gets the normal corrispodning to the face the pick collided with
  53660. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53661. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53662. * @returns The normal corrispodning to the face the pick collided with
  53663. */
  53664. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53665. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53666. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53667. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53668. return null;
  53669. }
  53670. var indices = this.pickedMesh.getIndices();
  53671. if (!indices) {
  53672. return null;
  53673. }
  53674. var result;
  53675. if (useVerticesNormals) {
  53676. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53677. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53678. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53679. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53680. normal0 = normal0.scale(this.bu);
  53681. normal1 = normal1.scale(this.bv);
  53682. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53683. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53684. }
  53685. else {
  53686. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53687. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53688. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53689. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53690. var p1p2 = vertex1.subtract(vertex2);
  53691. var p3p2 = vertex3.subtract(vertex2);
  53692. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53693. }
  53694. if (useWorldCoordinates) {
  53695. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53696. }
  53697. return BABYLON.Vector3.Normalize(result);
  53698. };
  53699. /**
  53700. * Gets the texture coordinates of where the pick occured
  53701. * @returns the vector containing the coordnates of the texture
  53702. */
  53703. PickingInfo.prototype.getTextureCoordinates = function () {
  53704. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53705. return null;
  53706. }
  53707. var indices = this.pickedMesh.getIndices();
  53708. if (!indices) {
  53709. return null;
  53710. }
  53711. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53712. if (!uvs) {
  53713. return null;
  53714. }
  53715. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53716. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53717. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53718. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53719. uv1 = uv1.scale(this.bu);
  53720. uv2 = uv2.scale(this.bv);
  53721. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53722. };
  53723. return PickingInfo;
  53724. }());
  53725. BABYLON.PickingInfo = PickingInfo;
  53726. })(BABYLON || (BABYLON = {}));
  53727. //# sourceMappingURL=babylon.pickingInfo.js.map
  53728. var BABYLON;
  53729. (function (BABYLON) {
  53730. var Ray = /** @class */ (function () {
  53731. function Ray(origin, direction, length) {
  53732. if (length === void 0) { length = Number.MAX_VALUE; }
  53733. this.origin = origin;
  53734. this.direction = direction;
  53735. this.length = length;
  53736. }
  53737. // Methods
  53738. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53739. var d = 0.0;
  53740. var maxValue = Number.MAX_VALUE;
  53741. var inv;
  53742. var min;
  53743. var max;
  53744. var temp;
  53745. if (Math.abs(this.direction.x) < 0.0000001) {
  53746. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53747. return false;
  53748. }
  53749. }
  53750. else {
  53751. inv = 1.0 / this.direction.x;
  53752. min = (minimum.x - this.origin.x) * inv;
  53753. max = (maximum.x - this.origin.x) * inv;
  53754. if (max === -Infinity) {
  53755. max = Infinity;
  53756. }
  53757. if (min > max) {
  53758. temp = min;
  53759. min = max;
  53760. max = temp;
  53761. }
  53762. d = Math.max(min, d);
  53763. maxValue = Math.min(max, maxValue);
  53764. if (d > maxValue) {
  53765. return false;
  53766. }
  53767. }
  53768. if (Math.abs(this.direction.y) < 0.0000001) {
  53769. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53770. return false;
  53771. }
  53772. }
  53773. else {
  53774. inv = 1.0 / this.direction.y;
  53775. min = (minimum.y - this.origin.y) * inv;
  53776. max = (maximum.y - this.origin.y) * inv;
  53777. if (max === -Infinity) {
  53778. max = Infinity;
  53779. }
  53780. if (min > max) {
  53781. temp = min;
  53782. min = max;
  53783. max = temp;
  53784. }
  53785. d = Math.max(min, d);
  53786. maxValue = Math.min(max, maxValue);
  53787. if (d > maxValue) {
  53788. return false;
  53789. }
  53790. }
  53791. if (Math.abs(this.direction.z) < 0.0000001) {
  53792. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53793. return false;
  53794. }
  53795. }
  53796. else {
  53797. inv = 1.0 / this.direction.z;
  53798. min = (minimum.z - this.origin.z) * inv;
  53799. max = (maximum.z - this.origin.z) * inv;
  53800. if (max === -Infinity) {
  53801. max = Infinity;
  53802. }
  53803. if (min > max) {
  53804. temp = min;
  53805. min = max;
  53806. max = temp;
  53807. }
  53808. d = Math.max(min, d);
  53809. maxValue = Math.min(max, maxValue);
  53810. if (d > maxValue) {
  53811. return false;
  53812. }
  53813. }
  53814. return true;
  53815. };
  53816. Ray.prototype.intersectsBox = function (box) {
  53817. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53818. };
  53819. Ray.prototype.intersectsSphere = function (sphere) {
  53820. var x = sphere.center.x - this.origin.x;
  53821. var y = sphere.center.y - this.origin.y;
  53822. var z = sphere.center.z - this.origin.z;
  53823. var pyth = (x * x) + (y * y) + (z * z);
  53824. var rr = sphere.radius * sphere.radius;
  53825. if (pyth <= rr) {
  53826. return true;
  53827. }
  53828. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53829. if (dot < 0.0) {
  53830. return false;
  53831. }
  53832. var temp = pyth - (dot * dot);
  53833. return temp <= rr;
  53834. };
  53835. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53836. if (!this._edge1) {
  53837. this._edge1 = BABYLON.Vector3.Zero();
  53838. this._edge2 = BABYLON.Vector3.Zero();
  53839. this._pvec = BABYLON.Vector3.Zero();
  53840. this._tvec = BABYLON.Vector3.Zero();
  53841. this._qvec = BABYLON.Vector3.Zero();
  53842. }
  53843. vertex1.subtractToRef(vertex0, this._edge1);
  53844. vertex2.subtractToRef(vertex0, this._edge2);
  53845. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53846. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53847. if (det === 0) {
  53848. return null;
  53849. }
  53850. var invdet = 1 / det;
  53851. this.origin.subtractToRef(vertex0, this._tvec);
  53852. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53853. if (bu < 0 || bu > 1.0) {
  53854. return null;
  53855. }
  53856. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53857. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53858. if (bv < 0 || bu + bv > 1.0) {
  53859. return null;
  53860. }
  53861. //check if the distance is longer than the predefined length.
  53862. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53863. if (distance > this.length) {
  53864. return null;
  53865. }
  53866. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53867. };
  53868. Ray.prototype.intersectsPlane = function (plane) {
  53869. var distance;
  53870. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53871. if (Math.abs(result1) < 9.99999997475243E-07) {
  53872. return null;
  53873. }
  53874. else {
  53875. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53876. distance = (-plane.d - result2) / result1;
  53877. if (distance < 0.0) {
  53878. if (distance < -9.99999997475243E-07) {
  53879. return null;
  53880. }
  53881. else {
  53882. return 0;
  53883. }
  53884. }
  53885. return distance;
  53886. }
  53887. };
  53888. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53889. var tm = BABYLON.Tmp.Matrix[0];
  53890. mesh.getWorldMatrix().invertToRef(tm);
  53891. if (this._tmpRay) {
  53892. Ray.TransformToRef(this, tm, this._tmpRay);
  53893. }
  53894. else {
  53895. this._tmpRay = Ray.Transform(this, tm);
  53896. }
  53897. return mesh.intersects(this._tmpRay, fastCheck);
  53898. };
  53899. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53900. if (results) {
  53901. results.length = 0;
  53902. }
  53903. else {
  53904. results = [];
  53905. }
  53906. for (var i = 0; i < meshes.length; i++) {
  53907. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53908. if (pickInfo.hit) {
  53909. results.push(pickInfo);
  53910. }
  53911. }
  53912. results.sort(this._comparePickingInfo);
  53913. return results;
  53914. };
  53915. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53916. if (pickingInfoA.distance < pickingInfoB.distance) {
  53917. return -1;
  53918. }
  53919. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53920. return 1;
  53921. }
  53922. else {
  53923. return 0;
  53924. }
  53925. };
  53926. /**
  53927. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53928. * @param sega the first point of the segment to test the intersection against
  53929. * @param segb the second point of the segment to test the intersection against
  53930. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53931. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53932. */
  53933. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53934. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53935. var u = segb.subtract(sega);
  53936. var v = rsegb.subtract(this.origin);
  53937. var w = sega.subtract(this.origin);
  53938. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53939. var b = BABYLON.Vector3.Dot(u, v);
  53940. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53941. var d = BABYLON.Vector3.Dot(u, w);
  53942. var e = BABYLON.Vector3.Dot(v, w);
  53943. var D = a * c - b * b; // always >= 0
  53944. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53945. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53946. // compute the line parameters of the two closest points
  53947. if (D < Ray.smallnum) { // the lines are almost parallel
  53948. sN = 0.0; // force using point P0 on segment S1
  53949. sD = 1.0; // to prevent possible division by 0.0 later
  53950. tN = e;
  53951. tD = c;
  53952. }
  53953. else { // get the closest points on the infinite lines
  53954. sN = (b * e - c * d);
  53955. tN = (a * e - b * d);
  53956. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53957. sN = 0.0;
  53958. tN = e;
  53959. tD = c;
  53960. }
  53961. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53962. sN = sD;
  53963. tN = e + b;
  53964. tD = c;
  53965. }
  53966. }
  53967. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53968. tN = 0.0;
  53969. // recompute sc for this edge
  53970. if (-d < 0.0) {
  53971. sN = 0.0;
  53972. }
  53973. else if (-d > a)
  53974. sN = sD;
  53975. else {
  53976. sN = -d;
  53977. sD = a;
  53978. }
  53979. }
  53980. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53981. tN = tD;
  53982. // recompute sc for this edge
  53983. if ((-d + b) < 0.0) {
  53984. sN = 0;
  53985. }
  53986. else if ((-d + b) > a) {
  53987. sN = sD;
  53988. }
  53989. else {
  53990. sN = (-d + b);
  53991. sD = a;
  53992. }
  53993. }
  53994. // finally do the division to get sc and tc
  53995. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53996. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53997. // get the difference of the two closest points
  53998. var qtc = v.multiplyByFloats(tc, tc, tc);
  53999. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54000. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54001. if (isIntersected) {
  54002. return qtc.length();
  54003. }
  54004. return -1;
  54005. };
  54006. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54007. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54008. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54009. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54010. this.direction.normalize();
  54011. return this;
  54012. };
  54013. // Statics
  54014. Ray.Zero = function () {
  54015. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54016. };
  54017. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54018. var result = Ray.Zero();
  54019. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54020. };
  54021. /**
  54022. * 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
  54023. * transformed to the given world matrix.
  54024. * @param origin The origin point
  54025. * @param end The end point
  54026. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54027. */
  54028. Ray.CreateNewFromTo = function (origin, end, world) {
  54029. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54030. var direction = end.subtract(origin);
  54031. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54032. direction.normalize();
  54033. return Ray.Transform(new Ray(origin, direction, length), world);
  54034. };
  54035. Ray.Transform = function (ray, matrix) {
  54036. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54037. Ray.TransformToRef(ray, matrix, result);
  54038. return result;
  54039. };
  54040. Ray.TransformToRef = function (ray, matrix, result) {
  54041. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54042. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54043. result.length = ray.length;
  54044. var dir = result.direction;
  54045. var len = dir.length();
  54046. if (!(len === 0 || len === 1)) {
  54047. var num = 1.0 / len;
  54048. dir.x *= num;
  54049. dir.y *= num;
  54050. dir.z *= num;
  54051. result.length *= len;
  54052. }
  54053. };
  54054. Ray.smallnum = 0.00000001;
  54055. Ray.rayl = 10e8;
  54056. return Ray;
  54057. }());
  54058. BABYLON.Ray = Ray;
  54059. })(BABYLON || (BABYLON = {}));
  54060. //# sourceMappingURL=babylon.ray.js.map
  54061. var BABYLON;
  54062. (function (BABYLON) {
  54063. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54064. if (boxMin.x > sphereCenter.x + sphereRadius)
  54065. return false;
  54066. if (sphereCenter.x - sphereRadius > boxMax.x)
  54067. return false;
  54068. if (boxMin.y > sphereCenter.y + sphereRadius)
  54069. return false;
  54070. if (sphereCenter.y - sphereRadius > boxMax.y)
  54071. return false;
  54072. if (boxMin.z > sphereCenter.z + sphereRadius)
  54073. return false;
  54074. if (sphereCenter.z - sphereRadius > boxMax.z)
  54075. return false;
  54076. return true;
  54077. };
  54078. var getLowestRoot = (function () {
  54079. var result = { root: 0, found: false };
  54080. return function (a, b, c, maxR) {
  54081. result.root = 0;
  54082. result.found = false;
  54083. var determinant = b * b - 4.0 * a * c;
  54084. if (determinant < 0)
  54085. return result;
  54086. var sqrtD = Math.sqrt(determinant);
  54087. var r1 = (-b - sqrtD) / (2.0 * a);
  54088. var r2 = (-b + sqrtD) / (2.0 * a);
  54089. if (r1 > r2) {
  54090. var temp = r2;
  54091. r2 = r1;
  54092. r1 = temp;
  54093. }
  54094. if (r1 > 0 && r1 < maxR) {
  54095. result.root = r1;
  54096. result.found = true;
  54097. return result;
  54098. }
  54099. if (r2 > 0 && r2 < maxR) {
  54100. result.root = r2;
  54101. result.found = true;
  54102. return result;
  54103. }
  54104. return result;
  54105. };
  54106. })();
  54107. var Collider = /** @class */ (function () {
  54108. function Collider() {
  54109. this._collisionPoint = BABYLON.Vector3.Zero();
  54110. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54111. this._tempVector = BABYLON.Vector3.Zero();
  54112. this._tempVector2 = BABYLON.Vector3.Zero();
  54113. this._tempVector3 = BABYLON.Vector3.Zero();
  54114. this._tempVector4 = BABYLON.Vector3.Zero();
  54115. this._edge = BABYLON.Vector3.Zero();
  54116. this._baseToVertex = BABYLON.Vector3.Zero();
  54117. this._destinationPoint = BABYLON.Vector3.Zero();
  54118. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54119. this._displacementVector = BABYLON.Vector3.Zero();
  54120. this._radius = BABYLON.Vector3.One();
  54121. this._retry = 0;
  54122. this._basePointWorld = BABYLON.Vector3.Zero();
  54123. this._velocityWorld = BABYLON.Vector3.Zero();
  54124. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54125. this._collisionMask = -1;
  54126. }
  54127. Object.defineProperty(Collider.prototype, "collisionMask", {
  54128. get: function () {
  54129. return this._collisionMask;
  54130. },
  54131. set: function (mask) {
  54132. this._collisionMask = !isNaN(mask) ? mask : -1;
  54133. },
  54134. enumerable: true,
  54135. configurable: true
  54136. });
  54137. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54138. /**
  54139. * Gets the plane normal used to compute the sliding response (in local space)
  54140. */
  54141. get: function () {
  54142. return this._slidePlaneNormal;
  54143. },
  54144. enumerable: true,
  54145. configurable: true
  54146. });
  54147. // Methods
  54148. Collider.prototype._initialize = function (source, dir, e) {
  54149. this._velocity = dir;
  54150. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54151. this._basePoint = source;
  54152. source.multiplyToRef(this._radius, this._basePointWorld);
  54153. dir.multiplyToRef(this._radius, this._velocityWorld);
  54154. this._velocityWorldLength = this._velocityWorld.length();
  54155. this._epsilon = e;
  54156. this.collisionFound = false;
  54157. };
  54158. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54159. pa.subtractToRef(point, this._tempVector);
  54160. pb.subtractToRef(point, this._tempVector2);
  54161. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54162. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54163. if (d < 0)
  54164. return false;
  54165. pc.subtractToRef(point, this._tempVector3);
  54166. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54167. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54168. if (d < 0)
  54169. return false;
  54170. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54171. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54172. return d >= 0;
  54173. };
  54174. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54175. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54176. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54177. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54178. return false;
  54179. }
  54180. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54181. return false;
  54182. return true;
  54183. };
  54184. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54185. var t0;
  54186. var embeddedInPlane = false;
  54187. //defensive programming, actually not needed.
  54188. if (!trianglePlaneArray) {
  54189. trianglePlaneArray = [];
  54190. }
  54191. if (!trianglePlaneArray[faceIndex]) {
  54192. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54193. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54194. }
  54195. var trianglePlane = trianglePlaneArray[faceIndex];
  54196. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54197. return;
  54198. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54199. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54200. if (normalDotVelocity == 0) {
  54201. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54202. return;
  54203. embeddedInPlane = true;
  54204. t0 = 0;
  54205. }
  54206. else {
  54207. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54208. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54209. if (t0 > t1) {
  54210. var temp = t1;
  54211. t1 = t0;
  54212. t0 = temp;
  54213. }
  54214. if (t0 > 1.0 || t1 < 0.0)
  54215. return;
  54216. if (t0 < 0)
  54217. t0 = 0;
  54218. if (t0 > 1.0)
  54219. t0 = 1.0;
  54220. }
  54221. this._collisionPoint.copyFromFloats(0, 0, 0);
  54222. var found = false;
  54223. var t = 1.0;
  54224. if (!embeddedInPlane) {
  54225. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54226. this._velocity.scaleToRef(t0, this._tempVector);
  54227. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54228. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54229. found = true;
  54230. t = t0;
  54231. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54232. }
  54233. }
  54234. if (!found) {
  54235. var velocitySquaredLength = this._velocity.lengthSquared();
  54236. var a = velocitySquaredLength;
  54237. this._basePoint.subtractToRef(p1, this._tempVector);
  54238. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54239. var c = this._tempVector.lengthSquared() - 1.0;
  54240. var lowestRoot = getLowestRoot(a, b, c, t);
  54241. if (lowestRoot.found) {
  54242. t = lowestRoot.root;
  54243. found = true;
  54244. this._collisionPoint.copyFrom(p1);
  54245. }
  54246. this._basePoint.subtractToRef(p2, this._tempVector);
  54247. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54248. c = this._tempVector.lengthSquared() - 1.0;
  54249. lowestRoot = getLowestRoot(a, b, c, t);
  54250. if (lowestRoot.found) {
  54251. t = lowestRoot.root;
  54252. found = true;
  54253. this._collisionPoint.copyFrom(p2);
  54254. }
  54255. this._basePoint.subtractToRef(p3, this._tempVector);
  54256. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54257. c = this._tempVector.lengthSquared() - 1.0;
  54258. lowestRoot = getLowestRoot(a, b, c, t);
  54259. if (lowestRoot.found) {
  54260. t = lowestRoot.root;
  54261. found = true;
  54262. this._collisionPoint.copyFrom(p3);
  54263. }
  54264. p2.subtractToRef(p1, this._edge);
  54265. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54266. var edgeSquaredLength = this._edge.lengthSquared();
  54267. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54268. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54269. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54270. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54271. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54272. lowestRoot = getLowestRoot(a, b, c, t);
  54273. if (lowestRoot.found) {
  54274. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54275. if (f >= 0.0 && f <= 1.0) {
  54276. t = lowestRoot.root;
  54277. found = true;
  54278. this._edge.scaleInPlace(f);
  54279. p1.addToRef(this._edge, this._collisionPoint);
  54280. }
  54281. }
  54282. p3.subtractToRef(p2, this._edge);
  54283. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54284. edgeSquaredLength = this._edge.lengthSquared();
  54285. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54286. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54287. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54288. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54289. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54290. lowestRoot = getLowestRoot(a, b, c, t);
  54291. if (lowestRoot.found) {
  54292. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54293. if (f >= 0.0 && f <= 1.0) {
  54294. t = lowestRoot.root;
  54295. found = true;
  54296. this._edge.scaleInPlace(f);
  54297. p2.addToRef(this._edge, this._collisionPoint);
  54298. }
  54299. }
  54300. p1.subtractToRef(p3, this._edge);
  54301. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54302. edgeSquaredLength = this._edge.lengthSquared();
  54303. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54304. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54305. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54306. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54307. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54308. lowestRoot = getLowestRoot(a, b, c, t);
  54309. if (lowestRoot.found) {
  54310. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54311. if (f >= 0.0 && f <= 1.0) {
  54312. t = lowestRoot.root;
  54313. found = true;
  54314. this._edge.scaleInPlace(f);
  54315. p3.addToRef(this._edge, this._collisionPoint);
  54316. }
  54317. }
  54318. }
  54319. if (found) {
  54320. var distToCollision = t * this._velocity.length();
  54321. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54322. if (!this.intersectionPoint) {
  54323. this.intersectionPoint = this._collisionPoint.clone();
  54324. }
  54325. else {
  54326. this.intersectionPoint.copyFrom(this._collisionPoint);
  54327. }
  54328. this._nearestDistance = distToCollision;
  54329. this.collisionFound = true;
  54330. }
  54331. }
  54332. };
  54333. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54334. for (var i = indexStart; i < indexEnd; i += 3) {
  54335. var p1 = pts[indices[i] - decal];
  54336. var p2 = pts[indices[i + 1] - decal];
  54337. var p3 = pts[indices[i + 2] - decal];
  54338. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54339. }
  54340. };
  54341. Collider.prototype._getResponse = function (pos, vel) {
  54342. pos.addToRef(vel, this._destinationPoint);
  54343. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54344. this._basePoint.addToRef(vel, pos);
  54345. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54346. this._slidePlaneNormal.normalize();
  54347. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54348. pos.addInPlace(this._displacementVector);
  54349. this.intersectionPoint.addInPlace(this._displacementVector);
  54350. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54351. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54352. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54353. };
  54354. return Collider;
  54355. }());
  54356. BABYLON.Collider = Collider;
  54357. })(BABYLON || (BABYLON = {}));
  54358. //# sourceMappingURL=babylon.collider.js.map
  54359. var BABYLON;
  54360. (function (BABYLON) {
  54361. //WebWorker code will be inserted to this variable.
  54362. BABYLON.CollisionWorker = "";
  54363. /** Defines supported task for worker process */
  54364. var WorkerTaskType;
  54365. (function (WorkerTaskType) {
  54366. /** Initialization */
  54367. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54368. /** Update of geometry */
  54369. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54370. /** Evaluate collision */
  54371. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54372. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54373. /** Defines kind of replies returned by worker */
  54374. var WorkerReplyType;
  54375. (function (WorkerReplyType) {
  54376. /** Success */
  54377. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54378. /** Unkown error */
  54379. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54380. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54381. var CollisionCoordinatorWorker = /** @class */ (function () {
  54382. function CollisionCoordinatorWorker() {
  54383. var _this = this;
  54384. this._scaledPosition = BABYLON.Vector3.Zero();
  54385. this._scaledVelocity = BABYLON.Vector3.Zero();
  54386. this.onMeshUpdated = function (transformNode) {
  54387. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54388. };
  54389. this.onGeometryUpdated = function (geometry) {
  54390. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54391. };
  54392. this._afterRender = function () {
  54393. if (!_this._init)
  54394. return;
  54395. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54396. return;
  54397. }
  54398. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54399. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54400. if (_this._runningUpdated > 4) {
  54401. return;
  54402. }
  54403. ++_this._runningUpdated;
  54404. var payload = {
  54405. updatedMeshes: _this._addUpdateMeshesList,
  54406. updatedGeometries: _this._addUpdateGeometriesList,
  54407. removedGeometries: _this._toRemoveGeometryArray,
  54408. removedMeshes: _this._toRemoveMeshesArray
  54409. };
  54410. var message = {
  54411. payload: payload,
  54412. taskType: WorkerTaskType.UPDATE
  54413. };
  54414. var serializable = [];
  54415. for (var id in payload.updatedGeometries) {
  54416. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54417. //prepare transferables
  54418. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54419. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54420. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54421. }
  54422. }
  54423. _this._worker.postMessage(message, serializable);
  54424. _this._addUpdateMeshesList = {};
  54425. _this._addUpdateGeometriesList = {};
  54426. _this._toRemoveGeometryArray = [];
  54427. _this._toRemoveMeshesArray = [];
  54428. };
  54429. this._onMessageFromWorker = function (e) {
  54430. var returnData = e.data;
  54431. if (returnData.error != WorkerReplyType.SUCCESS) {
  54432. //TODO what errors can be returned from the worker?
  54433. BABYLON.Tools.Warn("error returned from worker!");
  54434. return;
  54435. }
  54436. switch (returnData.taskType) {
  54437. case WorkerTaskType.INIT:
  54438. _this._init = true;
  54439. //Update the worked with ALL of the scene's current state
  54440. _this._scene.meshes.forEach(function (mesh) {
  54441. _this.onMeshAdded(mesh);
  54442. });
  54443. _this._scene.getGeometries().forEach(function (geometry) {
  54444. _this.onGeometryAdded(geometry);
  54445. });
  54446. break;
  54447. case WorkerTaskType.UPDATE:
  54448. _this._runningUpdated--;
  54449. break;
  54450. case WorkerTaskType.COLLIDE:
  54451. var returnPayload = returnData.payload;
  54452. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54453. return;
  54454. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54455. if (callback) {
  54456. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54457. if (mesh) {
  54458. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54459. }
  54460. }
  54461. //cleanup
  54462. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54463. break;
  54464. }
  54465. };
  54466. this._collisionsCallbackArray = [];
  54467. this._init = false;
  54468. this._runningUpdated = 0;
  54469. this._addUpdateMeshesList = {};
  54470. this._addUpdateGeometriesList = {};
  54471. this._toRemoveGeometryArray = [];
  54472. this._toRemoveMeshesArray = [];
  54473. }
  54474. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54475. if (!this._init)
  54476. return;
  54477. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54478. return;
  54479. position.divideToRef(collider._radius, this._scaledPosition);
  54480. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54481. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54482. var payload = {
  54483. collider: {
  54484. position: this._scaledPosition.asArray(),
  54485. velocity: this._scaledVelocity.asArray(),
  54486. radius: collider._radius.asArray()
  54487. },
  54488. collisionId: collisionIndex,
  54489. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54490. maximumRetry: maximumRetry
  54491. };
  54492. var message = {
  54493. payload: payload,
  54494. taskType: WorkerTaskType.COLLIDE
  54495. };
  54496. this._worker.postMessage(message);
  54497. };
  54498. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54499. this._scene = scene;
  54500. this._scene.registerAfterRender(this._afterRender);
  54501. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54502. this._worker = new Worker(workerUrl);
  54503. this._worker.onmessage = this._onMessageFromWorker;
  54504. var message = {
  54505. payload: {},
  54506. taskType: WorkerTaskType.INIT
  54507. };
  54508. this._worker.postMessage(message);
  54509. };
  54510. CollisionCoordinatorWorker.prototype.destroy = function () {
  54511. this._scene.unregisterAfterRender(this._afterRender);
  54512. this._worker.terminate();
  54513. };
  54514. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54515. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54516. this.onMeshUpdated(mesh);
  54517. };
  54518. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54519. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54520. };
  54521. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54522. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54523. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54524. this.onGeometryUpdated(geometry);
  54525. };
  54526. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54527. this._toRemoveGeometryArray.push(geometry.id);
  54528. };
  54529. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54530. var submeshes = [];
  54531. if (mesh.subMeshes) {
  54532. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54533. var boundingInfo = sm.getBoundingInfo();
  54534. return {
  54535. position: idx,
  54536. verticesStart: sm.verticesStart,
  54537. verticesCount: sm.verticesCount,
  54538. indexStart: sm.indexStart,
  54539. indexCount: sm.indexCount,
  54540. hasMaterial: !!sm.getMaterial(),
  54541. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54542. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54543. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54544. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54545. };
  54546. });
  54547. }
  54548. var geometryId = null;
  54549. if (mesh instanceof BABYLON.Mesh) {
  54550. var geometry = mesh.geometry;
  54551. geometryId = geometry ? geometry.id : null;
  54552. }
  54553. else if (mesh instanceof BABYLON.InstancedMesh) {
  54554. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54555. geometryId = geometry ? geometry.id : null;
  54556. }
  54557. var boundingInfo = mesh.getBoundingInfo();
  54558. return {
  54559. uniqueId: mesh.uniqueId,
  54560. id: mesh.id,
  54561. name: mesh.name,
  54562. geometryId: geometryId,
  54563. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54564. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54565. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54566. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54567. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54568. subMeshes: submeshes,
  54569. checkCollisions: mesh.checkCollisions
  54570. };
  54571. };
  54572. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54573. return {
  54574. id: geometry.id,
  54575. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54576. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54577. indices: new Uint32Array(geometry.getIndices() || []),
  54578. };
  54579. };
  54580. return CollisionCoordinatorWorker;
  54581. }());
  54582. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54583. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54584. function CollisionCoordinatorLegacy() {
  54585. this._scaledPosition = BABYLON.Vector3.Zero();
  54586. this._scaledVelocity = BABYLON.Vector3.Zero();
  54587. this._finalPosition = BABYLON.Vector3.Zero();
  54588. }
  54589. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54590. position.divideToRef(collider._radius, this._scaledPosition);
  54591. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54592. collider.collidedMesh = null;
  54593. collider._retry = 0;
  54594. collider._initialVelocity = this._scaledVelocity;
  54595. collider._initialPosition = this._scaledPosition;
  54596. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54597. this._finalPosition.multiplyInPlace(collider._radius);
  54598. //run the callback
  54599. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54600. };
  54601. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54602. this._scene = scene;
  54603. };
  54604. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54605. //Legacy need no destruction method.
  54606. };
  54607. //No update in legacy mode
  54608. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54609. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54610. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54611. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54612. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54613. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54614. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54615. if (excludedMesh === void 0) { excludedMesh = null; }
  54616. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54617. if (collider._retry >= maximumRetry) {
  54618. finalPosition.copyFrom(position);
  54619. return;
  54620. }
  54621. // Check if this is a mesh else camera or -1
  54622. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54623. collider._initialize(position, velocity, closeDistance);
  54624. // Check all meshes
  54625. for (var index = 0; index < this._scene.meshes.length; index++) {
  54626. var mesh = this._scene.meshes[index];
  54627. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54628. mesh._checkCollision(collider);
  54629. }
  54630. }
  54631. if (!collider.collisionFound) {
  54632. position.addToRef(velocity, finalPosition);
  54633. return;
  54634. }
  54635. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54636. collider._getResponse(position, velocity);
  54637. }
  54638. if (velocity.length() <= closeDistance) {
  54639. finalPosition.copyFrom(position);
  54640. return;
  54641. }
  54642. collider._retry++;
  54643. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54644. };
  54645. return CollisionCoordinatorLegacy;
  54646. }());
  54647. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54648. })(BABYLON || (BABYLON = {}));
  54649. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54650. var BABYLON;
  54651. (function (BABYLON) {
  54652. /**
  54653. * A particle represents one of the element emitted by a particle system.
  54654. * This is mainly define by its coordinates, direction, velocity and age.
  54655. */
  54656. var Particle = /** @class */ (function () {
  54657. /**
  54658. * Creates a new instance Particle
  54659. * @param particleSystem the particle system the particle belongs to
  54660. */
  54661. function Particle(
  54662. /**
  54663. * particleSystem the particle system the particle belongs to.
  54664. */
  54665. particleSystem) {
  54666. this.particleSystem = particleSystem;
  54667. /**
  54668. * The world position of the particle in the scene.
  54669. */
  54670. this.position = BABYLON.Vector3.Zero();
  54671. /**
  54672. * The world direction of the particle in the scene.
  54673. */
  54674. this.direction = BABYLON.Vector3.Zero();
  54675. /**
  54676. * The color of the particle.
  54677. */
  54678. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54679. /**
  54680. * The color change of the particle per step.
  54681. */
  54682. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54683. /**
  54684. * Defines how long will the life of the particle be.
  54685. */
  54686. this.lifeTime = 1.0;
  54687. /**
  54688. * The current age of the particle.
  54689. */
  54690. this.age = 0;
  54691. /**
  54692. * The current size of the particle.
  54693. */
  54694. this.size = 0;
  54695. /**
  54696. * The current scale of the particle.
  54697. */
  54698. this.scale = new BABYLON.Vector2(1, 1);
  54699. /**
  54700. * The current angle of the particle.
  54701. */
  54702. this.angle = 0;
  54703. /**
  54704. * Defines how fast is the angle changing.
  54705. */
  54706. this.angularSpeed = 0;
  54707. /**
  54708. * Defines the cell index used by the particle to be rendered from a sprite.
  54709. */
  54710. this.cellIndex = 0;
  54711. this._currentFrameCounter = 0;
  54712. if (!this.particleSystem.isAnimationSheetEnabled) {
  54713. return;
  54714. }
  54715. this.updateCellInfoFromSystem();
  54716. }
  54717. Particle.prototype.updateCellInfoFromSystem = function () {
  54718. this.cellIndex = this.particleSystem.startSpriteCellID;
  54719. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54720. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54721. }
  54722. else {
  54723. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54724. }
  54725. };
  54726. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54727. // (ageOffset / scaledUpdateSpeed) / available cells
  54728. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54729. this._currentFrameCounter += scaledUpdateSpeed;
  54730. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54731. this._currentFrameCounter = 0;
  54732. this.cellIndex++;
  54733. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54734. this.cellIndex = this.particleSystem.endSpriteCellID;
  54735. }
  54736. }
  54737. };
  54738. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54739. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54740. this.cellIndex++;
  54741. this._currentFrameCounter = 0;
  54742. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54743. if (this.particleSystem.spriteCellLoop) {
  54744. this.cellIndex = this.particleSystem.startSpriteCellID;
  54745. }
  54746. else {
  54747. this.cellIndex = this.particleSystem.endSpriteCellID;
  54748. }
  54749. }
  54750. }
  54751. else {
  54752. this._currentFrameCounter++;
  54753. }
  54754. };
  54755. /**
  54756. * Copy the properties of particle to another one.
  54757. * @param other the particle to copy the information to.
  54758. */
  54759. Particle.prototype.copyTo = function (other) {
  54760. other.position.copyFrom(this.position);
  54761. other.direction.copyFrom(this.direction);
  54762. other.color.copyFrom(this.color);
  54763. other.colorStep.copyFrom(this.colorStep);
  54764. other.lifeTime = this.lifeTime;
  54765. other.age = this.age;
  54766. other.size = this.size;
  54767. other.scale.copyFrom(this.scale);
  54768. other.angle = this.angle;
  54769. other.angularSpeed = this.angularSpeed;
  54770. other.particleSystem = this.particleSystem;
  54771. other.cellIndex = this.cellIndex;
  54772. };
  54773. return Particle;
  54774. }());
  54775. BABYLON.Particle = Particle;
  54776. })(BABYLON || (BABYLON = {}));
  54777. //# sourceMappingURL=babylon.particle.js.map
  54778. var BABYLON;
  54779. (function (BABYLON) {
  54780. /**
  54781. * This represents a particle system in Babylon.
  54782. * 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.
  54783. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54784. * @example https://doc.babylonjs.com/babylon101/particles
  54785. */
  54786. var ParticleSystem = /** @class */ (function () {
  54787. /**
  54788. * Instantiates a particle system.
  54789. * 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.
  54790. * @param name The name of the particle system
  54791. * @param capacity The max number of particles alive at the same time
  54792. * @param scene The scene the particle system belongs to
  54793. * @param customEffect a custom effect used to change the way particles are rendered by default
  54794. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54795. * @param epsilon Offset used to render the particles
  54796. */
  54797. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54798. if (customEffect === void 0) { customEffect = null; }
  54799. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54800. if (epsilon === void 0) { epsilon = 0.01; }
  54801. var _this = this;
  54802. /**
  54803. * List of animations used by the particle system.
  54804. */
  54805. this.animations = [];
  54806. /**
  54807. * The rendering group used by the Particle system to chose when to render.
  54808. */
  54809. this.renderingGroupId = 0;
  54810. /**
  54811. * The emitter represents the Mesh or position we are attaching the particle system to.
  54812. */
  54813. this.emitter = null;
  54814. /**
  54815. * The maximum number of particles to emit per frame
  54816. */
  54817. this.emitRate = 10;
  54818. /**
  54819. * If you want to launch only a few particles at once, that can be done, as well.
  54820. */
  54821. this.manualEmitCount = -1;
  54822. /**
  54823. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54824. */
  54825. this.updateSpeed = 0.01;
  54826. /**
  54827. * The amount of time the particle system is running (depends of the overall update speed).
  54828. */
  54829. this.targetStopDuration = 0;
  54830. /**
  54831. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54832. */
  54833. this.disposeOnStop = false;
  54834. /**
  54835. * Minimum power of emitting particles.
  54836. */
  54837. this.minEmitPower = 1;
  54838. /**
  54839. * Maximum power of emitting particles.
  54840. */
  54841. this.maxEmitPower = 1;
  54842. /**
  54843. * Minimum life time of emitting particles.
  54844. */
  54845. this.minLifeTime = 1;
  54846. /**
  54847. * Maximum life time of emitting particles.
  54848. */
  54849. this.maxLifeTime = 1;
  54850. /**
  54851. * Minimum Size of emitting particles.
  54852. */
  54853. this.minSize = 1;
  54854. /**
  54855. * Maximum Size of emitting particles.
  54856. */
  54857. this.maxSize = 1;
  54858. /**
  54859. * Minimum scale of emitting particles on X axis.
  54860. */
  54861. this.minScaleX = 1;
  54862. /**
  54863. * Maximum scale of emitting particles on X axis.
  54864. */
  54865. this.maxScaleX = 1;
  54866. /**
  54867. * Minimum scale of emitting particles on Y axis.
  54868. */
  54869. this.minScaleY = 1;
  54870. /**
  54871. * Maximum scale of emitting particles on Y axis.
  54872. */
  54873. this.maxScaleY = 1;
  54874. /**
  54875. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54876. */
  54877. this.minAngularSpeed = 0;
  54878. /**
  54879. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54880. */
  54881. this.maxAngularSpeed = 0;
  54882. /**
  54883. * The layer mask we are rendering the particles through.
  54884. */
  54885. this.layerMask = 0x0FFFFFFF;
  54886. /**
  54887. * This can help using your own shader to render the particle system.
  54888. * The according effect will be created
  54889. */
  54890. this.customShader = null;
  54891. /**
  54892. * By default particle system starts as soon as they are created. This prevents the
  54893. * automatic start to happen and let you decide when to start emitting particles.
  54894. */
  54895. this.preventAutoStart = false;
  54896. /**
  54897. * Callback triggered when the particle animation is ending.
  54898. */
  54899. this.onAnimationEnd = null;
  54900. /**
  54901. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54902. */
  54903. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54904. /**
  54905. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54906. * to override the particles.
  54907. */
  54908. this.forceDepthWrite = false;
  54909. /**
  54910. * You can use gravity if you want to give an orientation to your particles.
  54911. */
  54912. this.gravity = BABYLON.Vector3.Zero();
  54913. /**
  54914. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54915. */
  54916. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54917. /**
  54918. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54919. */
  54920. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54921. /**
  54922. * Color the particle will have at the end of its lifetime.
  54923. */
  54924. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54925. /**
  54926. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54927. */
  54928. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54929. /**
  54930. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54931. */
  54932. this.spriteCellLoop = true;
  54933. /**
  54934. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54935. */
  54936. this.spriteCellChangeSpeed = 0;
  54937. /**
  54938. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54939. */
  54940. this.startSpriteCellID = 0;
  54941. /**
  54942. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54943. */
  54944. this.endSpriteCellID = 0;
  54945. /**
  54946. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54947. */
  54948. this.spriteCellWidth = 0;
  54949. /**
  54950. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54951. */
  54952. this.spriteCellHeight = 0;
  54953. /**
  54954. * An event triggered when the system is disposed.
  54955. */
  54956. this.onDisposeObservable = new BABYLON.Observable();
  54957. this._particles = new Array();
  54958. this._stockParticles = new Array();
  54959. this._newPartsExcess = 0;
  54960. this._vertexBuffers = {};
  54961. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54962. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54963. this._scaledDirection = BABYLON.Vector3.Zero();
  54964. this._scaledGravity = BABYLON.Vector3.Zero();
  54965. this._currentRenderId = -1;
  54966. this._started = false;
  54967. this._stopped = false;
  54968. this._actualFrame = 0;
  54969. this._vertexBufferSize = 12;
  54970. // start of sub system methods
  54971. /**
  54972. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54973. * Its lifetime will start back at 0.
  54974. */
  54975. this.recycleParticle = function (particle) {
  54976. var lastParticle = _this._particles.pop();
  54977. if (lastParticle !== particle) {
  54978. lastParticle.copyTo(particle);
  54979. }
  54980. _this._stockParticles.push(lastParticle);
  54981. };
  54982. this._createParticle = function () {
  54983. var particle;
  54984. if (_this._stockParticles.length !== 0) {
  54985. particle = _this._stockParticles.pop();
  54986. particle.age = 0;
  54987. particle.cellIndex = _this.startSpriteCellID;
  54988. }
  54989. else {
  54990. particle = new BABYLON.Particle(_this);
  54991. }
  54992. return particle;
  54993. };
  54994. this._emitFromParticle = function (particle) {
  54995. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54996. return;
  54997. }
  54998. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54999. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55000. subSystem._rootParticleSystem = _this;
  55001. _this.activeSubSystems.push(subSystem);
  55002. subSystem.start();
  55003. };
  55004. this._appendParticleVertexes = null;
  55005. this.id = name;
  55006. this.name = name;
  55007. this._capacity = capacity;
  55008. this._epsilon = epsilon;
  55009. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55010. if (isAnimationSheetEnabled) {
  55011. this._vertexBufferSize = 13;
  55012. }
  55013. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55014. this._customEffect = customEffect;
  55015. scene.particleSystems.push(this);
  55016. this._createIndexBuffer();
  55017. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  55018. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55019. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55020. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55021. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55022. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  55023. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  55024. if (this._isAnimationSheetEnabled) {
  55025. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  55026. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55027. }
  55028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55029. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55030. this._vertexBuffers["options"] = options;
  55031. this._vertexBuffers["size"] = size;
  55032. // Default emitter type
  55033. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55034. this.updateFunction = function (particles) {
  55035. for (var index = 0; index < particles.length; index++) {
  55036. var particle = particles[index];
  55037. particle.age += _this._scaledUpdateSpeed;
  55038. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55039. _this._emitFromParticle(particle);
  55040. _this.recycleParticle(particle);
  55041. index--;
  55042. continue;
  55043. }
  55044. else {
  55045. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55046. particle.color.addInPlace(_this._scaledColorStep);
  55047. if (particle.color.a < 0)
  55048. particle.color.a = 0;
  55049. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55050. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55051. particle.position.addInPlace(_this._scaledDirection);
  55052. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55053. particle.direction.addInPlace(_this._scaledGravity);
  55054. if (_this._isAnimationSheetEnabled) {
  55055. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55056. }
  55057. }
  55058. }
  55059. };
  55060. }
  55061. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55062. /**
  55063. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55064. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55065. */
  55066. get: function () {
  55067. if (this.particleEmitterType.direction1) {
  55068. return this.particleEmitterType.direction1;
  55069. }
  55070. return BABYLON.Vector3.Zero();
  55071. },
  55072. set: function (value) {
  55073. if (this.particleEmitterType.direction1) {
  55074. this.particleEmitterType.direction1 = value;
  55075. }
  55076. },
  55077. enumerable: true,
  55078. configurable: true
  55079. });
  55080. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55081. /**
  55082. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55083. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55084. */
  55085. get: function () {
  55086. if (this.particleEmitterType.direction2) {
  55087. return this.particleEmitterType.direction2;
  55088. }
  55089. return BABYLON.Vector3.Zero();
  55090. },
  55091. set: function (value) {
  55092. if (this.particleEmitterType.direction2) {
  55093. this.particleEmitterType.direction2 = value;
  55094. }
  55095. },
  55096. enumerable: true,
  55097. configurable: true
  55098. });
  55099. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55100. /**
  55101. * 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.
  55102. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55103. */
  55104. get: function () {
  55105. if (this.particleEmitterType.minEmitBox) {
  55106. return this.particleEmitterType.minEmitBox;
  55107. }
  55108. return BABYLON.Vector3.Zero();
  55109. },
  55110. set: function (value) {
  55111. if (this.particleEmitterType.minEmitBox) {
  55112. this.particleEmitterType.minEmitBox = value;
  55113. }
  55114. },
  55115. enumerable: true,
  55116. configurable: true
  55117. });
  55118. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55119. /**
  55120. * 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.
  55121. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55122. */
  55123. get: function () {
  55124. if (this.particleEmitterType.maxEmitBox) {
  55125. return this.particleEmitterType.maxEmitBox;
  55126. }
  55127. return BABYLON.Vector3.Zero();
  55128. },
  55129. set: function (value) {
  55130. if (this.particleEmitterType.maxEmitBox) {
  55131. this.particleEmitterType.maxEmitBox = value;
  55132. }
  55133. },
  55134. enumerable: true,
  55135. configurable: true
  55136. });
  55137. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55138. /**
  55139. * Sets a callback that will be triggered when the system is disposed.
  55140. */
  55141. set: function (callback) {
  55142. if (this._onDisposeObserver) {
  55143. this.onDisposeObservable.remove(this._onDisposeObserver);
  55144. }
  55145. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55146. },
  55147. enumerable: true,
  55148. configurable: true
  55149. });
  55150. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55151. /**
  55152. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55153. */
  55154. get: function () {
  55155. return this._isAnimationSheetEnabled;
  55156. },
  55157. enumerable: true,
  55158. configurable: true
  55159. });
  55160. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55161. //end of Sub-emitter
  55162. /**
  55163. * Gets the current list of active particles
  55164. */
  55165. get: function () {
  55166. return this._particles;
  55167. },
  55168. enumerable: true,
  55169. configurable: true
  55170. });
  55171. /**
  55172. * Returns the string "ParticleSystem"
  55173. * @returns a string containing the class name
  55174. */
  55175. ParticleSystem.prototype.getClassName = function () {
  55176. return "ParticleSystem";
  55177. };
  55178. ParticleSystem.prototype._createIndexBuffer = function () {
  55179. var indices = [];
  55180. var index = 0;
  55181. for (var count = 0; count < this._capacity; count++) {
  55182. indices.push(index);
  55183. indices.push(index + 1);
  55184. indices.push(index + 2);
  55185. indices.push(index);
  55186. indices.push(index + 2);
  55187. indices.push(index + 3);
  55188. index += 4;
  55189. }
  55190. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55191. };
  55192. /**
  55193. * Gets the maximum number of particles active at the same time.
  55194. * @returns The max number of active particles.
  55195. */
  55196. ParticleSystem.prototype.getCapacity = function () {
  55197. return this._capacity;
  55198. };
  55199. /**
  55200. * Gets Wether there are still active particles in the system.
  55201. * @returns True if it is alive, otherwise false.
  55202. */
  55203. ParticleSystem.prototype.isAlive = function () {
  55204. return this._alive;
  55205. };
  55206. /**
  55207. * Gets Wether the system has been started.
  55208. * @returns True if it has been started, otherwise false.
  55209. */
  55210. ParticleSystem.prototype.isStarted = function () {
  55211. return this._started;
  55212. };
  55213. /**
  55214. * Starts the particle system and begins to emit.
  55215. */
  55216. ParticleSystem.prototype.start = function () {
  55217. this._started = true;
  55218. this._stopped = false;
  55219. this._actualFrame = 0;
  55220. if (this.subEmitters && this.subEmitters.length != 0) {
  55221. this.activeSubSystems = new Array();
  55222. }
  55223. };
  55224. /**
  55225. * Stops the particle system.
  55226. * @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.
  55227. */
  55228. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55229. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55230. this._stopped = true;
  55231. if (stopSubEmitters) {
  55232. this._stopSubEmitters();
  55233. }
  55234. };
  55235. // animation sheet
  55236. /**
  55237. * Remove all active particles
  55238. */
  55239. ParticleSystem.prototype.reset = function () {
  55240. this._stockParticles = [];
  55241. this._particles = [];
  55242. };
  55243. /**
  55244. * @hidden (for internal use only)
  55245. */
  55246. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55247. var offset = index * this._vertexBufferSize;
  55248. this._vertexData[offset] = particle.position.x;
  55249. this._vertexData[offset + 1] = particle.position.y;
  55250. this._vertexData[offset + 2] = particle.position.z;
  55251. this._vertexData[offset + 3] = particle.color.r;
  55252. this._vertexData[offset + 4] = particle.color.g;
  55253. this._vertexData[offset + 5] = particle.color.b;
  55254. this._vertexData[offset + 6] = particle.color.a;
  55255. this._vertexData[offset + 7] = particle.angle;
  55256. this._vertexData[offset + 8] = offsetX;
  55257. this._vertexData[offset + 9] = offsetY;
  55258. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55259. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55260. };
  55261. /**
  55262. * @hidden (for internal use only)
  55263. */
  55264. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55265. if (offsetX === 0)
  55266. offsetX = this._epsilon;
  55267. else if (offsetX === 1)
  55268. offsetX = 1 - this._epsilon;
  55269. if (offsetY === 0)
  55270. offsetY = this._epsilon;
  55271. else if (offsetY === 1)
  55272. offsetY = 1 - this._epsilon;
  55273. var offset = index * this._vertexBufferSize;
  55274. this._vertexData[offset] = particle.position.x;
  55275. this._vertexData[offset + 1] = particle.position.y;
  55276. this._vertexData[offset + 2] = particle.position.z;
  55277. this._vertexData[offset + 3] = particle.color.r;
  55278. this._vertexData[offset + 4] = particle.color.g;
  55279. this._vertexData[offset + 5] = particle.color.b;
  55280. this._vertexData[offset + 6] = particle.color.a;
  55281. this._vertexData[offset + 7] = particle.angle;
  55282. this._vertexData[offset + 8] = offsetX;
  55283. this._vertexData[offset + 9] = offsetY;
  55284. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55285. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55286. this._vertexData[offset + 12] = particle.cellIndex;
  55287. };
  55288. ParticleSystem.prototype._stopSubEmitters = function () {
  55289. if (!this.activeSubSystems) {
  55290. return;
  55291. }
  55292. this.activeSubSystems.forEach(function (subSystem) {
  55293. subSystem.stop(true);
  55294. });
  55295. this.activeSubSystems = new Array();
  55296. };
  55297. ParticleSystem.prototype._removeFromRoot = function () {
  55298. if (!this._rootParticleSystem) {
  55299. return;
  55300. }
  55301. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55302. if (index !== -1) {
  55303. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55304. }
  55305. };
  55306. // end of sub system methods
  55307. ParticleSystem.prototype._update = function (newParticles) {
  55308. // Update current
  55309. this._alive = this._particles.length > 0;
  55310. this.updateFunction(this._particles);
  55311. // Add new ones
  55312. var worldMatrix;
  55313. if (this.emitter.position) {
  55314. var emitterMesh = this.emitter;
  55315. worldMatrix = emitterMesh.getWorldMatrix();
  55316. }
  55317. else {
  55318. var emitterPosition = this.emitter;
  55319. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55320. }
  55321. var particle;
  55322. for (var index = 0; index < newParticles; index++) {
  55323. if (this._particles.length === this._capacity) {
  55324. break;
  55325. }
  55326. particle = this._createParticle();
  55327. this._particles.push(particle);
  55328. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55329. if (this.startPositionFunction) {
  55330. this.startPositionFunction(worldMatrix, particle.position, particle);
  55331. }
  55332. else {
  55333. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55334. }
  55335. if (this.startDirectionFunction) {
  55336. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55337. }
  55338. else {
  55339. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55340. }
  55341. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55342. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55343. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55344. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55345. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55346. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55347. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55348. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55349. }
  55350. };
  55351. ParticleSystem.prototype._getEffect = function () {
  55352. if (this._customEffect) {
  55353. return this._customEffect;
  55354. }
  55355. ;
  55356. var defines = [];
  55357. if (this._scene.clipPlane) {
  55358. defines.push("#define CLIPPLANE");
  55359. }
  55360. if (this._isAnimationSheetEnabled) {
  55361. defines.push("#define ANIMATESHEET");
  55362. }
  55363. // Effect
  55364. var join = defines.join("\n");
  55365. if (this._cachedDefines !== join) {
  55366. this._cachedDefines = join;
  55367. var attributesNamesOrOptions;
  55368. var effectCreationOption;
  55369. if (this._isAnimationSheetEnabled) {
  55370. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  55371. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55372. }
  55373. else {
  55374. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  55375. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55376. }
  55377. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55378. }
  55379. return this._effect;
  55380. };
  55381. /**
  55382. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55383. */
  55384. ParticleSystem.prototype.animate = function () {
  55385. if (!this._started)
  55386. return;
  55387. var effect = this._getEffect();
  55388. // Check
  55389. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55390. return;
  55391. if (this._currentRenderId === this._scene.getRenderId()) {
  55392. return;
  55393. }
  55394. this._currentRenderId = this._scene.getRenderId();
  55395. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55396. // determine the number of particles we need to create
  55397. var newParticles;
  55398. if (this.manualEmitCount > -1) {
  55399. newParticles = this.manualEmitCount;
  55400. this._newPartsExcess = 0;
  55401. this.manualEmitCount = 0;
  55402. }
  55403. else {
  55404. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55405. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55406. }
  55407. if (this._newPartsExcess > 1.0) {
  55408. newParticles += this._newPartsExcess >> 0;
  55409. this._newPartsExcess -= this._newPartsExcess >> 0;
  55410. }
  55411. this._alive = false;
  55412. if (!this._stopped) {
  55413. this._actualFrame += this._scaledUpdateSpeed;
  55414. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55415. this.stop();
  55416. }
  55417. else {
  55418. newParticles = 0;
  55419. }
  55420. this._update(newParticles);
  55421. // Stopped?
  55422. if (this._stopped) {
  55423. if (!this._alive) {
  55424. this._started = false;
  55425. if (this.onAnimationEnd) {
  55426. this.onAnimationEnd();
  55427. }
  55428. if (this.disposeOnStop) {
  55429. this._scene._toBeDisposed.push(this);
  55430. }
  55431. }
  55432. }
  55433. // Animation sheet
  55434. if (this._isAnimationSheetEnabled) {
  55435. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55436. }
  55437. else {
  55438. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55439. }
  55440. // Update VBO
  55441. var offset = 0;
  55442. for (var index = 0; index < this._particles.length; index++) {
  55443. var particle = this._particles[index];
  55444. this._appendParticleVertexes(offset, particle);
  55445. offset += 4;
  55446. }
  55447. if (this._vertexBuffer) {
  55448. this._vertexBuffer.update(this._vertexData);
  55449. }
  55450. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55451. this.stop();
  55452. }
  55453. };
  55454. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55455. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55456. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55457. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55458. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55459. };
  55460. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55461. this._appendParticleVertex(offset++, particle, 0, 0);
  55462. this._appendParticleVertex(offset++, particle, 1, 0);
  55463. this._appendParticleVertex(offset++, particle, 1, 1);
  55464. this._appendParticleVertex(offset++, particle, 0, 1);
  55465. };
  55466. /**
  55467. * Rebuilds the particle system.
  55468. */
  55469. ParticleSystem.prototype.rebuild = function () {
  55470. this._createIndexBuffer();
  55471. if (this._vertexBuffer) {
  55472. this._vertexBuffer._rebuild();
  55473. }
  55474. };
  55475. /**
  55476. * Is this system ready to be used/rendered
  55477. * @return true if the system is ready
  55478. */
  55479. ParticleSystem.prototype.isReady = function () {
  55480. var effect = this._getEffect();
  55481. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55482. return false;
  55483. }
  55484. return true;
  55485. };
  55486. /**
  55487. * Renders the particle system in its current state.
  55488. * @returns the current number of particles
  55489. */
  55490. ParticleSystem.prototype.render = function () {
  55491. var effect = this._getEffect();
  55492. // Check
  55493. if (!this.isReady() || !this._particles.length) {
  55494. return 0;
  55495. }
  55496. var engine = this._scene.getEngine();
  55497. // Render
  55498. engine.enableEffect(effect);
  55499. engine.setState(false);
  55500. var viewMatrix = this._scene.getViewMatrix();
  55501. effect.setTexture("diffuseSampler", this.particleTexture);
  55502. effect.setMatrix("view", viewMatrix);
  55503. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55504. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55505. var baseSize = this.particleTexture.getBaseSize();
  55506. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55507. }
  55508. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55509. if (this._scene.clipPlane) {
  55510. var clipPlane = this._scene.clipPlane;
  55511. var invView = viewMatrix.clone();
  55512. invView.invert();
  55513. effect.setMatrix("invView", invView);
  55514. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55515. }
  55516. // VBOs
  55517. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55518. // Draw order
  55519. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55520. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55521. }
  55522. else {
  55523. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55524. }
  55525. if (this.forceDepthWrite) {
  55526. engine.setDepthWrite(true);
  55527. }
  55528. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55529. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55530. return this._particles.length;
  55531. };
  55532. /**
  55533. * Disposes the particle system and free the associated resources
  55534. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55535. */
  55536. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55537. if (disposeTexture === void 0) { disposeTexture = true; }
  55538. if (this._vertexBuffer) {
  55539. this._vertexBuffer.dispose();
  55540. this._vertexBuffer = null;
  55541. }
  55542. if (this._indexBuffer) {
  55543. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55544. this._indexBuffer = null;
  55545. }
  55546. if (disposeTexture && this.particleTexture) {
  55547. this.particleTexture.dispose();
  55548. this.particleTexture = null;
  55549. }
  55550. this._removeFromRoot();
  55551. // Remove from scene
  55552. var index = this._scene.particleSystems.indexOf(this);
  55553. if (index > -1) {
  55554. this._scene.particleSystems.splice(index, 1);
  55555. }
  55556. // Callback
  55557. this.onDisposeObservable.notifyObservers(this);
  55558. this.onDisposeObservable.clear();
  55559. };
  55560. /**
  55561. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55562. * @param radius The radius of the sphere to emit from
  55563. * @returns the emitter
  55564. */
  55565. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55566. if (radius === void 0) { radius = 1; }
  55567. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55568. this.particleEmitterType = particleEmitter;
  55569. return particleEmitter;
  55570. };
  55571. /**
  55572. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55573. * @param radius The radius of the sphere to emit from
  55574. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55575. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55576. * @returns the emitter
  55577. */
  55578. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55579. if (radius === void 0) { radius = 1; }
  55580. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55581. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55582. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55583. this.particleEmitterType = particleEmitter;
  55584. return particleEmitter;
  55585. };
  55586. /**
  55587. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55588. * @param radius The radius of the cone to emit from
  55589. * @param angle The base angle of the cone
  55590. * @returns the emitter
  55591. */
  55592. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55593. if (radius === void 0) { radius = 1; }
  55594. if (angle === void 0) { angle = Math.PI / 4; }
  55595. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55596. this.particleEmitterType = particleEmitter;
  55597. return particleEmitter;
  55598. };
  55599. // 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.
  55600. /**
  55601. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55602. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55603. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55604. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55605. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55606. * @returns the emitter
  55607. */
  55608. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55609. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55610. this.particleEmitterType = particleEmitter;
  55611. this.direction1 = direction1;
  55612. this.direction2 = direction2;
  55613. this.minEmitBox = minEmitBox;
  55614. this.maxEmitBox = maxEmitBox;
  55615. return particleEmitter;
  55616. };
  55617. // Clone
  55618. /**
  55619. * Clones the particle system.
  55620. * @param name The name of the cloned object
  55621. * @param newEmitter The new emitter to use
  55622. * @returns the cloned particle system
  55623. */
  55624. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55625. var custom = null;
  55626. var program = null;
  55627. if (this.customShader != null) {
  55628. program = this.customShader;
  55629. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55630. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55631. }
  55632. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55633. result.customShader = program;
  55634. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55635. if (newEmitter === undefined) {
  55636. newEmitter = this.emitter;
  55637. }
  55638. result.emitter = newEmitter;
  55639. if (this.particleTexture) {
  55640. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55641. }
  55642. if (!this.preventAutoStart) {
  55643. result.start();
  55644. }
  55645. return result;
  55646. };
  55647. /**
  55648. * Serializes the particle system to a JSON object.
  55649. * @returns the JSON object
  55650. */
  55651. ParticleSystem.prototype.serialize = function () {
  55652. var serializationObject = {};
  55653. serializationObject.name = this.name;
  55654. serializationObject.id = this.id;
  55655. // Emitter
  55656. if (this.emitter.position) {
  55657. var emitterMesh = this.emitter;
  55658. serializationObject.emitterId = emitterMesh.id;
  55659. }
  55660. else {
  55661. var emitterPosition = this.emitter;
  55662. serializationObject.emitter = emitterPosition.asArray();
  55663. }
  55664. serializationObject.capacity = this.getCapacity();
  55665. if (this.particleTexture) {
  55666. serializationObject.textureName = this.particleTexture.name;
  55667. }
  55668. // Animations
  55669. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55670. // Particle system
  55671. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55672. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55673. serializationObject.minSize = this.minSize;
  55674. serializationObject.maxSize = this.maxSize;
  55675. serializationObject.minScaleX = this.minScaleX;
  55676. serializationObject.maxScaleX = this.maxScaleX;
  55677. serializationObject.minScaleY = this.minScaleY;
  55678. serializationObject.maxScaleY = this.maxScaleY;
  55679. serializationObject.minEmitPower = this.minEmitPower;
  55680. serializationObject.maxEmitPower = this.maxEmitPower;
  55681. serializationObject.minLifeTime = this.minLifeTime;
  55682. serializationObject.maxLifeTime = this.maxLifeTime;
  55683. serializationObject.emitRate = this.emitRate;
  55684. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55685. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55686. serializationObject.gravity = this.gravity.asArray();
  55687. serializationObject.direction1 = this.direction1.asArray();
  55688. serializationObject.direction2 = this.direction2.asArray();
  55689. serializationObject.color1 = this.color1.asArray();
  55690. serializationObject.color2 = this.color2.asArray();
  55691. serializationObject.colorDead = this.colorDead.asArray();
  55692. serializationObject.updateSpeed = this.updateSpeed;
  55693. serializationObject.targetStopDuration = this.targetStopDuration;
  55694. serializationObject.textureMask = this.textureMask.asArray();
  55695. serializationObject.blendMode = this.blendMode;
  55696. serializationObject.customShader = this.customShader;
  55697. serializationObject.preventAutoStart = this.preventAutoStart;
  55698. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55699. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55700. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55701. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55702. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55703. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55704. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55705. // Emitter
  55706. if (this.particleEmitterType) {
  55707. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55708. }
  55709. return serializationObject;
  55710. };
  55711. /**
  55712. * Parses a JSON object to create a particle system.
  55713. * @param parsedParticleSystem The JSON object to parse
  55714. * @param scene The scene to create the particle system in
  55715. * @param rootUrl The root url to use to load external dependencies like texture
  55716. * @returns the Parsed particle system
  55717. */
  55718. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55719. var name = parsedParticleSystem.name;
  55720. var custom = null;
  55721. var program = null;
  55722. if (parsedParticleSystem.customShader) {
  55723. program = parsedParticleSystem.customShader;
  55724. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55725. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55726. }
  55727. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55728. particleSystem.customShader = program;
  55729. if (parsedParticleSystem.id) {
  55730. particleSystem.id = parsedParticleSystem.id;
  55731. }
  55732. // Auto start
  55733. if (parsedParticleSystem.preventAutoStart) {
  55734. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55735. }
  55736. // Texture
  55737. if (parsedParticleSystem.textureName) {
  55738. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55739. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55740. }
  55741. // Emitter
  55742. if (parsedParticleSystem.emitterId) {
  55743. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55744. }
  55745. else {
  55746. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55747. }
  55748. // Animations
  55749. if (parsedParticleSystem.animations) {
  55750. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55751. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55752. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55753. }
  55754. }
  55755. if (parsedParticleSystem.autoAnimate) {
  55756. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55757. }
  55758. // Particle system
  55759. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55760. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55761. particleSystem.minSize = parsedParticleSystem.minSize;
  55762. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55763. if (parsedParticleSystem.minScaleX) {
  55764. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  55765. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  55766. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  55767. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  55768. }
  55769. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55770. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55771. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55772. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55773. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55774. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55775. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55776. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55777. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55778. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55779. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55780. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55781. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55782. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55783. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55784. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55785. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55786. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55787. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55788. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55789. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55790. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55791. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55792. if (!particleSystem.preventAutoStart) {
  55793. particleSystem.start();
  55794. }
  55795. return particleSystem;
  55796. };
  55797. /**
  55798. * Source color is added to the destination color without alpha affecting the result.
  55799. */
  55800. ParticleSystem.BLENDMODE_ONEONE = 0;
  55801. /**
  55802. * Blend current color and particle color using particle’s alpha.
  55803. */
  55804. ParticleSystem.BLENDMODE_STANDARD = 1;
  55805. return ParticleSystem;
  55806. }());
  55807. BABYLON.ParticleSystem = ParticleSystem;
  55808. })(BABYLON || (BABYLON = {}));
  55809. //# sourceMappingURL=babylon.particleSystem.js.map
  55810. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55811. var BABYLON;
  55812. (function (BABYLON) {
  55813. /**
  55814. * Particle emitter emitting particles from the inside of a box.
  55815. * It emits the particles randomly between 2 given directions.
  55816. */
  55817. var BoxParticleEmitter = /** @class */ (function () {
  55818. /**
  55819. * Creates a new instance BoxParticleEmitter
  55820. */
  55821. function BoxParticleEmitter() {
  55822. /**
  55823. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55824. */
  55825. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55826. /**
  55827. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55828. */
  55829. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55830. /**
  55831. * 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.
  55832. */
  55833. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55834. /**
  55835. * 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.
  55836. */
  55837. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55838. }
  55839. /**
  55840. * Called by the particle System when the direction is computed for the created particle.
  55841. * @param emitPower is the power of the particle (speed)
  55842. * @param worldMatrix is the world matrix of the particle system
  55843. * @param directionToUpdate is the direction vector to update with the result
  55844. * @param particle is the particle we are computed the direction for
  55845. */
  55846. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55847. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55848. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55849. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55850. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55851. };
  55852. /**
  55853. * Called by the particle System when the position is computed for the created particle.
  55854. * @param worldMatrix is the world matrix of the particle system
  55855. * @param positionToUpdate is the position vector to update with the result
  55856. * @param particle is the particle we are computed the position for
  55857. */
  55858. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55859. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55860. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55861. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55862. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55863. };
  55864. /**
  55865. * Clones the current emitter and returns a copy of it
  55866. * @returns the new emitter
  55867. */
  55868. BoxParticleEmitter.prototype.clone = function () {
  55869. var newOne = new BoxParticleEmitter();
  55870. BABYLON.Tools.DeepCopy(this, newOne);
  55871. return newOne;
  55872. };
  55873. /**
  55874. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55875. * @param effect defines the update shader
  55876. */
  55877. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55878. effect.setVector3("direction1", this.direction1);
  55879. effect.setVector3("direction2", this.direction2);
  55880. effect.setVector3("minEmitBox", this.minEmitBox);
  55881. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55882. };
  55883. /**
  55884. * Returns a string to use to update the GPU particles update shader
  55885. * @returns a string containng the defines string
  55886. */
  55887. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55888. return "#define BOXEMITTER";
  55889. };
  55890. /**
  55891. * Returns the string "BoxEmitter"
  55892. * @returns a string containing the class name
  55893. */
  55894. BoxParticleEmitter.prototype.getClassName = function () {
  55895. return "BoxEmitter";
  55896. };
  55897. /**
  55898. * Serializes the particle system to a JSON object.
  55899. * @returns the JSON object
  55900. */
  55901. BoxParticleEmitter.prototype.serialize = function () {
  55902. var serializationObject = {};
  55903. serializationObject.type = this.getClassName();
  55904. serializationObject.direction1 = this.direction1.asArray();
  55905. serializationObject.direction2 = this.direction2.asArray();
  55906. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55907. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55908. return serializationObject;
  55909. };
  55910. /**
  55911. * Parse properties from a JSON object
  55912. * @param serializationObject defines the JSON object
  55913. */
  55914. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55915. this.direction1.copyFrom(serializationObject.direction1);
  55916. this.direction2.copyFrom(serializationObject.direction2);
  55917. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55918. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55919. };
  55920. return BoxParticleEmitter;
  55921. }());
  55922. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55923. })(BABYLON || (BABYLON = {}));
  55924. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55925. var BABYLON;
  55926. (function (BABYLON) {
  55927. /**
  55928. * Particle emitter emitting particles from the inside of a cone.
  55929. * It emits the particles alongside the cone volume from the base to the particle.
  55930. * The emission direction might be randomized.
  55931. */
  55932. var ConeParticleEmitter = /** @class */ (function () {
  55933. /**
  55934. * Creates a new instance ConeParticleEmitter
  55935. * @param radius the radius of the emission cone (1 by default)
  55936. * @param angles the cone base angle (PI by default)
  55937. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  55938. */
  55939. function ConeParticleEmitter(radius, angle,
  55940. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  55941. directionRandomizer) {
  55942. if (radius === void 0) { radius = 1; }
  55943. if (angle === void 0) { angle = Math.PI; }
  55944. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55945. this.directionRandomizer = directionRandomizer;
  55946. this.angle = angle;
  55947. this.radius = radius;
  55948. }
  55949. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55950. /**
  55951. * Gets or sets the radius of the emission cone
  55952. */
  55953. get: function () {
  55954. return this._radius;
  55955. },
  55956. set: function (value) {
  55957. this._radius = value;
  55958. this._buildHeight();
  55959. },
  55960. enumerable: true,
  55961. configurable: true
  55962. });
  55963. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  55964. /**
  55965. * Gets or sets the angle of the emission cone
  55966. */
  55967. get: function () {
  55968. return this._angle;
  55969. },
  55970. set: function (value) {
  55971. this._angle = value;
  55972. this._buildHeight();
  55973. },
  55974. enumerable: true,
  55975. configurable: true
  55976. });
  55977. ConeParticleEmitter.prototype._buildHeight = function () {
  55978. if (this._angle !== 0) {
  55979. this._height = this._radius / Math.tan(this._angle / 2);
  55980. }
  55981. else {
  55982. this._height = 1;
  55983. }
  55984. };
  55985. /**
  55986. * Called by the particle System when the direction is computed for the created particle.
  55987. * @param emitPower is the power of the particle (speed)
  55988. * @param worldMatrix is the world matrix of the particle system
  55989. * @param directionToUpdate is the direction vector to update with the result
  55990. * @param particle is the particle we are computed the direction for
  55991. */
  55992. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55993. if (this._angle === 0) {
  55994. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55995. }
  55996. else {
  55997. // measure the direction Vector from the emitter to the particle.
  55998. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55999. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56000. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56001. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56002. direction.x += randX;
  56003. direction.y += randY;
  56004. direction.z += randZ;
  56005. direction.normalize();
  56006. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56007. }
  56008. };
  56009. /**
  56010. * Called by the particle System when the position is computed for the created particle.
  56011. * @param worldMatrix is the world matrix of the particle system
  56012. * @param positionToUpdate is the position vector to update with the result
  56013. * @param particle is the particle we are computed the position for
  56014. */
  56015. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56016. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56017. var h = BABYLON.Scalar.RandomRange(0, 1);
  56018. // Better distribution in a cone at normal angles.
  56019. h = 1 - h * h;
  56020. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56021. radius = radius * h;
  56022. var randX = radius * Math.sin(s);
  56023. var randZ = radius * Math.cos(s);
  56024. var randY = h * this._height;
  56025. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56026. };
  56027. /**
  56028. * Clones the current emitter and returns a copy of it
  56029. * @returns the new emitter
  56030. */
  56031. ConeParticleEmitter.prototype.clone = function () {
  56032. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56033. BABYLON.Tools.DeepCopy(this, newOne);
  56034. return newOne;
  56035. };
  56036. /**
  56037. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56038. * @param effect defines the update shader
  56039. */
  56040. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56041. effect.setFloat("radius", this._radius);
  56042. effect.setFloat("coneAngle", this._angle);
  56043. effect.setFloat("height", this._height);
  56044. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56045. };
  56046. /**
  56047. * Returns a string to use to update the GPU particles update shader
  56048. * @returns a string containng the defines string
  56049. */
  56050. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56051. return "#define CONEEMITTER";
  56052. };
  56053. /**
  56054. * Returns the string "BoxEmitter"
  56055. * @returns a string containing the class name
  56056. */
  56057. ConeParticleEmitter.prototype.getClassName = function () {
  56058. return "ConeEmitter";
  56059. };
  56060. /**
  56061. * Serializes the particle system to a JSON object.
  56062. * @returns the JSON object
  56063. */
  56064. ConeParticleEmitter.prototype.serialize = function () {
  56065. var serializationObject = {};
  56066. serializationObject.type = this.getClassName();
  56067. serializationObject.radius = this._radius;
  56068. serializationObject.angle = this._angle;
  56069. serializationObject.directionRandomizer = this.directionRandomizer;
  56070. return serializationObject;
  56071. };
  56072. /**
  56073. * Parse properties from a JSON object
  56074. * @param serializationObject defines the JSON object
  56075. */
  56076. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56077. this.radius = serializationObject.radius;
  56078. this.angle = serializationObject.angle;
  56079. this.directionRandomizer = serializationObject.directionRandomizer;
  56080. };
  56081. return ConeParticleEmitter;
  56082. }());
  56083. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56084. })(BABYLON || (BABYLON = {}));
  56085. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56086. var BABYLON;
  56087. (function (BABYLON) {
  56088. /**
  56089. * Particle emitter emitting particles from the inside of a sphere.
  56090. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56091. */
  56092. var SphereParticleEmitter = /** @class */ (function () {
  56093. /**
  56094. * Creates a new instance SphereParticleEmitter
  56095. * @param radius the radius of the emission sphere (1 by default)
  56096. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56097. */
  56098. function SphereParticleEmitter(
  56099. /**
  56100. * The radius of the emission sphere.
  56101. */
  56102. radius,
  56103. /**
  56104. * How much to randomize the particle direction [0-1].
  56105. */
  56106. directionRandomizer) {
  56107. if (radius === void 0) { radius = 1; }
  56108. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56109. this.radius = radius;
  56110. this.directionRandomizer = directionRandomizer;
  56111. }
  56112. /**
  56113. * Called by the particle System when the direction is computed for the created particle.
  56114. * @param emitPower is the power of the particle (speed)
  56115. * @param worldMatrix is the world matrix of the particle system
  56116. * @param directionToUpdate is the direction vector to update with the result
  56117. * @param particle is the particle we are computed the direction for
  56118. */
  56119. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56120. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56121. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56122. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56123. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56124. direction.x += randX;
  56125. direction.y += randY;
  56126. direction.z += randZ;
  56127. direction.normalize();
  56128. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56129. };
  56130. /**
  56131. * Called by the particle System when the position is computed for the created particle.
  56132. * @param worldMatrix is the world matrix of the particle system
  56133. * @param positionToUpdate is the position vector to update with the result
  56134. * @param particle is the particle we are computed the position for
  56135. */
  56136. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56137. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56138. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56139. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56140. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56141. var randY = randRadius * Math.cos(theta);
  56142. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56143. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56144. };
  56145. /**
  56146. * Clones the current emitter and returns a copy of it
  56147. * @returns the new emitter
  56148. */
  56149. SphereParticleEmitter.prototype.clone = function () {
  56150. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56151. BABYLON.Tools.DeepCopy(this, newOne);
  56152. return newOne;
  56153. };
  56154. /**
  56155. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56156. * @param effect defines the update shader
  56157. */
  56158. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56159. effect.setFloat("radius", this.radius);
  56160. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56161. };
  56162. /**
  56163. * Returns a string to use to update the GPU particles update shader
  56164. * @returns a string containng the defines string
  56165. */
  56166. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56167. return "#define SPHEREEMITTER";
  56168. };
  56169. /**
  56170. * Returns the string "SphereParticleEmitter"
  56171. * @returns a string containing the class name
  56172. */
  56173. SphereParticleEmitter.prototype.getClassName = function () {
  56174. return "SphereParticleEmitter";
  56175. };
  56176. /**
  56177. * Serializes the particle system to a JSON object.
  56178. * @returns the JSON object
  56179. */
  56180. SphereParticleEmitter.prototype.serialize = function () {
  56181. var serializationObject = {};
  56182. serializationObject.type = this.getClassName();
  56183. serializationObject.radius = this.radius;
  56184. serializationObject.directionRandomizer = this.directionRandomizer;
  56185. return serializationObject;
  56186. };
  56187. /**
  56188. * Parse properties from a JSON object
  56189. * @param serializationObject defines the JSON object
  56190. */
  56191. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56192. this.radius = serializationObject.radius;
  56193. this.directionRandomizer = serializationObject.directionRandomizer;
  56194. };
  56195. return SphereParticleEmitter;
  56196. }());
  56197. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56198. /**
  56199. * Particle emitter emitting particles from the inside of a sphere.
  56200. * It emits the particles randomly between two vectors.
  56201. */
  56202. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56203. __extends(SphereDirectedParticleEmitter, _super);
  56204. /**
  56205. * Creates a new instance SphereDirectedParticleEmitter
  56206. * @param radius the radius of the emission sphere (1 by default)
  56207. * @param direction1 the min limit of the emission direction (up vector by default)
  56208. * @param direction2 the max limit of the emission direction (up vector by default)
  56209. */
  56210. function SphereDirectedParticleEmitter(radius,
  56211. /**
  56212. * The min limit of the emission direction.
  56213. */
  56214. direction1,
  56215. /**
  56216. * The max limit of the emission direction.
  56217. */
  56218. direction2) {
  56219. if (radius === void 0) { radius = 1; }
  56220. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56221. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56222. var _this = _super.call(this, radius) || this;
  56223. _this.direction1 = direction1;
  56224. _this.direction2 = direction2;
  56225. return _this;
  56226. }
  56227. /**
  56228. * Called by the particle System when the direction is computed for the created particle.
  56229. * @param emitPower is the power of the particle (speed)
  56230. * @param worldMatrix is the world matrix of the particle system
  56231. * @param directionToUpdate is the direction vector to update with the result
  56232. * @param particle is the particle we are computed the direction for
  56233. */
  56234. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56235. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56236. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56237. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56238. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56239. };
  56240. /**
  56241. * Clones the current emitter and returns a copy of it
  56242. * @returns the new emitter
  56243. */
  56244. SphereDirectedParticleEmitter.prototype.clone = function () {
  56245. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56246. BABYLON.Tools.DeepCopy(this, newOne);
  56247. return newOne;
  56248. };
  56249. /**
  56250. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56251. * @param effect defines the update shader
  56252. */
  56253. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56254. effect.setFloat("radius", this.radius);
  56255. effect.setVector3("direction1", this.direction1);
  56256. effect.setVector3("direction2", this.direction2);
  56257. };
  56258. /**
  56259. * Returns a string to use to update the GPU particles update shader
  56260. * @returns a string containng the defines string
  56261. */
  56262. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56263. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56264. };
  56265. /**
  56266. * Returns the string "SphereDirectedParticleEmitter"
  56267. * @returns a string containing the class name
  56268. */
  56269. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56270. return "SphereDirectedParticleEmitter";
  56271. };
  56272. /**
  56273. * Serializes the particle system to a JSON object.
  56274. * @returns the JSON object
  56275. */
  56276. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56277. var serializationObject = _super.prototype.serialize.call(this);
  56278. serializationObject.direction1 = this.direction1.asArray();
  56279. serializationObject.direction2 = this.direction2.asArray();
  56280. return serializationObject;
  56281. };
  56282. /**
  56283. * Parse properties from a JSON object
  56284. * @param serializationObject defines the JSON object
  56285. */
  56286. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56287. _super.prototype.parse.call(this, serializationObject);
  56288. this.direction1.copyFrom(serializationObject.direction1);
  56289. this.direction2.copyFrom(serializationObject.direction2);
  56290. };
  56291. return SphereDirectedParticleEmitter;
  56292. }(SphereParticleEmitter));
  56293. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56294. })(BABYLON || (BABYLON = {}));
  56295. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56296. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56297. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56298. s = arguments[i];
  56299. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56300. t[p] = s[p];
  56301. }
  56302. return t;
  56303. };
  56304. var BABYLON;
  56305. (function (BABYLON) {
  56306. /**
  56307. * This represents a GPU particle system in Babylon
  56308. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56309. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56310. */
  56311. var GPUParticleSystem = /** @class */ (function () {
  56312. /**
  56313. * Instantiates a GPU particle system.
  56314. * 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.
  56315. * @param name The name of the particle system
  56316. * @param capacity The max number of particles alive at the same time
  56317. * @param scene The scene the particle system belongs to
  56318. */
  56319. function GPUParticleSystem(name, options, scene) {
  56320. /**
  56321. * The emitter represents the Mesh or position we are attaching the particle system to.
  56322. */
  56323. this.emitter = null;
  56324. /**
  56325. * The rendering group used by the Particle system to chose when to render.
  56326. */
  56327. this.renderingGroupId = 0;
  56328. /**
  56329. * The layer mask we are rendering the particles through.
  56330. */
  56331. this.layerMask = 0x0FFFFFFF;
  56332. this._targetIndex = 0;
  56333. this._currentRenderId = -1;
  56334. this._started = false;
  56335. this._stopped = false;
  56336. this._timeDelta = 0;
  56337. this._attributesStrideSize = 18;
  56338. this._actualFrame = 0;
  56339. /**
  56340. * List of animations used by the particle system.
  56341. */
  56342. this.animations = [];
  56343. /**
  56344. * An event triggered when the system is disposed.
  56345. */
  56346. this.onDisposeObservable = new BABYLON.Observable();
  56347. /**
  56348. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56349. */
  56350. this.updateSpeed = 0.01;
  56351. /**
  56352. * The amount of time the particle system is running (depends of the overall update speed).
  56353. */
  56354. this.targetStopDuration = 0;
  56355. /**
  56356. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56357. */
  56358. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56359. /**
  56360. * Minimum life time of emitting particles.
  56361. */
  56362. this.minLifeTime = 1;
  56363. /**
  56364. * Maximum life time of emitting particles.
  56365. */
  56366. this.maxLifeTime = 1;
  56367. /**
  56368. * Minimum Size of emitting particles.
  56369. */
  56370. this.minSize = 1;
  56371. /**
  56372. * Maximum Size of emitting particles.
  56373. */
  56374. this.maxSize = 1;
  56375. /**
  56376. * Minimum scale of emitting particles on X axis.
  56377. */
  56378. this.minScaleX = 1;
  56379. /**
  56380. * Maximum scale of emitting particles on X axis.
  56381. */
  56382. this.maxScaleX = 1;
  56383. /**
  56384. * Minimum scale of emitting particles on Y axis.
  56385. */
  56386. this.minScaleY = 1;
  56387. /**
  56388. * Maximum scale of emitting particles on Y axis.
  56389. */
  56390. this.maxScaleY = 1;
  56391. /**
  56392. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56393. */
  56394. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56395. /**
  56396. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56397. */
  56398. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56399. /**
  56400. * Color the particle will have at the end of its lifetime.
  56401. */
  56402. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56403. /**
  56404. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56405. */
  56406. this.emitRate = 100;
  56407. /**
  56408. * You can use gravity if you want to give an orientation to your particles.
  56409. */
  56410. this.gravity = BABYLON.Vector3.Zero();
  56411. /**
  56412. * Minimum power of emitting particles.
  56413. */
  56414. this.minEmitPower = 1;
  56415. /**
  56416. * Maximum power of emitting particles.
  56417. */
  56418. this.maxEmitPower = 1;
  56419. /**
  56420. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56421. */
  56422. this.minAngularSpeed = 0;
  56423. /**
  56424. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56425. */
  56426. this.maxAngularSpeed = 0;
  56427. /**
  56428. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56429. * to override the particles.
  56430. */
  56431. this.forceDepthWrite = false;
  56432. this.id = name;
  56433. this.name = name;
  56434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56435. this._engine = this._scene.getEngine();
  56436. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56437. this._capacity = fullOptions.capacity;
  56438. this._activeCount = fullOptions.capacity;
  56439. this._currentActiveCount = 0;
  56440. this._scene.particleSystems.push(this);
  56441. this._updateEffectOptions = {
  56442. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  56443. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56444. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56445. "angleRange"],
  56446. uniformBuffersNames: [],
  56447. samplers: ["randomSampler"],
  56448. defines: "",
  56449. fallbacks: null,
  56450. onCompiled: null,
  56451. onError: null,
  56452. indexParameters: null,
  56453. maxSimultaneousLights: 0,
  56454. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  56455. };
  56456. // Random data
  56457. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56458. var d = [];
  56459. for (var i = 0; i < maxTextureSize; ++i) {
  56460. d.push(Math.random());
  56461. d.push(Math.random());
  56462. d.push(Math.random());
  56463. d.push(Math.random());
  56464. }
  56465. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56466. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56467. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56468. this._randomTextureSize = maxTextureSize;
  56469. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56470. }
  56471. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56472. /**
  56473. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56474. */
  56475. get: function () {
  56476. if (!BABYLON.Engine.LastCreatedEngine) {
  56477. return false;
  56478. }
  56479. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56480. },
  56481. enumerable: true,
  56482. configurable: true
  56483. });
  56484. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56485. /**
  56486. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56487. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56488. */
  56489. get: function () {
  56490. if (this.particleEmitterType.direction1) {
  56491. return this.particleEmitterType.direction1;
  56492. }
  56493. return BABYLON.Vector3.Zero();
  56494. },
  56495. set: function (value) {
  56496. if (this.particleEmitterType.direction1) {
  56497. this.particleEmitterType.direction1 = value;
  56498. }
  56499. },
  56500. enumerable: true,
  56501. configurable: true
  56502. });
  56503. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56504. /**
  56505. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56506. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56507. */
  56508. get: function () {
  56509. if (this.particleEmitterType.direction2) {
  56510. return this.particleEmitterType.direction2;
  56511. }
  56512. return BABYLON.Vector3.Zero();
  56513. },
  56514. set: function (value) {
  56515. if (this.particleEmitterType.direction2) {
  56516. this.particleEmitterType.direction2 = value;
  56517. }
  56518. },
  56519. enumerable: true,
  56520. configurable: true
  56521. });
  56522. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56523. /**
  56524. * 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.
  56525. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56526. */
  56527. get: function () {
  56528. if (this.particleEmitterType.minEmitBox) {
  56529. return this.particleEmitterType.minEmitBox;
  56530. }
  56531. return BABYLON.Vector3.Zero();
  56532. },
  56533. set: function (value) {
  56534. if (this.particleEmitterType.minEmitBox) {
  56535. this.particleEmitterType.minEmitBox = value;
  56536. }
  56537. },
  56538. enumerable: true,
  56539. configurable: true
  56540. });
  56541. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56542. /**
  56543. * 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.
  56544. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56545. */
  56546. get: function () {
  56547. if (this.particleEmitterType.maxEmitBox) {
  56548. return this.particleEmitterType.maxEmitBox;
  56549. }
  56550. return BABYLON.Vector3.Zero();
  56551. },
  56552. set: function (value) {
  56553. if (this.particleEmitterType.maxEmitBox) {
  56554. this.particleEmitterType.maxEmitBox = value;
  56555. }
  56556. },
  56557. enumerable: true,
  56558. configurable: true
  56559. });
  56560. /**
  56561. * Gets the maximum number of particles active at the same time.
  56562. * @returns The max number of active particles.
  56563. */
  56564. GPUParticleSystem.prototype.getCapacity = function () {
  56565. return this._capacity;
  56566. };
  56567. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56568. /**
  56569. * Gets or set the number of active particles
  56570. */
  56571. get: function () {
  56572. return this._activeCount;
  56573. },
  56574. set: function (value) {
  56575. this._activeCount = Math.min(value, this._capacity);
  56576. },
  56577. enumerable: true,
  56578. configurable: true
  56579. });
  56580. /**
  56581. * Is this system ready to be used/rendered
  56582. * @return true if the system is ready
  56583. */
  56584. GPUParticleSystem.prototype.isReady = function () {
  56585. if (!this._updateEffect) {
  56586. this._recreateUpdateEffect();
  56587. this._recreateRenderEffect();
  56588. return false;
  56589. }
  56590. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56591. return false;
  56592. }
  56593. return true;
  56594. };
  56595. /**
  56596. * Gets Wether the system has been started.
  56597. * @returns True if it has been started, otherwise false.
  56598. */
  56599. GPUParticleSystem.prototype.isStarted = function () {
  56600. return this._started;
  56601. };
  56602. /**
  56603. * Starts the particle system and begins to emit.
  56604. */
  56605. GPUParticleSystem.prototype.start = function () {
  56606. this._started = true;
  56607. this._stopped = false;
  56608. };
  56609. /**
  56610. * Stops the particle system.
  56611. */
  56612. GPUParticleSystem.prototype.stop = function () {
  56613. this._stopped = true;
  56614. };
  56615. /**
  56616. * Remove all active particles
  56617. */
  56618. GPUParticleSystem.prototype.reset = function () {
  56619. this._releaseBuffers();
  56620. this._releaseVAOs();
  56621. this._currentActiveCount = 0;
  56622. this._targetIndex = 0;
  56623. };
  56624. /**
  56625. * Returns the string "GPUParticleSystem"
  56626. * @returns a string containing the class name
  56627. */
  56628. GPUParticleSystem.prototype.getClassName = function () {
  56629. return "GPUParticleSystem";
  56630. };
  56631. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56632. var updateVertexBuffers = {};
  56633. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56634. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56635. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56636. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56637. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  56638. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  56639. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  56640. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  56641. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56642. this._engine.bindArrayBuffer(null);
  56643. return vao;
  56644. };
  56645. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56646. var renderVertexBuffers = {};
  56647. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56648. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56649. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56650. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  56651. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  56652. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  56653. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56654. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56655. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56656. this._engine.bindArrayBuffer(null);
  56657. return vao;
  56658. };
  56659. GPUParticleSystem.prototype._initialize = function (force) {
  56660. if (force === void 0) { force = false; }
  56661. if (this._buffer0 && !force) {
  56662. return;
  56663. }
  56664. var engine = this._scene.getEngine();
  56665. var data = new Array();
  56666. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56667. // position
  56668. data.push(0.0);
  56669. data.push(0.0);
  56670. data.push(0.0);
  56671. // Age and life
  56672. data.push(0.0); // create the particle as a dead one to create a new one at start
  56673. data.push(0.0);
  56674. // Seed
  56675. data.push(Math.random());
  56676. // Size
  56677. data.push(0.0);
  56678. data.push(0.0);
  56679. data.push(0.0);
  56680. // color
  56681. data.push(0.0);
  56682. data.push(0.0);
  56683. data.push(0.0);
  56684. data.push(0.0);
  56685. // direction
  56686. data.push(0.0);
  56687. data.push(0.0);
  56688. data.push(0.0);
  56689. // angle
  56690. data.push(0.0);
  56691. data.push(0.0);
  56692. }
  56693. // Sprite data
  56694. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56695. -0.5, 0.5, 0, 1,
  56696. -0.5, -0.5, 0, 0,
  56697. 0.5, -0.5, 1, 0]);
  56698. // Buffers
  56699. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56700. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56701. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56702. // Update VAO
  56703. this._updateVAO = [];
  56704. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56705. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56706. // Render VAO
  56707. this._renderVAO = [];
  56708. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56709. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56710. // Links
  56711. this._sourceBuffer = this._buffer0;
  56712. this._targetBuffer = this._buffer1;
  56713. };
  56714. /** @hidden */
  56715. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56716. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56717. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56718. return;
  56719. }
  56720. this._updateEffectOptions.defines = defines;
  56721. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56722. };
  56723. /** @hidden */
  56724. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56725. var defines = "";
  56726. if (this._scene.clipPlane) {
  56727. defines = "\n#define CLIPPLANE";
  56728. }
  56729. if (this._renderEffect && this._renderEffect.defines === defines) {
  56730. return;
  56731. }
  56732. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56733. };
  56734. /**
  56735. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56736. */
  56737. GPUParticleSystem.prototype.animate = function () {
  56738. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56739. this._actualFrame += this._timeDelta;
  56740. if (!this._stopped) {
  56741. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56742. this.stop();
  56743. }
  56744. }
  56745. };
  56746. /**
  56747. * Renders the particle system in its current state.
  56748. * @returns the current number of particles
  56749. */
  56750. GPUParticleSystem.prototype.render = function () {
  56751. if (!this._started) {
  56752. return 0;
  56753. }
  56754. this._recreateUpdateEffect();
  56755. this._recreateRenderEffect();
  56756. if (!this.isReady()) {
  56757. return 0;
  56758. }
  56759. if (this._currentRenderId === this._scene.getRenderId()) {
  56760. return 0;
  56761. }
  56762. this._currentRenderId = this._scene.getRenderId();
  56763. // Get everything ready to render
  56764. this._initialize();
  56765. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56766. // Enable update effect
  56767. this._engine.enableEffect(this._updateEffect);
  56768. this._engine.setState(false);
  56769. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56770. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56771. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56772. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56773. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56774. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56775. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56776. this._updateEffect.setDirectColor4("color1", this.color1);
  56777. this._updateEffect.setDirectColor4("color2", this.color2);
  56778. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56779. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  56780. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  56781. this._updateEffect.setVector3("gravity", this.gravity);
  56782. if (this.particleEmitterType) {
  56783. this.particleEmitterType.applyToShader(this._updateEffect);
  56784. }
  56785. var emitterWM;
  56786. if (this.emitter.position) {
  56787. var emitterMesh = this.emitter;
  56788. emitterWM = emitterMesh.getWorldMatrix();
  56789. }
  56790. else {
  56791. var emitterPosition = this.emitter;
  56792. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56793. }
  56794. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56795. // Bind source VAO
  56796. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56797. // Update
  56798. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56799. this._engine.setRasterizerState(false);
  56800. this._engine.beginTransformFeedback();
  56801. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56802. this._engine.endTransformFeedback();
  56803. this._engine.setRasterizerState(true);
  56804. this._engine.bindTransformFeedbackBuffer(null);
  56805. // Enable render effect
  56806. this._engine.enableEffect(this._renderEffect);
  56807. var viewMatrix = this._scene.getViewMatrix();
  56808. this._renderEffect.setMatrix("view", viewMatrix);
  56809. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56810. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56811. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56812. if (this._scene.clipPlane) {
  56813. var clipPlane = this._scene.clipPlane;
  56814. var invView = viewMatrix.clone();
  56815. invView.invert();
  56816. this._renderEffect.setMatrix("invView", invView);
  56817. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56818. }
  56819. // Draw order
  56820. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56821. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56822. }
  56823. else {
  56824. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56825. }
  56826. if (this.forceDepthWrite) {
  56827. this._engine.setDepthWrite(true);
  56828. }
  56829. // Bind source VAO
  56830. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56831. // Render
  56832. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56833. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56834. // Switch VAOs
  56835. this._targetIndex++;
  56836. if (this._targetIndex === 2) {
  56837. this._targetIndex = 0;
  56838. }
  56839. // Switch buffers
  56840. var tmpBuffer = this._sourceBuffer;
  56841. this._sourceBuffer = this._targetBuffer;
  56842. this._targetBuffer = tmpBuffer;
  56843. return this._currentActiveCount;
  56844. };
  56845. /**
  56846. * Rebuilds the particle system
  56847. */
  56848. GPUParticleSystem.prototype.rebuild = function () {
  56849. this._initialize(true);
  56850. };
  56851. GPUParticleSystem.prototype._releaseBuffers = function () {
  56852. if (this._buffer0) {
  56853. this._buffer0.dispose();
  56854. this._buffer0 = null;
  56855. }
  56856. if (this._buffer1) {
  56857. this._buffer1.dispose();
  56858. this._buffer1 = null;
  56859. }
  56860. if (this._spriteBuffer) {
  56861. this._spriteBuffer.dispose();
  56862. this._spriteBuffer = null;
  56863. }
  56864. };
  56865. GPUParticleSystem.prototype._releaseVAOs = function () {
  56866. if (!this._updateVAO) {
  56867. return;
  56868. }
  56869. for (var index = 0; index < this._updateVAO.length; index++) {
  56870. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56871. }
  56872. this._updateVAO = [];
  56873. for (var index = 0; index < this._renderVAO.length; index++) {
  56874. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56875. }
  56876. this._renderVAO = [];
  56877. };
  56878. /**
  56879. * Disposes the particle system and free the associated resources
  56880. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56881. */
  56882. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56883. if (disposeTexture === void 0) { disposeTexture = true; }
  56884. var index = this._scene.particleSystems.indexOf(this);
  56885. if (index > -1) {
  56886. this._scene.particleSystems.splice(index, 1);
  56887. }
  56888. this._releaseBuffers();
  56889. this._releaseVAOs();
  56890. if (this._randomTexture) {
  56891. this._randomTexture.dispose();
  56892. this._randomTexture = null;
  56893. }
  56894. if (disposeTexture && this.particleTexture) {
  56895. this.particleTexture.dispose();
  56896. this.particleTexture = null;
  56897. }
  56898. // Callback
  56899. this.onDisposeObservable.notifyObservers(this);
  56900. this.onDisposeObservable.clear();
  56901. };
  56902. /**
  56903. * Clones the particle system.
  56904. * @param name The name of the cloned object
  56905. * @param newEmitter The new emitter to use
  56906. * @returns the cloned particle system
  56907. */
  56908. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56909. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56910. BABYLON.Tools.DeepCopy(this, result);
  56911. if (newEmitter === undefined) {
  56912. newEmitter = this.emitter;
  56913. }
  56914. result.emitter = newEmitter;
  56915. if (this.particleTexture) {
  56916. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56917. }
  56918. return result;
  56919. };
  56920. /**
  56921. * Serializes the particle system to a JSON object.
  56922. * @returns the JSON object
  56923. */
  56924. GPUParticleSystem.prototype.serialize = function () {
  56925. var serializationObject = {};
  56926. serializationObject.name = this.name;
  56927. serializationObject.id = this.id;
  56928. // Emitter
  56929. if (this.emitter.position) {
  56930. var emitterMesh = this.emitter;
  56931. serializationObject.emitterId = emitterMesh.id;
  56932. }
  56933. else {
  56934. var emitterPosition = this.emitter;
  56935. serializationObject.emitter = emitterPosition.asArray();
  56936. }
  56937. serializationObject.capacity = this.getCapacity();
  56938. if (this.particleTexture) {
  56939. serializationObject.textureName = this.particleTexture.name;
  56940. }
  56941. // Animations
  56942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56943. // Particle system
  56944. serializationObject.activeParticleCount = this.activeParticleCount;
  56945. serializationObject.randomTextureSize = this._randomTextureSize;
  56946. serializationObject.minSize = this.minSize;
  56947. serializationObject.maxSize = this.maxSize;
  56948. serializationObject.minEmitPower = this.minEmitPower;
  56949. serializationObject.maxEmitPower = this.maxEmitPower;
  56950. serializationObject.minLifeTime = this.minLifeTime;
  56951. serializationObject.maxLifeTime = this.maxLifeTime;
  56952. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56953. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56954. serializationObject.emitRate = this.emitRate;
  56955. serializationObject.gravity = this.gravity.asArray();
  56956. serializationObject.color1 = this.color1.asArray();
  56957. serializationObject.color2 = this.color2.asArray();
  56958. serializationObject.colorDead = this.colorDead.asArray();
  56959. serializationObject.updateSpeed = this.updateSpeed;
  56960. serializationObject.targetStopDuration = this.targetStopDuration;
  56961. serializationObject.blendMode = this.blendMode;
  56962. // Emitter
  56963. if (this.particleEmitterType) {
  56964. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56965. }
  56966. return serializationObject;
  56967. };
  56968. /**
  56969. * Parses a JSON object to create a GPU particle system.
  56970. * @param parsedParticleSystem The JSON object to parse
  56971. * @param scene The scene to create the particle system in
  56972. * @param rootUrl The root url to use to load external dependencies like texture
  56973. * @returns the parsed GPU particle system
  56974. */
  56975. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56976. var name = parsedParticleSystem.name;
  56977. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56978. if (parsedParticleSystem.id) {
  56979. particleSystem.id = parsedParticleSystem.id;
  56980. }
  56981. // Texture
  56982. if (parsedParticleSystem.textureName) {
  56983. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56984. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56985. }
  56986. // Emitter
  56987. if (parsedParticleSystem.emitterId) {
  56988. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56989. }
  56990. else {
  56991. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56992. }
  56993. // Animations
  56994. if (parsedParticleSystem.animations) {
  56995. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56996. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56997. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56998. }
  56999. }
  57000. // Particle system
  57001. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57002. particleSystem.minSize = parsedParticleSystem.minSize;
  57003. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57004. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57005. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57006. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57007. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57008. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57009. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57010. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57011. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57012. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57013. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57014. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57015. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57016. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57017. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57018. // Emitter
  57019. if (parsedParticleSystem.particleEmitterType) {
  57020. var emitterType = void 0;
  57021. switch (parsedParticleSystem.particleEmitterType.type) {
  57022. case "SphereEmitter":
  57023. emitterType = new BABYLON.SphereParticleEmitter();
  57024. break;
  57025. case "SphereDirectedParticleEmitter":
  57026. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57027. break;
  57028. case "ConeEmitter":
  57029. emitterType = new BABYLON.ConeParticleEmitter();
  57030. break;
  57031. case "BoxEmitter":
  57032. default:
  57033. emitterType = new BABYLON.BoxParticleEmitter();
  57034. break;
  57035. }
  57036. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57037. particleSystem.particleEmitterType = emitterType;
  57038. }
  57039. return particleSystem;
  57040. };
  57041. return GPUParticleSystem;
  57042. }());
  57043. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. /**
  57049. * Represents one particle of a solid particle system.
  57050. */
  57051. var SolidParticle = /** @class */ (function () {
  57052. /**
  57053. * Creates a Solid Particle object.
  57054. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57055. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57056. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57057. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57058. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57059. * @param shapeId (integer) is the model shape identifier in the SPS.
  57060. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57061. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57062. */
  57063. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57064. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57065. /**
  57066. * particle global index
  57067. */
  57068. this.idx = 0;
  57069. /**
  57070. * The color of the particle
  57071. */
  57072. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57073. /**
  57074. * The world space position of the particle.
  57075. */
  57076. this.position = BABYLON.Vector3.Zero();
  57077. /**
  57078. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57079. */
  57080. this.rotation = BABYLON.Vector3.Zero();
  57081. /**
  57082. * The scaling of the particle.
  57083. */
  57084. this.scaling = BABYLON.Vector3.One();
  57085. /**
  57086. * The uvs of the particle.
  57087. */
  57088. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57089. /**
  57090. * The current speed of the particle.
  57091. */
  57092. this.velocity = BABYLON.Vector3.Zero();
  57093. /**
  57094. * The pivot point in the particle local space.
  57095. */
  57096. this.pivot = BABYLON.Vector3.Zero();
  57097. /**
  57098. * Must the particle be translated from its pivot point in its local space ?
  57099. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57100. * Default : false
  57101. */
  57102. this.translateFromPivot = false;
  57103. /**
  57104. * Is the particle active or not ?
  57105. */
  57106. this.alive = true;
  57107. /**
  57108. * Is the particle visible or not ?
  57109. */
  57110. this.isVisible = true;
  57111. /**
  57112. * Index of this particle in the global "positions" array (Internal use)
  57113. */
  57114. this._pos = 0;
  57115. /**
  57116. * Index of this particle in the global "indices" array (Internal use)
  57117. */
  57118. this._ind = 0;
  57119. /**
  57120. * ModelShape id of this particle
  57121. */
  57122. this.shapeId = 0;
  57123. /**
  57124. * Index of the particle in its shape id (Internal use)
  57125. */
  57126. this.idxInShape = 0;
  57127. /**
  57128. * Still set as invisible in order to skip useless computations (Internal use)
  57129. */
  57130. this._stillInvisible = false;
  57131. /**
  57132. * Last computed particle rotation matrix
  57133. */
  57134. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57135. /**
  57136. * Parent particle Id, if any.
  57137. * Default null.
  57138. */
  57139. this.parentId = null;
  57140. /**
  57141. * Internal global position in the SPS.
  57142. */
  57143. this._globalPosition = BABYLON.Vector3.Zero();
  57144. this.idx = particleIndex;
  57145. this._pos = positionIndex;
  57146. this._ind = indiceIndex;
  57147. this._model = model;
  57148. this.shapeId = shapeId;
  57149. this.idxInShape = idxInShape;
  57150. this._sps = sps;
  57151. if (modelBoundingInfo) {
  57152. this._modelBoundingInfo = modelBoundingInfo;
  57153. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57154. }
  57155. }
  57156. Object.defineProperty(SolidParticle.prototype, "scale", {
  57157. /**
  57158. * Legacy support, changed scale to scaling
  57159. */
  57160. get: function () {
  57161. return this.scaling;
  57162. },
  57163. /**
  57164. * Legacy support, changed scale to scaling
  57165. */
  57166. set: function (scale) {
  57167. this.scaling = scale;
  57168. },
  57169. enumerable: true,
  57170. configurable: true
  57171. });
  57172. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57173. /**
  57174. * Legacy support, changed quaternion to rotationQuaternion
  57175. */
  57176. get: function () {
  57177. return this.rotationQuaternion;
  57178. },
  57179. /**
  57180. * Legacy support, changed quaternion to rotationQuaternion
  57181. */
  57182. set: function (q) {
  57183. this.rotationQuaternion = q;
  57184. },
  57185. enumerable: true,
  57186. configurable: true
  57187. });
  57188. /**
  57189. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57190. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57191. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57192. * @returns true if it intersects
  57193. */
  57194. SolidParticle.prototype.intersectsMesh = function (target) {
  57195. if (!this._boundingInfo || !target._boundingInfo) {
  57196. return false;
  57197. }
  57198. if (this._sps._bSphereOnly) {
  57199. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57200. }
  57201. return this._boundingInfo.intersects(target._boundingInfo, false);
  57202. };
  57203. return SolidParticle;
  57204. }());
  57205. BABYLON.SolidParticle = SolidParticle;
  57206. /**
  57207. * Represents the shape of the model used by one particle of a solid particle system.
  57208. * SPS internal tool, don't use it manually.
  57209. */
  57210. var ModelShape = /** @class */ (function () {
  57211. /**
  57212. * 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.
  57213. * SPS internal tool, don't use it manually.
  57214. * @hidden
  57215. */
  57216. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57217. /**
  57218. * length of the shape in the model indices array (internal use)
  57219. */
  57220. this._indicesLength = 0;
  57221. this.shapeID = id;
  57222. this._shape = shape;
  57223. this._indicesLength = indicesLength;
  57224. this._shapeUV = shapeUV;
  57225. this._positionFunction = posFunction;
  57226. this._vertexFunction = vtxFunction;
  57227. }
  57228. return ModelShape;
  57229. }());
  57230. BABYLON.ModelShape = ModelShape;
  57231. /**
  57232. * Represents a Depth Sorted Particle in the solid particle system.
  57233. */
  57234. var DepthSortedParticle = /** @class */ (function () {
  57235. function DepthSortedParticle() {
  57236. /**
  57237. * Index of the particle in the "indices" array
  57238. */
  57239. this.ind = 0;
  57240. /**
  57241. * Length of the particle shape in the "indices" array
  57242. */
  57243. this.indicesLength = 0;
  57244. /**
  57245. * Squared distance from the particle to the camera
  57246. */
  57247. this.sqDistance = 0.0;
  57248. }
  57249. return DepthSortedParticle;
  57250. }());
  57251. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57252. })(BABYLON || (BABYLON = {}));
  57253. //# sourceMappingURL=babylon.solidParticle.js.map
  57254. var BABYLON;
  57255. (function (BABYLON) {
  57256. /**
  57257. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57258. *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.
  57259. * The SPS is also a particle system. It provides some methods to manage the particles.
  57260. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57261. *
  57262. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57263. */
  57264. var SolidParticleSystem = /** @class */ (function () {
  57265. /**
  57266. * Creates a SPS (Solid Particle System) object.
  57267. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57268. * @param scene (Scene) is the scene in which the SPS is added.
  57269. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57270. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57271. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57272. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57273. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57274. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57275. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57276. */
  57277. function SolidParticleSystem(name, scene, options) {
  57278. /**
  57279. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57280. * Example : var p = SPS.particles[i];
  57281. */
  57282. this.particles = new Array();
  57283. /**
  57284. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57285. */
  57286. this.nbParticles = 0;
  57287. /**
  57288. * If the particles must ever face the camera (default false). Useful for planar particles.
  57289. */
  57290. this.billboard = false;
  57291. /**
  57292. * Recompute normals when adding a shape
  57293. */
  57294. this.recomputeNormals = true;
  57295. /**
  57296. * This a counter ofr your own usage. It's not set by any SPS functions.
  57297. */
  57298. this.counter = 0;
  57299. /**
  57300. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57301. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57302. */
  57303. this.vars = {};
  57304. /**
  57305. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57306. */
  57307. this._bSphereOnly = false;
  57308. /**
  57309. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57310. */
  57311. this._bSphereRadiusFactor = 1.0;
  57312. this._positions = new Array();
  57313. this._indices = new Array();
  57314. this._normals = new Array();
  57315. this._colors = new Array();
  57316. this._uvs = new Array();
  57317. this._index = 0; // indices index
  57318. this._updatable = true;
  57319. this._pickable = false;
  57320. this._isVisibilityBoxLocked = false;
  57321. this._alwaysVisible = false;
  57322. this._depthSort = false;
  57323. this._shapeCounter = 0;
  57324. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57325. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57326. this._computeParticleColor = true;
  57327. this._computeParticleTexture = true;
  57328. this._computeParticleRotation = true;
  57329. this._computeParticleVertex = false;
  57330. this._computeBoundingBox = false;
  57331. this._depthSortParticles = true;
  57332. this._cam_axisZ = BABYLON.Vector3.Zero();
  57333. this._cam_axisY = BABYLON.Vector3.Zero();
  57334. this._cam_axisX = BABYLON.Vector3.Zero();
  57335. this._axisZ = BABYLON.Axis.Z;
  57336. this._camDir = BABYLON.Vector3.Zero();
  57337. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57338. this._rotMatrix = new BABYLON.Matrix();
  57339. this._invertMatrix = new BABYLON.Matrix();
  57340. this._rotated = BABYLON.Vector3.Zero();
  57341. this._quaternion = new BABYLON.Quaternion();
  57342. this._vertex = BABYLON.Vector3.Zero();
  57343. this._normal = BABYLON.Vector3.Zero();
  57344. this._yaw = 0.0;
  57345. this._pitch = 0.0;
  57346. this._roll = 0.0;
  57347. this._halfroll = 0.0;
  57348. this._halfpitch = 0.0;
  57349. this._halfyaw = 0.0;
  57350. this._sinRoll = 0.0;
  57351. this._cosRoll = 0.0;
  57352. this._sinPitch = 0.0;
  57353. this._cosPitch = 0.0;
  57354. this._sinYaw = 0.0;
  57355. this._cosYaw = 0.0;
  57356. this._mustUnrotateFixedNormals = false;
  57357. this._minimum = BABYLON.Vector3.Zero();
  57358. this._maximum = BABYLON.Vector3.Zero();
  57359. this._minBbox = BABYLON.Vector3.Zero();
  57360. this._maxBbox = BABYLON.Vector3.Zero();
  57361. this._particlesIntersect = false;
  57362. this._depthSortFunction = function (p1, p2) {
  57363. return (p2.sqDistance - p1.sqDistance);
  57364. };
  57365. this._needs32Bits = false;
  57366. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57367. this._scaledPivot = BABYLON.Vector3.Zero();
  57368. this._particleHasParent = false;
  57369. this.name = name;
  57370. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57371. this._camera = scene.activeCamera;
  57372. this._pickable = options ? options.isPickable : false;
  57373. this._depthSort = options ? options.enableDepthSort : false;
  57374. this._particlesIntersect = options ? options.particleIntersection : false;
  57375. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57376. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57377. if (options && options.updatable !== undefined) {
  57378. this._updatable = options.updatable;
  57379. }
  57380. else {
  57381. this._updatable = true;
  57382. }
  57383. if (this._pickable) {
  57384. this.pickedParticles = [];
  57385. }
  57386. if (this._depthSort) {
  57387. this.depthSortedParticles = [];
  57388. }
  57389. }
  57390. /**
  57391. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57392. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57393. * @returns the created mesh
  57394. */
  57395. SolidParticleSystem.prototype.buildMesh = function () {
  57396. if (this.nbParticles === 0) {
  57397. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57398. this.addShape(triangle, 1);
  57399. triangle.dispose();
  57400. }
  57401. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57402. this._positions32 = new Float32Array(this._positions);
  57403. this._uvs32 = new Float32Array(this._uvs);
  57404. this._colors32 = new Float32Array(this._colors);
  57405. if (this.recomputeNormals) {
  57406. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57407. }
  57408. this._normals32 = new Float32Array(this._normals);
  57409. this._fixedNormal32 = new Float32Array(this._normals);
  57410. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57411. this._unrotateFixedNormals();
  57412. }
  57413. var vertexData = new BABYLON.VertexData();
  57414. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57415. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57416. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57417. if (this._uvs32.length > 0) {
  57418. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57419. }
  57420. if (this._colors32.length > 0) {
  57421. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57422. }
  57423. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57424. vertexData.applyToMesh(mesh, this._updatable);
  57425. this.mesh = mesh;
  57426. this.mesh.isPickable = this._pickable;
  57427. // free memory
  57428. if (!this._depthSort) {
  57429. this._indices = null;
  57430. }
  57431. this._positions = null;
  57432. this._normals = null;
  57433. this._uvs = null;
  57434. this._colors = null;
  57435. if (!this._updatable) {
  57436. this.particles.length = 0;
  57437. }
  57438. return mesh;
  57439. };
  57440. /**
  57441. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57442. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57443. * Thus the particles generated from `digest()` have their property `position` set yet.
  57444. * @param mesh ( Mesh ) is the mesh to be digested
  57445. * @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
  57446. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57447. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57448. * @returns the current SPS
  57449. */
  57450. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57451. var size = (options && options.facetNb) || 1;
  57452. var number = (options && options.number) || 0;
  57453. var delta = (options && options.delta) || 0;
  57454. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57455. var meshInd = mesh.getIndices();
  57456. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57457. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57458. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57459. var f = 0; // facet counter
  57460. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57461. // compute size from number
  57462. if (number) {
  57463. number = (number > totalFacets) ? totalFacets : number;
  57464. size = Math.round(totalFacets / number);
  57465. delta = 0;
  57466. }
  57467. else {
  57468. size = (size > totalFacets) ? totalFacets : size;
  57469. }
  57470. var facetPos = []; // submesh positions
  57471. var facetInd = []; // submesh indices
  57472. var facetUV = []; // submesh UV
  57473. var facetCol = []; // submesh colors
  57474. var barycenter = BABYLON.Vector3.Zero();
  57475. var sizeO = size;
  57476. while (f < totalFacets) {
  57477. size = sizeO + Math.floor((1 + delta) * Math.random());
  57478. if (f > totalFacets - size) {
  57479. size = totalFacets - f;
  57480. }
  57481. // reset temp arrays
  57482. facetPos.length = 0;
  57483. facetInd.length = 0;
  57484. facetUV.length = 0;
  57485. facetCol.length = 0;
  57486. // iterate over "size" facets
  57487. var fi = 0;
  57488. for (var j = f * 3; j < (f + size) * 3; j++) {
  57489. facetInd.push(fi);
  57490. var i = meshInd[j];
  57491. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57492. if (meshUV) {
  57493. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57494. }
  57495. if (meshCol) {
  57496. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57497. }
  57498. fi++;
  57499. }
  57500. // create a model shape for each single particle
  57501. var idx = this.nbParticles;
  57502. var shape = this._posToShape(facetPos);
  57503. var shapeUV = this._uvsToShapeUV(facetUV);
  57504. // compute the barycenter of the shape
  57505. var v;
  57506. for (v = 0; v < shape.length; v++) {
  57507. barycenter.addInPlace(shape[v]);
  57508. }
  57509. barycenter.scaleInPlace(1 / shape.length);
  57510. // shift the shape from its barycenter to the origin
  57511. for (v = 0; v < shape.length; v++) {
  57512. shape[v].subtractInPlace(barycenter);
  57513. }
  57514. var bInfo;
  57515. if (this._particlesIntersect) {
  57516. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57517. }
  57518. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57519. // add the particle in the SPS
  57520. var currentPos = this._positions.length;
  57521. var currentInd = this._indices.length;
  57522. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57523. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57524. // initialize the particle position
  57525. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57526. this._index += shape.length;
  57527. idx++;
  57528. this.nbParticles++;
  57529. this._shapeCounter++;
  57530. f += size;
  57531. }
  57532. return this;
  57533. };
  57534. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57535. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57536. var index = 0;
  57537. var idx = 0;
  57538. for (var p = 0; p < this.particles.length; p++) {
  57539. this._particle = this.particles[p];
  57540. this._shape = this._particle._model._shape;
  57541. if (this._particle.rotationQuaternion) {
  57542. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57543. }
  57544. else {
  57545. this._yaw = this._particle.rotation.y;
  57546. this._pitch = this._particle.rotation.x;
  57547. this._roll = this._particle.rotation.z;
  57548. this._quaternionRotationYPR();
  57549. }
  57550. this._quaternionToRotationMatrix();
  57551. this._rotMatrix.invertToRef(this._invertMatrix);
  57552. for (var pt = 0; pt < this._shape.length; pt++) {
  57553. idx = index + pt * 3;
  57554. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57555. this._fixedNormal32[idx] = this._normal.x;
  57556. this._fixedNormal32[idx + 1] = this._normal.y;
  57557. this._fixedNormal32[idx + 2] = this._normal.z;
  57558. }
  57559. index = idx + 3;
  57560. }
  57561. };
  57562. //reset copy
  57563. SolidParticleSystem.prototype._resetCopy = function () {
  57564. this._copy.position.x = 0;
  57565. this._copy.position.y = 0;
  57566. this._copy.position.z = 0;
  57567. this._copy.rotation.x = 0;
  57568. this._copy.rotation.y = 0;
  57569. this._copy.rotation.z = 0;
  57570. this._copy.rotationQuaternion = null;
  57571. this._copy.scaling.x = 1.0;
  57572. this._copy.scaling.y = 1.0;
  57573. this._copy.scaling.z = 1.0;
  57574. this._copy.uvs.x = 0;
  57575. this._copy.uvs.y = 0;
  57576. this._copy.uvs.z = 1.0;
  57577. this._copy.uvs.w = 1.0;
  57578. this._copy.color = null;
  57579. this._copy.translateFromPivot = false;
  57580. };
  57581. // _meshBuilder : inserts the shape model in the global SPS mesh
  57582. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57583. var i;
  57584. var u = 0;
  57585. var c = 0;
  57586. var n = 0;
  57587. this._resetCopy();
  57588. if (options && options.positionFunction) { // call to custom positionFunction
  57589. options.positionFunction(this._copy, idx, idxInShape);
  57590. this._mustUnrotateFixedNormals = true;
  57591. }
  57592. if (this._copy.rotationQuaternion) {
  57593. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57594. }
  57595. else {
  57596. this._yaw = this._copy.rotation.y;
  57597. this._pitch = this._copy.rotation.x;
  57598. this._roll = this._copy.rotation.z;
  57599. this._quaternionRotationYPR();
  57600. }
  57601. this._quaternionToRotationMatrix();
  57602. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57603. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57604. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57605. if (this._copy.translateFromPivot) {
  57606. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57607. }
  57608. else {
  57609. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57610. }
  57611. for (i = 0; i < shape.length; i++) {
  57612. this._vertex.x = shape[i].x;
  57613. this._vertex.y = shape[i].y;
  57614. this._vertex.z = shape[i].z;
  57615. if (options && options.vertexFunction) {
  57616. options.vertexFunction(this._copy, this._vertex, i);
  57617. }
  57618. this._vertex.x *= this._copy.scaling.x;
  57619. this._vertex.y *= this._copy.scaling.y;
  57620. this._vertex.z *= this._copy.scaling.z;
  57621. this._vertex.x -= this._scaledPivot.x;
  57622. this._vertex.y -= this._scaledPivot.y;
  57623. this._vertex.z -= this._scaledPivot.z;
  57624. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57625. this._rotated.addInPlace(this._pivotBackTranslation);
  57626. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57627. if (meshUV) {
  57628. 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);
  57629. u += 2;
  57630. }
  57631. if (this._copy.color) {
  57632. this._color = this._copy.color;
  57633. }
  57634. else if (meshCol && meshCol[c] !== undefined) {
  57635. this._color.r = meshCol[c];
  57636. this._color.g = meshCol[c + 1];
  57637. this._color.b = meshCol[c + 2];
  57638. this._color.a = meshCol[c + 3];
  57639. }
  57640. else {
  57641. this._color.r = 1.0;
  57642. this._color.g = 1.0;
  57643. this._color.b = 1.0;
  57644. this._color.a = 1.0;
  57645. }
  57646. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57647. c += 4;
  57648. if (!this.recomputeNormals && meshNor) {
  57649. this._normal.x = meshNor[n];
  57650. this._normal.y = meshNor[n + 1];
  57651. this._normal.z = meshNor[n + 2];
  57652. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57653. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57654. n += 3;
  57655. }
  57656. }
  57657. for (i = 0; i < meshInd.length; i++) {
  57658. var current_ind = p + meshInd[i];
  57659. indices.push(current_ind);
  57660. if (current_ind > 65535) {
  57661. this._needs32Bits = true;
  57662. }
  57663. }
  57664. if (this._pickable) {
  57665. var nbfaces = meshInd.length / 3;
  57666. for (i = 0; i < nbfaces; i++) {
  57667. this.pickedParticles.push({ idx: idx, faceId: i });
  57668. }
  57669. }
  57670. if (this._depthSort) {
  57671. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57672. }
  57673. return this._copy;
  57674. };
  57675. // returns a shape array from positions array
  57676. SolidParticleSystem.prototype._posToShape = function (positions) {
  57677. var shape = [];
  57678. for (var i = 0; i < positions.length; i += 3) {
  57679. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57680. }
  57681. return shape;
  57682. };
  57683. // returns a shapeUV array from a Vector4 uvs
  57684. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57685. var shapeUV = [];
  57686. if (uvs) {
  57687. for (var i = 0; i < uvs.length; i++)
  57688. shapeUV.push(uvs[i]);
  57689. }
  57690. return shapeUV;
  57691. };
  57692. // adds a new particle object in the particles array
  57693. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57694. if (bInfo === void 0) { bInfo = null; }
  57695. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57696. this.particles.push(sp);
  57697. return sp;
  57698. };
  57699. /**
  57700. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57701. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57702. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57703. * @param nb (positive integer) the number of particles to be created from this model
  57704. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57705. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57706. * @returns the number of shapes in the system
  57707. */
  57708. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57709. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57710. var meshInd = mesh.getIndices();
  57711. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57712. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57713. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57714. var bbInfo;
  57715. if (this._particlesIntersect) {
  57716. bbInfo = mesh.getBoundingInfo();
  57717. }
  57718. var shape = this._posToShape(meshPos);
  57719. var shapeUV = this._uvsToShapeUV(meshUV);
  57720. var posfunc = options ? options.positionFunction : null;
  57721. var vtxfunc = options ? options.vertexFunction : null;
  57722. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57723. // particles
  57724. var sp;
  57725. var currentCopy;
  57726. var idx = this.nbParticles;
  57727. for (var i = 0; i < nb; i++) {
  57728. var currentPos = this._positions.length;
  57729. var currentInd = this._indices.length;
  57730. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57731. if (this._updatable) {
  57732. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57733. sp.position.copyFrom(currentCopy.position);
  57734. sp.rotation.copyFrom(currentCopy.rotation);
  57735. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57736. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57737. }
  57738. if (currentCopy.color && sp.color) {
  57739. sp.color.copyFrom(currentCopy.color);
  57740. }
  57741. sp.scaling.copyFrom(currentCopy.scaling);
  57742. sp.uvs.copyFrom(currentCopy.uvs);
  57743. }
  57744. this._index += shape.length;
  57745. idx++;
  57746. }
  57747. this.nbParticles += nb;
  57748. this._shapeCounter++;
  57749. return this._shapeCounter - 1;
  57750. };
  57751. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57752. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57753. this._resetCopy();
  57754. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57755. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57756. }
  57757. if (this._copy.rotationQuaternion) {
  57758. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57759. }
  57760. else {
  57761. this._yaw = this._copy.rotation.y;
  57762. this._pitch = this._copy.rotation.x;
  57763. this._roll = this._copy.rotation.z;
  57764. this._quaternionRotationYPR();
  57765. }
  57766. this._quaternionToRotationMatrix();
  57767. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57768. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57769. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57770. if (this._copy.translateFromPivot) {
  57771. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57772. }
  57773. else {
  57774. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57775. }
  57776. this._shape = particle._model._shape;
  57777. for (var pt = 0; pt < this._shape.length; pt++) {
  57778. this._vertex.x = this._shape[pt].x;
  57779. this._vertex.y = this._shape[pt].y;
  57780. this._vertex.z = this._shape[pt].z;
  57781. if (particle._model._vertexFunction) {
  57782. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57783. }
  57784. this._vertex.x *= this._copy.scaling.x;
  57785. this._vertex.y *= this._copy.scaling.y;
  57786. this._vertex.z *= this._copy.scaling.z;
  57787. this._vertex.x -= this._scaledPivot.x;
  57788. this._vertex.y -= this._scaledPivot.y;
  57789. this._vertex.z -= this._scaledPivot.z;
  57790. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57791. this._rotated.addInPlace(this._pivotBackTranslation);
  57792. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57793. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57794. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57795. }
  57796. particle.position.x = 0.0;
  57797. particle.position.y = 0.0;
  57798. particle.position.z = 0.0;
  57799. particle.rotation.x = 0.0;
  57800. particle.rotation.y = 0.0;
  57801. particle.rotation.z = 0.0;
  57802. particle.rotationQuaternion = null;
  57803. particle.scaling.x = 1.0;
  57804. particle.scaling.y = 1.0;
  57805. particle.scaling.z = 1.0;
  57806. particle.uvs.x = 0.0;
  57807. particle.uvs.y = 0.0;
  57808. particle.uvs.z = 1.0;
  57809. particle.uvs.w = 1.0;
  57810. particle.pivot.x = 0.0;
  57811. particle.pivot.y = 0.0;
  57812. particle.pivot.z = 0.0;
  57813. particle.translateFromPivot = false;
  57814. particle.parentId = null;
  57815. };
  57816. /**
  57817. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57818. * @returns the SPS.
  57819. */
  57820. SolidParticleSystem.prototype.rebuildMesh = function () {
  57821. for (var p = 0; p < this.particles.length; p++) {
  57822. this._rebuildParticle(this.particles[p]);
  57823. }
  57824. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57825. return this;
  57826. };
  57827. /**
  57828. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57829. * This method calls `updateParticle()` for each particle of the SPS.
  57830. * For an animated SPS, it is usually called within the render loop.
  57831. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57832. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57833. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57834. * @returns the SPS.
  57835. */
  57836. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57837. if (start === void 0) { start = 0; }
  57838. if (end === void 0) { end = this.nbParticles - 1; }
  57839. if (update === void 0) { update = true; }
  57840. if (!this._updatable) {
  57841. return this;
  57842. }
  57843. // custom beforeUpdate
  57844. this.beforeUpdateParticles(start, end, update);
  57845. this._cam_axisX.x = 1.0;
  57846. this._cam_axisX.y = 0.0;
  57847. this._cam_axisX.z = 0.0;
  57848. this._cam_axisY.x = 0.0;
  57849. this._cam_axisY.y = 1.0;
  57850. this._cam_axisY.z = 0.0;
  57851. this._cam_axisZ.x = 0.0;
  57852. this._cam_axisZ.y = 0.0;
  57853. this._cam_axisZ.z = 1.0;
  57854. // cases when the World Matrix is to be computed first
  57855. if (this.billboard || this._depthSort) {
  57856. this.mesh.computeWorldMatrix(true);
  57857. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57858. }
  57859. // if the particles will always face the camera
  57860. if (this.billboard) {
  57861. // compute the camera position and un-rotate it by the current mesh rotation
  57862. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57863. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57864. this._cam_axisZ.normalize();
  57865. // same for camera up vector extracted from the cam view matrix
  57866. var view = this._camera.getViewMatrix(true);
  57867. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57868. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57869. this._cam_axisY.normalize();
  57870. this._cam_axisX.normalize();
  57871. }
  57872. // if depthSort, compute the camera global position in the mesh local system
  57873. if (this._depthSort) {
  57874. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57875. }
  57876. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57877. var idx = 0; // current position index in the global array positions32
  57878. var index = 0; // position start index in the global array positions32 of the current particle
  57879. var colidx = 0; // current color index in the global array colors32
  57880. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57881. var uvidx = 0; // current uv index in the global array uvs32
  57882. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57883. var pt = 0; // current index in the particle model shape
  57884. if (this.mesh.isFacetDataEnabled) {
  57885. this._computeBoundingBox = true;
  57886. }
  57887. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57888. if (this._computeBoundingBox) {
  57889. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  57890. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57891. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57892. }
  57893. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  57894. if (this.mesh._boundingInfo) {
  57895. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57896. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57897. }
  57898. }
  57899. }
  57900. // particle loop
  57901. index = this.particles[start]._pos;
  57902. var vpos = (index / 3) | 0;
  57903. colorIndex = vpos * 4;
  57904. uvIndex = vpos * 2;
  57905. for (var p = start; p <= end; p++) {
  57906. this._particle = this.particles[p];
  57907. this._shape = this._particle._model._shape;
  57908. this._shapeUV = this._particle._model._shapeUV;
  57909. // call to custom user function to update the particle properties
  57910. this.updateParticle(this._particle);
  57911. // camera-particle distance for depth sorting
  57912. if (this._depthSort && this._depthSortParticles) {
  57913. var dsp = this.depthSortedParticles[p];
  57914. dsp.ind = this._particle._ind;
  57915. dsp.indicesLength = this._particle._model._indicesLength;
  57916. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57917. }
  57918. // skip the computations for inactive or already invisible particles
  57919. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57920. // increment indexes for the next particle
  57921. pt = this._shape.length;
  57922. index += pt * 3;
  57923. colorIndex += pt * 4;
  57924. uvIndex += pt * 2;
  57925. continue;
  57926. }
  57927. if (this._particle.isVisible) {
  57928. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57929. this._particleHasParent = (this._particle.parentId !== null);
  57930. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57931. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57932. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57933. // particle rotation matrix
  57934. if (this.billboard) {
  57935. this._particle.rotation.x = 0.0;
  57936. this._particle.rotation.y = 0.0;
  57937. }
  57938. if (this._computeParticleRotation || this.billboard) {
  57939. if (this._particle.rotationQuaternion) {
  57940. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57941. }
  57942. else {
  57943. this._yaw = this._particle.rotation.y;
  57944. this._pitch = this._particle.rotation.x;
  57945. this._roll = this._particle.rotation.z;
  57946. this._quaternionRotationYPR();
  57947. }
  57948. this._quaternionToRotationMatrix();
  57949. }
  57950. if (this._particleHasParent) {
  57951. this._parent = this.particles[this._particle.parentId];
  57952. 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];
  57953. 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];
  57954. 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];
  57955. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57956. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57957. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57958. if (this._computeParticleRotation || this.billboard) {
  57959. 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];
  57960. 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];
  57961. 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];
  57962. 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];
  57963. 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];
  57964. 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];
  57965. 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];
  57966. 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];
  57967. 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];
  57968. }
  57969. }
  57970. else {
  57971. this._particle._globalPosition.x = this._particle.position.x;
  57972. this._particle._globalPosition.y = this._particle.position.y;
  57973. this._particle._globalPosition.z = this._particle.position.z;
  57974. if (this._computeParticleRotation || this.billboard) {
  57975. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57976. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57977. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57978. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57979. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57980. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57981. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57982. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57983. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57984. }
  57985. }
  57986. if (this._particle.translateFromPivot) {
  57987. this._pivotBackTranslation.x = 0.0;
  57988. this._pivotBackTranslation.y = 0.0;
  57989. this._pivotBackTranslation.z = 0.0;
  57990. }
  57991. else {
  57992. this._pivotBackTranslation.x = this._scaledPivot.x;
  57993. this._pivotBackTranslation.y = this._scaledPivot.y;
  57994. this._pivotBackTranslation.z = this._scaledPivot.z;
  57995. }
  57996. // particle vertex loop
  57997. for (pt = 0; pt < this._shape.length; pt++) {
  57998. idx = index + pt * 3;
  57999. colidx = colorIndex + pt * 4;
  58000. uvidx = uvIndex + pt * 2;
  58001. this._vertex.x = this._shape[pt].x;
  58002. this._vertex.y = this._shape[pt].y;
  58003. this._vertex.z = this._shape[pt].z;
  58004. if (this._computeParticleVertex) {
  58005. this.updateParticleVertex(this._particle, this._vertex, pt);
  58006. }
  58007. // positions
  58008. this._vertex.x *= this._particle.scaling.x;
  58009. this._vertex.y *= this._particle.scaling.y;
  58010. this._vertex.z *= this._particle.scaling.z;
  58011. this._vertex.x -= this._scaledPivot.x;
  58012. this._vertex.y -= this._scaledPivot.y;
  58013. this._vertex.z -= this._scaledPivot.z;
  58014. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58015. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58016. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58017. this._rotated.x += this._pivotBackTranslation.x;
  58018. this._rotated.y += this._pivotBackTranslation.y;
  58019. this._rotated.z += this._pivotBackTranslation.z;
  58020. 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;
  58021. 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;
  58022. 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;
  58023. if (this._computeBoundingBox) {
  58024. if (this._positions32[idx] < this._minimum.x) {
  58025. this._minimum.x = this._positions32[idx];
  58026. }
  58027. if (this._positions32[idx] > this._maximum.x) {
  58028. this._maximum.x = this._positions32[idx];
  58029. }
  58030. if (this._positions32[idx + 1] < this._minimum.y) {
  58031. this._minimum.y = this._positions32[idx + 1];
  58032. }
  58033. if (this._positions32[idx + 1] > this._maximum.y) {
  58034. this._maximum.y = this._positions32[idx + 1];
  58035. }
  58036. if (this._positions32[idx + 2] < this._minimum.z) {
  58037. this._minimum.z = this._positions32[idx + 2];
  58038. }
  58039. if (this._positions32[idx + 2] > this._maximum.z) {
  58040. this._maximum.z = this._positions32[idx + 2];
  58041. }
  58042. }
  58043. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58044. if (!this._computeParticleVertex) {
  58045. this._normal.x = this._fixedNormal32[idx];
  58046. this._normal.y = this._fixedNormal32[idx + 1];
  58047. this._normal.z = this._fixedNormal32[idx + 2];
  58048. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58049. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58050. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58051. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58052. 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;
  58053. 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;
  58054. }
  58055. if (this._computeParticleColor && this._particle.color) {
  58056. this._colors32[colidx] = this._particle.color.r;
  58057. this._colors32[colidx + 1] = this._particle.color.g;
  58058. this._colors32[colidx + 2] = this._particle.color.b;
  58059. this._colors32[colidx + 3] = this._particle.color.a;
  58060. }
  58061. if (this._computeParticleTexture) {
  58062. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58063. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58064. }
  58065. }
  58066. }
  58067. // particle just set invisible : scaled to zero and positioned at the origin
  58068. else {
  58069. this._particle._stillInvisible = true; // mark the particle as invisible
  58070. for (pt = 0; pt < this._shape.length; pt++) {
  58071. idx = index + pt * 3;
  58072. colidx = colorIndex + pt * 4;
  58073. uvidx = uvIndex + pt * 2;
  58074. this._positions32[idx] = 0.0;
  58075. this._positions32[idx + 1] = 0.0;
  58076. this._positions32[idx + 2] = 0.0;
  58077. this._normals32[idx] = 0.0;
  58078. this._normals32[idx + 1] = 0.0;
  58079. this._normals32[idx + 2] = 0.0;
  58080. if (this._computeParticleColor && this._particle.color) {
  58081. this._colors32[colidx] = this._particle.color.r;
  58082. this._colors32[colidx + 1] = this._particle.color.g;
  58083. this._colors32[colidx + 2] = this._particle.color.b;
  58084. this._colors32[colidx + 3] = this._particle.color.a;
  58085. }
  58086. if (this._computeParticleTexture) {
  58087. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58088. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58089. }
  58090. }
  58091. }
  58092. // if the particle intersections must be computed : update the bbInfo
  58093. if (this._particlesIntersect) {
  58094. var bInfo = this._particle._boundingInfo;
  58095. var bBox = bInfo.boundingBox;
  58096. var bSphere = bInfo.boundingSphere;
  58097. if (!this._bSphereOnly) {
  58098. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58099. for (var b = 0; b < bBox.vectors.length; b++) {
  58100. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58101. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58102. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58103. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58104. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58105. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58106. 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;
  58107. 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;
  58108. 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;
  58109. }
  58110. bBox._update(this.mesh._worldMatrix);
  58111. }
  58112. // place and scale the particle bouding sphere in the SPS local system, then update it
  58113. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58114. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58115. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58116. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58117. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58118. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58119. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58120. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58121. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58122. 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));
  58123. bSphere._update(this.mesh._worldMatrix);
  58124. }
  58125. // increment indexes for the next particle
  58126. index = idx + 3;
  58127. colorIndex = colidx + 4;
  58128. uvIndex = uvidx + 2;
  58129. }
  58130. // if the VBO must be updated
  58131. if (update) {
  58132. if (this._computeParticleColor) {
  58133. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58134. }
  58135. if (this._computeParticleTexture) {
  58136. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58137. }
  58138. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58139. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58140. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58141. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58142. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58143. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58144. for (var i = 0; i < this._normals32.length; i++) {
  58145. this._fixedNormal32[i] = this._normals32[i];
  58146. }
  58147. }
  58148. if (!this.mesh.areNormalsFrozen) {
  58149. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58150. }
  58151. }
  58152. if (this._depthSort && this._depthSortParticles) {
  58153. this.depthSortedParticles.sort(this._depthSortFunction);
  58154. var dspl = this.depthSortedParticles.length;
  58155. var sorted = 0;
  58156. var lind = 0;
  58157. var sind = 0;
  58158. var sid = 0;
  58159. for (sorted = 0; sorted < dspl; sorted++) {
  58160. lind = this.depthSortedParticles[sorted].indicesLength;
  58161. sind = this.depthSortedParticles[sorted].ind;
  58162. for (var i = 0; i < lind; i++) {
  58163. this._indices32[sid] = this._indices[sind + i];
  58164. sid++;
  58165. }
  58166. }
  58167. this.mesh.updateIndices(this._indices32);
  58168. }
  58169. }
  58170. if (this._computeBoundingBox) {
  58171. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58172. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58173. }
  58174. this.afterUpdateParticles(start, end, update);
  58175. return this;
  58176. };
  58177. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58178. this._halfroll = this._roll * 0.5;
  58179. this._halfpitch = this._pitch * 0.5;
  58180. this._halfyaw = this._yaw * 0.5;
  58181. this._sinRoll = Math.sin(this._halfroll);
  58182. this._cosRoll = Math.cos(this._halfroll);
  58183. this._sinPitch = Math.sin(this._halfpitch);
  58184. this._cosPitch = Math.cos(this._halfpitch);
  58185. this._sinYaw = Math.sin(this._halfyaw);
  58186. this._cosYaw = Math.cos(this._halfyaw);
  58187. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58188. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58189. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58190. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58191. };
  58192. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58193. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58194. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58195. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58196. this._rotMatrix.m[3] = 0;
  58197. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58198. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58199. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58200. this._rotMatrix.m[7] = 0;
  58201. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58202. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58203. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58204. this._rotMatrix.m[11] = 0;
  58205. this._rotMatrix.m[12] = 0;
  58206. this._rotMatrix.m[13] = 0;
  58207. this._rotMatrix.m[14] = 0;
  58208. this._rotMatrix.m[15] = 1.0;
  58209. };
  58210. /**
  58211. * Disposes the SPS.
  58212. */
  58213. SolidParticleSystem.prototype.dispose = function () {
  58214. this.mesh.dispose();
  58215. this.vars = null;
  58216. // drop references to internal big arrays for the GC
  58217. this._positions = null;
  58218. this._indices = null;
  58219. this._normals = null;
  58220. this._uvs = null;
  58221. this._colors = null;
  58222. this._indices32 = null;
  58223. this._positions32 = null;
  58224. this._normals32 = null;
  58225. this._fixedNormal32 = null;
  58226. this._uvs32 = null;
  58227. this._colors32 = null;
  58228. this.pickedParticles = null;
  58229. };
  58230. /**
  58231. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58232. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58233. * @returns the SPS.
  58234. */
  58235. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58236. if (!this._isVisibilityBoxLocked) {
  58237. this.mesh.refreshBoundingInfo();
  58238. }
  58239. return this;
  58240. };
  58241. /**
  58242. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58243. * @param size the size (float) of the visibility box
  58244. * note : this doesn't lock the SPS mesh bounding box.
  58245. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58246. */
  58247. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58248. var vis = size / 2;
  58249. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58250. };
  58251. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58252. /**
  58253. * Gets whether the SPS as always visible or not
  58254. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58255. */
  58256. get: function () {
  58257. return this._alwaysVisible;
  58258. },
  58259. /**
  58260. * Sets the SPS as always visible or not
  58261. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58262. */
  58263. set: function (val) {
  58264. this._alwaysVisible = val;
  58265. this.mesh.alwaysSelectAsActiveMesh = val;
  58266. },
  58267. enumerable: true,
  58268. configurable: true
  58269. });
  58270. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58271. /**
  58272. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58273. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58274. */
  58275. get: function () {
  58276. return this._isVisibilityBoxLocked;
  58277. },
  58278. /**
  58279. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58280. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58281. */
  58282. set: function (val) {
  58283. this._isVisibilityBoxLocked = val;
  58284. var boundingInfo = this.mesh.getBoundingInfo();
  58285. boundingInfo.isLocked = val;
  58286. },
  58287. enumerable: true,
  58288. configurable: true
  58289. });
  58290. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58291. /**
  58292. * Gets if `setParticles()` computes the particle rotations or not.
  58293. * Default value : true. The SPS is faster when it's set to false.
  58294. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58295. */
  58296. get: function () {
  58297. return this._computeParticleRotation;
  58298. },
  58299. /**
  58300. * Tells to `setParticles()` to compute the particle rotations or not.
  58301. * Default value : true. The SPS is faster when it's set to false.
  58302. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58303. */
  58304. set: function (val) {
  58305. this._computeParticleRotation = val;
  58306. },
  58307. enumerable: true,
  58308. configurable: true
  58309. });
  58310. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58311. /**
  58312. * Gets if `setParticles()` computes the particle colors or not.
  58313. * Default value : true. The SPS is faster when it's set to false.
  58314. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58315. */
  58316. get: function () {
  58317. return this._computeParticleColor;
  58318. },
  58319. /**
  58320. * Tells to `setParticles()` to compute the particle colors or not.
  58321. * Default value : true. The SPS is faster when it's set to false.
  58322. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58323. */
  58324. set: function (val) {
  58325. this._computeParticleColor = val;
  58326. },
  58327. enumerable: true,
  58328. configurable: true
  58329. });
  58330. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58331. /**
  58332. * Gets if `setParticles()` computes the particle textures or not.
  58333. * Default value : true. The SPS is faster when it's set to false.
  58334. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58335. */
  58336. get: function () {
  58337. return this._computeParticleTexture;
  58338. },
  58339. set: function (val) {
  58340. this._computeParticleTexture = val;
  58341. },
  58342. enumerable: true,
  58343. configurable: true
  58344. });
  58345. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58346. /**
  58347. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58348. * Default value : false. The SPS is faster when it's set to false.
  58349. * Note : the particle custom vertex positions aren't stored values.
  58350. */
  58351. get: function () {
  58352. return this._computeParticleVertex;
  58353. },
  58354. /**
  58355. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58356. * Default value : false. The SPS is faster when it's set to false.
  58357. * Note : the particle custom vertex positions aren't stored values.
  58358. */
  58359. set: function (val) {
  58360. this._computeParticleVertex = val;
  58361. },
  58362. enumerable: true,
  58363. configurable: true
  58364. });
  58365. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58366. /**
  58367. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58368. */
  58369. get: function () {
  58370. return this._computeBoundingBox;
  58371. },
  58372. /**
  58373. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58374. */
  58375. set: function (val) {
  58376. this._computeBoundingBox = val;
  58377. },
  58378. enumerable: true,
  58379. configurable: true
  58380. });
  58381. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58382. /**
  58383. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58384. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58385. * Default : `true`
  58386. */
  58387. get: function () {
  58388. return this._depthSortParticles;
  58389. },
  58390. /**
  58391. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58392. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58393. * Default : `true`
  58394. */
  58395. set: function (val) {
  58396. this._depthSortParticles = val;
  58397. },
  58398. enumerable: true,
  58399. configurable: true
  58400. });
  58401. // =======================================================================
  58402. // Particle behavior logic
  58403. // these following methods may be overwritten by the user to fit his needs
  58404. /**
  58405. * This function does nothing. It may be overwritten to set all the particle first values.
  58406. * The SPS doesn't call this function, you may have to call it by your own.
  58407. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58408. */
  58409. SolidParticleSystem.prototype.initParticles = function () {
  58410. };
  58411. /**
  58412. * This function does nothing. It may be overwritten to recycle a particle.
  58413. * The SPS doesn't call this function, you may have to call it by your own.
  58414. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58415. * @param particle The particle to recycle
  58416. * @returns the recycled particle
  58417. */
  58418. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58419. return particle;
  58420. };
  58421. /**
  58422. * Updates a particle : this function should be overwritten by the user.
  58423. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58424. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58425. * @example : just set a particle position or velocity and recycle conditions
  58426. * @param particle The particle to update
  58427. * @returns the updated particle
  58428. */
  58429. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58430. return particle;
  58431. };
  58432. /**
  58433. * Updates a vertex of a particle : it can be overwritten by the user.
  58434. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58435. * @param particle the current particle
  58436. * @param vertex the current index of the current particle
  58437. * @param pt the index of the current vertex in the particle shape
  58438. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58439. * @example : just set a vertex particle position
  58440. * @returns the updated vertex
  58441. */
  58442. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58443. return vertex;
  58444. };
  58445. /**
  58446. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58447. * This does nothing and may be overwritten by the user.
  58448. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58449. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58450. * @param update the boolean update value actually passed to setParticles()
  58451. */
  58452. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58453. };
  58454. /**
  58455. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58456. * This will be passed three parameters.
  58457. * This does nothing and may be overwritten by the user.
  58458. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58459. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58460. * @param update the boolean update value actually passed to setParticles()
  58461. */
  58462. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58463. };
  58464. return SolidParticleSystem;
  58465. }());
  58466. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58467. })(BABYLON || (BABYLON = {}));
  58468. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58469. var BABYLON;
  58470. (function (BABYLON) {
  58471. var ShaderMaterial = /** @class */ (function (_super) {
  58472. __extends(ShaderMaterial, _super);
  58473. function ShaderMaterial(name, scene, shaderPath, options) {
  58474. var _this = _super.call(this, name, scene) || this;
  58475. _this._textures = {};
  58476. _this._textureArrays = {};
  58477. _this._floats = {};
  58478. _this._ints = {};
  58479. _this._floatsArrays = {};
  58480. _this._colors3 = {};
  58481. _this._colors3Arrays = {};
  58482. _this._colors4 = {};
  58483. _this._vectors2 = {};
  58484. _this._vectors3 = {};
  58485. _this._vectors4 = {};
  58486. _this._matrices = {};
  58487. _this._matrices3x3 = {};
  58488. _this._matrices2x2 = {};
  58489. _this._vectors2Arrays = {};
  58490. _this._vectors3Arrays = {};
  58491. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58492. _this._shaderPath = shaderPath;
  58493. options.needAlphaBlending = options.needAlphaBlending || false;
  58494. options.needAlphaTesting = options.needAlphaTesting || false;
  58495. options.attributes = options.attributes || ["position", "normal", "uv"];
  58496. options.uniforms = options.uniforms || ["worldViewProjection"];
  58497. options.uniformBuffers = options.uniformBuffers || [];
  58498. options.samplers = options.samplers || [];
  58499. options.defines = options.defines || [];
  58500. _this._options = options;
  58501. return _this;
  58502. }
  58503. ShaderMaterial.prototype.getClassName = function () {
  58504. return "ShaderMaterial";
  58505. };
  58506. ShaderMaterial.prototype.needAlphaBlending = function () {
  58507. return this._options.needAlphaBlending;
  58508. };
  58509. ShaderMaterial.prototype.needAlphaTesting = function () {
  58510. return this._options.needAlphaTesting;
  58511. };
  58512. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58513. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58514. this._options.uniforms.push(uniformName);
  58515. }
  58516. };
  58517. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58518. if (this._options.samplers.indexOf(name) === -1) {
  58519. this._options.samplers.push(name);
  58520. }
  58521. this._textures[name] = texture;
  58522. return this;
  58523. };
  58524. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58525. if (this._options.samplers.indexOf(name) === -1) {
  58526. this._options.samplers.push(name);
  58527. }
  58528. this._checkUniform(name);
  58529. this._textureArrays[name] = textures;
  58530. return this;
  58531. };
  58532. ShaderMaterial.prototype.setFloat = function (name, value) {
  58533. this._checkUniform(name);
  58534. this._floats[name] = value;
  58535. return this;
  58536. };
  58537. ShaderMaterial.prototype.setInt = function (name, value) {
  58538. this._checkUniform(name);
  58539. this._ints[name] = value;
  58540. return this;
  58541. };
  58542. ShaderMaterial.prototype.setFloats = function (name, value) {
  58543. this._checkUniform(name);
  58544. this._floatsArrays[name] = value;
  58545. return this;
  58546. };
  58547. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58548. this._checkUniform(name);
  58549. this._colors3[name] = value;
  58550. return this;
  58551. };
  58552. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58553. this._checkUniform(name);
  58554. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58555. color.toArray(arr, arr.length);
  58556. return arr;
  58557. }, []);
  58558. return this;
  58559. };
  58560. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58561. this._checkUniform(name);
  58562. this._colors4[name] = value;
  58563. return this;
  58564. };
  58565. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58566. this._checkUniform(name);
  58567. this._vectors2[name] = value;
  58568. return this;
  58569. };
  58570. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58571. this._checkUniform(name);
  58572. this._vectors3[name] = value;
  58573. return this;
  58574. };
  58575. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58576. this._checkUniform(name);
  58577. this._vectors4[name] = value;
  58578. return this;
  58579. };
  58580. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58581. this._checkUniform(name);
  58582. this._matrices[name] = value;
  58583. return this;
  58584. };
  58585. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58586. this._checkUniform(name);
  58587. this._matrices3x3[name] = value;
  58588. return this;
  58589. };
  58590. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58591. this._checkUniform(name);
  58592. this._matrices2x2[name] = value;
  58593. return this;
  58594. };
  58595. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58596. this._checkUniform(name);
  58597. this._vectors2Arrays[name] = value;
  58598. return this;
  58599. };
  58600. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58601. this._checkUniform(name);
  58602. this._vectors3Arrays[name] = value;
  58603. return this;
  58604. };
  58605. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58606. if (!mesh) {
  58607. return true;
  58608. }
  58609. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58610. return false;
  58611. }
  58612. return false;
  58613. };
  58614. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58615. var scene = this.getScene();
  58616. var engine = scene.getEngine();
  58617. if (!this.checkReadyOnEveryCall) {
  58618. if (this._renderId === scene.getRenderId()) {
  58619. if (this._checkCache(scene, mesh, useInstances)) {
  58620. return true;
  58621. }
  58622. }
  58623. }
  58624. // Instances
  58625. var defines = [];
  58626. var attribs = [];
  58627. var fallbacks = new BABYLON.EffectFallbacks();
  58628. if (useInstances) {
  58629. defines.push("#define INSTANCES");
  58630. }
  58631. for (var index = 0; index < this._options.defines.length; index++) {
  58632. defines.push(this._options.defines[index]);
  58633. }
  58634. for (var index = 0; index < this._options.attributes.length; index++) {
  58635. attribs.push(this._options.attributes[index]);
  58636. }
  58637. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58638. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58639. defines.push("#define VERTEXCOLOR");
  58640. }
  58641. // Bones
  58642. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58645. if (mesh.numBoneInfluencers > 4) {
  58646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58648. }
  58649. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58650. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58651. fallbacks.addCPUSkinningFallback(0, mesh);
  58652. if (this._options.uniforms.indexOf("mBones") === -1) {
  58653. this._options.uniforms.push("mBones");
  58654. }
  58655. }
  58656. else {
  58657. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58658. }
  58659. // Textures
  58660. for (var name in this._textures) {
  58661. if (!this._textures[name].isReady()) {
  58662. return false;
  58663. }
  58664. }
  58665. // Alpha test
  58666. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58667. defines.push("#define ALPHATEST");
  58668. }
  58669. var previousEffect = this._effect;
  58670. var join = defines.join("\n");
  58671. this._effect = engine.createEffect(this._shaderPath, {
  58672. attributes: attribs,
  58673. uniformsNames: this._options.uniforms,
  58674. uniformBuffersNames: this._options.uniformBuffers,
  58675. samplers: this._options.samplers,
  58676. defines: join,
  58677. fallbacks: fallbacks,
  58678. onCompiled: this.onCompiled,
  58679. onError: this.onError
  58680. }, engine);
  58681. if (!this._effect.isReady()) {
  58682. return false;
  58683. }
  58684. if (previousEffect !== this._effect) {
  58685. scene.resetCachedMaterial();
  58686. }
  58687. this._renderId = scene.getRenderId();
  58688. return true;
  58689. };
  58690. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58691. var scene = this.getScene();
  58692. if (!this._effect) {
  58693. return;
  58694. }
  58695. if (this._options.uniforms.indexOf("world") !== -1) {
  58696. this._effect.setMatrix("world", world);
  58697. }
  58698. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58699. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58700. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58701. }
  58702. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58703. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58704. }
  58705. };
  58706. ShaderMaterial.prototype.bind = function (world, mesh) {
  58707. // Std values
  58708. this.bindOnlyWorldMatrix(world);
  58709. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58710. if (this._options.uniforms.indexOf("view") !== -1) {
  58711. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58712. }
  58713. if (this._options.uniforms.indexOf("projection") !== -1) {
  58714. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58715. }
  58716. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58717. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58718. }
  58719. // Bones
  58720. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58721. var name;
  58722. // Texture
  58723. for (name in this._textures) {
  58724. this._effect.setTexture(name, this._textures[name]);
  58725. }
  58726. // Texture arrays
  58727. for (name in this._textureArrays) {
  58728. this._effect.setTextureArray(name, this._textureArrays[name]);
  58729. }
  58730. // Int
  58731. for (name in this._ints) {
  58732. this._effect.setInt(name, this._ints[name]);
  58733. }
  58734. // Float
  58735. for (name in this._floats) {
  58736. this._effect.setFloat(name, this._floats[name]);
  58737. }
  58738. // Floats
  58739. for (name in this._floatsArrays) {
  58740. this._effect.setArray(name, this._floatsArrays[name]);
  58741. }
  58742. // Color3
  58743. for (name in this._colors3) {
  58744. this._effect.setColor3(name, this._colors3[name]);
  58745. }
  58746. for (name in this._colors3Arrays) {
  58747. this._effect.setArray3(name, this._colors3Arrays[name]);
  58748. }
  58749. // Color4
  58750. for (name in this._colors4) {
  58751. var color = this._colors4[name];
  58752. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58753. }
  58754. // Vector2
  58755. for (name in this._vectors2) {
  58756. this._effect.setVector2(name, this._vectors2[name]);
  58757. }
  58758. // Vector3
  58759. for (name in this._vectors3) {
  58760. this._effect.setVector3(name, this._vectors3[name]);
  58761. }
  58762. // Vector4
  58763. for (name in this._vectors4) {
  58764. this._effect.setVector4(name, this._vectors4[name]);
  58765. }
  58766. // Matrix
  58767. for (name in this._matrices) {
  58768. this._effect.setMatrix(name, this._matrices[name]);
  58769. }
  58770. // Matrix 3x3
  58771. for (name in this._matrices3x3) {
  58772. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58773. }
  58774. // Matrix 2x2
  58775. for (name in this._matrices2x2) {
  58776. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58777. }
  58778. // Vector2Array
  58779. for (name in this._vectors2Arrays) {
  58780. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58781. }
  58782. // Vector3Array
  58783. for (name in this._vectors3Arrays) {
  58784. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58785. }
  58786. }
  58787. this._afterBind(mesh);
  58788. };
  58789. ShaderMaterial.prototype.getActiveTextures = function () {
  58790. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58791. for (var name in this._textures) {
  58792. activeTextures.push(this._textures[name]);
  58793. }
  58794. for (var name in this._textureArrays) {
  58795. var array = this._textureArrays[name];
  58796. for (var index = 0; index < array.length; index++) {
  58797. activeTextures.push(array[index]);
  58798. }
  58799. }
  58800. return activeTextures;
  58801. };
  58802. ShaderMaterial.prototype.hasTexture = function (texture) {
  58803. if (_super.prototype.hasTexture.call(this, texture)) {
  58804. return true;
  58805. }
  58806. for (var name in this._textures) {
  58807. if (this._textures[name] === texture) {
  58808. return true;
  58809. }
  58810. }
  58811. for (var name in this._textureArrays) {
  58812. var array = this._textureArrays[name];
  58813. for (var index = 0; index < array.length; index++) {
  58814. if (array[index] === texture) {
  58815. return true;
  58816. }
  58817. }
  58818. }
  58819. return false;
  58820. };
  58821. ShaderMaterial.prototype.clone = function (name) {
  58822. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58823. return newShaderMaterial;
  58824. };
  58825. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58826. if (forceDisposeTextures) {
  58827. var name;
  58828. for (name in this._textures) {
  58829. this._textures[name].dispose();
  58830. }
  58831. for (name in this._textureArrays) {
  58832. var array = this._textureArrays[name];
  58833. for (var index = 0; index < array.length; index++) {
  58834. array[index].dispose();
  58835. }
  58836. }
  58837. }
  58838. this._textures = {};
  58839. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58840. };
  58841. ShaderMaterial.prototype.serialize = function () {
  58842. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58843. serializationObject.customType = "BABYLON.ShaderMaterial";
  58844. serializationObject.options = this._options;
  58845. serializationObject.shaderPath = this._shaderPath;
  58846. var name;
  58847. // Texture
  58848. serializationObject.textures = {};
  58849. for (name in this._textures) {
  58850. serializationObject.textures[name] = this._textures[name].serialize();
  58851. }
  58852. // Texture arrays
  58853. serializationObject.textureArrays = {};
  58854. for (name in this._textureArrays) {
  58855. serializationObject.textureArrays[name] = [];
  58856. var array = this._textureArrays[name];
  58857. for (var index = 0; index < array.length; index++) {
  58858. serializationObject.textureArrays[name].push(array[index].serialize());
  58859. }
  58860. }
  58861. // Float
  58862. serializationObject.floats = {};
  58863. for (name in this._floats) {
  58864. serializationObject.floats[name] = this._floats[name];
  58865. }
  58866. // Float s
  58867. serializationObject.FloatArrays = {};
  58868. for (name in this._floatsArrays) {
  58869. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58870. }
  58871. // Color3
  58872. serializationObject.colors3 = {};
  58873. for (name in this._colors3) {
  58874. serializationObject.colors3[name] = this._colors3[name].asArray();
  58875. }
  58876. // Color3 array
  58877. serializationObject.colors3Arrays = {};
  58878. for (name in this._colors3Arrays) {
  58879. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58880. }
  58881. // Color4
  58882. serializationObject.colors4 = {};
  58883. for (name in this._colors4) {
  58884. serializationObject.colors4[name] = this._colors4[name].asArray();
  58885. }
  58886. // Vector2
  58887. serializationObject.vectors2 = {};
  58888. for (name in this._vectors2) {
  58889. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58890. }
  58891. // Vector3
  58892. serializationObject.vectors3 = {};
  58893. for (name in this._vectors3) {
  58894. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58895. }
  58896. // Vector4
  58897. serializationObject.vectors4 = {};
  58898. for (name in this._vectors4) {
  58899. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58900. }
  58901. // Matrix
  58902. serializationObject.matrices = {};
  58903. for (name in this._matrices) {
  58904. serializationObject.matrices[name] = this._matrices[name].asArray();
  58905. }
  58906. // Matrix 3x3
  58907. serializationObject.matrices3x3 = {};
  58908. for (name in this._matrices3x3) {
  58909. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58910. }
  58911. // Matrix 2x2
  58912. serializationObject.matrices2x2 = {};
  58913. for (name in this._matrices2x2) {
  58914. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58915. }
  58916. // Vector2Array
  58917. serializationObject.vectors2Arrays = {};
  58918. for (name in this._vectors2Arrays) {
  58919. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58920. }
  58921. // Vector3Array
  58922. serializationObject.vectors3Arrays = {};
  58923. for (name in this._vectors3Arrays) {
  58924. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58925. }
  58926. return serializationObject;
  58927. };
  58928. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58929. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58930. var name;
  58931. // Texture
  58932. for (name in source.textures) {
  58933. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58934. }
  58935. // Texture arrays
  58936. for (name in source.textureArrays) {
  58937. var array = source.textureArrays[name];
  58938. var textureArray = new Array();
  58939. for (var index = 0; index < array.length; index++) {
  58940. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58941. }
  58942. material.setTextureArray(name, textureArray);
  58943. }
  58944. // Float
  58945. for (name in source.floats) {
  58946. material.setFloat(name, source.floats[name]);
  58947. }
  58948. // Float s
  58949. for (name in source.floatsArrays) {
  58950. material.setFloats(name, source.floatsArrays[name]);
  58951. }
  58952. // Color3
  58953. for (name in source.colors3) {
  58954. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58955. }
  58956. // Color3 arrays
  58957. for (name in source.colors3Arrays) {
  58958. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58959. if (i % 3 === 0) {
  58960. arr.push([num]);
  58961. }
  58962. else {
  58963. arr[arr.length - 1].push(num);
  58964. }
  58965. return arr;
  58966. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58967. material.setColor3Array(name, colors);
  58968. }
  58969. // Color4
  58970. for (name in source.colors4) {
  58971. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58972. }
  58973. // Vector2
  58974. for (name in source.vectors2) {
  58975. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58976. }
  58977. // Vector3
  58978. for (name in source.vectors3) {
  58979. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58980. }
  58981. // Vector4
  58982. for (name in source.vectors4) {
  58983. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58984. }
  58985. // Matrix
  58986. for (name in source.matrices) {
  58987. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58988. }
  58989. // Matrix 3x3
  58990. for (name in source.matrices3x3) {
  58991. material.setMatrix3x3(name, source.matrices3x3[name]);
  58992. }
  58993. // Matrix 2x2
  58994. for (name in source.matrices2x2) {
  58995. material.setMatrix2x2(name, source.matrices2x2[name]);
  58996. }
  58997. // Vector2Array
  58998. for (name in source.vectors2Arrays) {
  58999. material.setArray2(name, source.vectors2Arrays[name]);
  59000. }
  59001. // Vector3Array
  59002. for (name in source.vectors3Arrays) {
  59003. material.setArray3(name, source.vectors3Arrays[name]);
  59004. }
  59005. return material;
  59006. };
  59007. return ShaderMaterial;
  59008. }(BABYLON.Material));
  59009. BABYLON.ShaderMaterial = ShaderMaterial;
  59010. })(BABYLON || (BABYLON = {}));
  59011. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59012. var BABYLON;
  59013. (function (BABYLON) {
  59014. var GroundMesh = /** @class */ (function (_super) {
  59015. __extends(GroundMesh, _super);
  59016. function GroundMesh(name, scene) {
  59017. var _this = _super.call(this, name, scene) || this;
  59018. _this.generateOctree = false;
  59019. return _this;
  59020. }
  59021. GroundMesh.prototype.getClassName = function () {
  59022. return "GroundMesh";
  59023. };
  59024. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59025. get: function () {
  59026. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59027. },
  59028. enumerable: true,
  59029. configurable: true
  59030. });
  59031. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59032. get: function () {
  59033. return this._subdivisionsX;
  59034. },
  59035. enumerable: true,
  59036. configurable: true
  59037. });
  59038. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59039. get: function () {
  59040. return this._subdivisionsY;
  59041. },
  59042. enumerable: true,
  59043. configurable: true
  59044. });
  59045. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59046. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59047. this._subdivisionsX = chunksCount;
  59048. this._subdivisionsY = chunksCount;
  59049. this.subdivide(chunksCount);
  59050. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59051. };
  59052. /**
  59053. * Returns a height (y) value in the Worl system :
  59054. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59055. * Returns the ground y position if (x, z) are outside the ground surface.
  59056. */
  59057. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59058. var world = this.getWorldMatrix();
  59059. var invMat = BABYLON.Tmp.Matrix[5];
  59060. world.invertToRef(invMat);
  59061. var tmpVect = BABYLON.Tmp.Vector3[8];
  59062. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59063. x = tmpVect.x;
  59064. z = tmpVect.z;
  59065. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59066. return this.position.y;
  59067. }
  59068. if (!this._heightQuads || this._heightQuads.length == 0) {
  59069. this._initHeightQuads();
  59070. this._computeHeightQuads();
  59071. }
  59072. var facet = this._getFacetAt(x, z);
  59073. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59074. // return y in the World system
  59075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59076. return tmpVect.y;
  59077. };
  59078. /**
  59079. * Returns a normalized vector (Vector3) orthogonal to the ground
  59080. * at the ground coordinates (x, z) expressed in the World system.
  59081. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59082. */
  59083. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59084. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59085. this.getNormalAtCoordinatesToRef(x, z, normal);
  59086. return normal;
  59087. };
  59088. /**
  59089. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59090. * at the ground coordinates (x, z) expressed in the World system.
  59091. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59092. * Returns the GroundMesh.
  59093. */
  59094. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59095. var world = this.getWorldMatrix();
  59096. var tmpMat = BABYLON.Tmp.Matrix[5];
  59097. world.invertToRef(tmpMat);
  59098. var tmpVect = BABYLON.Tmp.Vector3[8];
  59099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59100. x = tmpVect.x;
  59101. z = tmpVect.z;
  59102. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59103. return this;
  59104. }
  59105. if (!this._heightQuads || this._heightQuads.length == 0) {
  59106. this._initHeightQuads();
  59107. this._computeHeightQuads();
  59108. }
  59109. var facet = this._getFacetAt(x, z);
  59110. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59111. return this;
  59112. };
  59113. /**
  59114. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59115. * if the ground has been updated.
  59116. * This can be used in the render loop.
  59117. * Returns the GroundMesh.
  59118. */
  59119. GroundMesh.prototype.updateCoordinateHeights = function () {
  59120. if (!this._heightQuads || this._heightQuads.length == 0) {
  59121. this._initHeightQuads();
  59122. }
  59123. this._computeHeightQuads();
  59124. return this;
  59125. };
  59126. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59127. GroundMesh.prototype._getFacetAt = function (x, z) {
  59128. // retrieve col and row from x, z coordinates in the ground local system
  59129. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59130. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59131. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59132. var facet;
  59133. if (z < quad.slope.x * x + quad.slope.y) {
  59134. facet = quad.facet1;
  59135. }
  59136. else {
  59137. facet = quad.facet2;
  59138. }
  59139. return facet;
  59140. };
  59141. // Creates and populates the heightMap array with "facet" elements :
  59142. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59143. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59144. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59145. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59146. // Returns the GroundMesh.
  59147. GroundMesh.prototype._initHeightQuads = function () {
  59148. var subdivisionsX = this._subdivisionsX;
  59149. var subdivisionsY = this._subdivisionsY;
  59150. this._heightQuads = new Array();
  59151. for (var row = 0; row < subdivisionsY; row++) {
  59152. for (var col = 0; col < subdivisionsX; col++) {
  59153. 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) };
  59154. this._heightQuads[row * subdivisionsX + col] = quad;
  59155. }
  59156. }
  59157. return this;
  59158. };
  59159. // Compute each quad element values and update the the heightMap array :
  59160. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59161. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59162. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59163. // Returns the GroundMesh.
  59164. GroundMesh.prototype._computeHeightQuads = function () {
  59165. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59166. if (!positions) {
  59167. return this;
  59168. }
  59169. var v1 = BABYLON.Tmp.Vector3[3];
  59170. var v2 = BABYLON.Tmp.Vector3[2];
  59171. var v3 = BABYLON.Tmp.Vector3[1];
  59172. var v4 = BABYLON.Tmp.Vector3[0];
  59173. var v1v2 = BABYLON.Tmp.Vector3[4];
  59174. var v1v3 = BABYLON.Tmp.Vector3[5];
  59175. var v1v4 = BABYLON.Tmp.Vector3[6];
  59176. var norm1 = BABYLON.Tmp.Vector3[7];
  59177. var norm2 = BABYLON.Tmp.Vector3[8];
  59178. var i = 0;
  59179. var j = 0;
  59180. var k = 0;
  59181. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59182. var h = 0;
  59183. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59184. var d2 = 0;
  59185. var subdivisionsX = this._subdivisionsX;
  59186. var subdivisionsY = this._subdivisionsY;
  59187. for (var row = 0; row < subdivisionsY; row++) {
  59188. for (var col = 0; col < subdivisionsX; col++) {
  59189. i = col * 3;
  59190. j = row * (subdivisionsX + 1) * 3;
  59191. k = (row + 1) * (subdivisionsX + 1) * 3;
  59192. v1.x = positions[j + i];
  59193. v1.y = positions[j + i + 1];
  59194. v1.z = positions[j + i + 2];
  59195. v2.x = positions[j + i + 3];
  59196. v2.y = positions[j + i + 4];
  59197. v2.z = positions[j + i + 5];
  59198. v3.x = positions[k + i];
  59199. v3.y = positions[k + i + 1];
  59200. v3.z = positions[k + i + 2];
  59201. v4.x = positions[k + i + 3];
  59202. v4.y = positions[k + i + 4];
  59203. v4.z = positions[k + i + 5];
  59204. // 2D slope V1V4
  59205. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59206. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59207. // facet equations :
  59208. // we compute each facet normal vector
  59209. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59210. // we compute the value d by applying the equation to v1 which belongs to the plane
  59211. // then we store the facet equation in a Vector4
  59212. v2.subtractToRef(v1, v1v2);
  59213. v3.subtractToRef(v1, v1v3);
  59214. v4.subtractToRef(v1, v1v4);
  59215. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59216. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59217. norm1.normalize();
  59218. norm2.normalize();
  59219. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59220. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59221. var quad = this._heightQuads[row * subdivisionsX + col];
  59222. quad.slope.copyFromFloats(cd, h);
  59223. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59224. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59225. }
  59226. }
  59227. return this;
  59228. };
  59229. GroundMesh.prototype.serialize = function (serializationObject) {
  59230. _super.prototype.serialize.call(this, serializationObject);
  59231. serializationObject.subdivisionsX = this._subdivisionsX;
  59232. serializationObject.subdivisionsY = this._subdivisionsY;
  59233. serializationObject.minX = this._minX;
  59234. serializationObject.maxX = this._maxX;
  59235. serializationObject.minZ = this._minZ;
  59236. serializationObject.maxZ = this._maxZ;
  59237. serializationObject.width = this._width;
  59238. serializationObject.height = this._height;
  59239. };
  59240. GroundMesh.Parse = function (parsedMesh, scene) {
  59241. var result = new GroundMesh(parsedMesh.name, scene);
  59242. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59243. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59244. result._minX = parsedMesh.minX;
  59245. result._maxX = parsedMesh.maxX;
  59246. result._minZ = parsedMesh.minZ;
  59247. result._maxZ = parsedMesh.maxZ;
  59248. result._width = parsedMesh.width;
  59249. result._height = parsedMesh.height;
  59250. return result;
  59251. };
  59252. return GroundMesh;
  59253. }(BABYLON.Mesh));
  59254. BABYLON.GroundMesh = GroundMesh;
  59255. })(BABYLON || (BABYLON = {}));
  59256. //# sourceMappingURL=babylon.groundMesh.js.map
  59257. var BABYLON;
  59258. (function (BABYLON) {
  59259. /**
  59260. * Creates an instance based on a source mesh.
  59261. */
  59262. var InstancedMesh = /** @class */ (function (_super) {
  59263. __extends(InstancedMesh, _super);
  59264. function InstancedMesh(name, source) {
  59265. var _this = _super.call(this, name, source.getScene()) || this;
  59266. source.instances.push(_this);
  59267. _this._sourceMesh = source;
  59268. _this.position.copyFrom(source.position);
  59269. _this.rotation.copyFrom(source.rotation);
  59270. _this.scaling.copyFrom(source.scaling);
  59271. if (source.rotationQuaternion) {
  59272. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59273. }
  59274. _this.infiniteDistance = source.infiniteDistance;
  59275. _this.setPivotMatrix(source.getPivotMatrix());
  59276. _this.refreshBoundingInfo();
  59277. _this._syncSubMeshes();
  59278. return _this;
  59279. }
  59280. /**
  59281. * Returns the string "InstancedMesh".
  59282. */
  59283. InstancedMesh.prototype.getClassName = function () {
  59284. return "InstancedMesh";
  59285. };
  59286. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59287. // Methods
  59288. get: function () {
  59289. return this._sourceMesh.receiveShadows;
  59290. },
  59291. enumerable: true,
  59292. configurable: true
  59293. });
  59294. Object.defineProperty(InstancedMesh.prototype, "material", {
  59295. get: function () {
  59296. return this._sourceMesh.material;
  59297. },
  59298. enumerable: true,
  59299. configurable: true
  59300. });
  59301. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59302. get: function () {
  59303. return this._sourceMesh.visibility;
  59304. },
  59305. enumerable: true,
  59306. configurable: true
  59307. });
  59308. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59309. get: function () {
  59310. return this._sourceMesh.skeleton;
  59311. },
  59312. enumerable: true,
  59313. configurable: true
  59314. });
  59315. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59316. get: function () {
  59317. return this._sourceMesh.renderingGroupId;
  59318. },
  59319. set: function (value) {
  59320. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59321. return;
  59322. }
  59323. //no-op with warning
  59324. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59325. },
  59326. enumerable: true,
  59327. configurable: true
  59328. });
  59329. /**
  59330. * Returns the total number of vertices (integer).
  59331. */
  59332. InstancedMesh.prototype.getTotalVertices = function () {
  59333. return this._sourceMesh.getTotalVertices();
  59334. };
  59335. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59336. get: function () {
  59337. return this._sourceMesh;
  59338. },
  59339. enumerable: true,
  59340. configurable: true
  59341. });
  59342. /**
  59343. * Is this node ready to be used/rendered
  59344. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59345. * @return {boolean} is it ready
  59346. */
  59347. InstancedMesh.prototype.isReady = function (completeCheck) {
  59348. if (completeCheck === void 0) { completeCheck = false; }
  59349. return this._sourceMesh.isReady(completeCheck, true);
  59350. };
  59351. /**
  59352. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59353. */
  59354. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59355. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59356. };
  59357. /**
  59358. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59359. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59360. * The `data` are either a numeric array either a Float32Array.
  59361. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59362. * 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).
  59363. * Note that a new underlying VertexBuffer object is created each call.
  59364. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59365. *
  59366. * Possible `kind` values :
  59367. * - BABYLON.VertexBuffer.PositionKind
  59368. * - BABYLON.VertexBuffer.UVKind
  59369. * - BABYLON.VertexBuffer.UV2Kind
  59370. * - BABYLON.VertexBuffer.UV3Kind
  59371. * - BABYLON.VertexBuffer.UV4Kind
  59372. * - BABYLON.VertexBuffer.UV5Kind
  59373. * - BABYLON.VertexBuffer.UV6Kind
  59374. * - BABYLON.VertexBuffer.ColorKind
  59375. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59376. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59377. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59378. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59379. *
  59380. * Returns the Mesh.
  59381. */
  59382. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59383. if (this.sourceMesh) {
  59384. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59385. }
  59386. return this.sourceMesh;
  59387. };
  59388. /**
  59389. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59390. * If the mesh has no geometry, it is simply returned as it is.
  59391. * The `data` are either a numeric array either a Float32Array.
  59392. * No new underlying VertexBuffer object is created.
  59393. * 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.
  59394. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59395. *
  59396. * Possible `kind` values :
  59397. * - BABYLON.VertexBuffer.PositionKind
  59398. * - BABYLON.VertexBuffer.UVKind
  59399. * - BABYLON.VertexBuffer.UV2Kind
  59400. * - BABYLON.VertexBuffer.UV3Kind
  59401. * - BABYLON.VertexBuffer.UV4Kind
  59402. * - BABYLON.VertexBuffer.UV5Kind
  59403. * - BABYLON.VertexBuffer.UV6Kind
  59404. * - BABYLON.VertexBuffer.ColorKind
  59405. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59406. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59407. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59408. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59409. *
  59410. * Returns the Mesh.
  59411. */
  59412. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59413. if (this.sourceMesh) {
  59414. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59415. }
  59416. return this.sourceMesh;
  59417. };
  59418. /**
  59419. * Sets the mesh indices.
  59420. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59421. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59422. * This method creates a new index buffer each call.
  59423. * Returns the Mesh.
  59424. */
  59425. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59426. if (totalVertices === void 0) { totalVertices = null; }
  59427. if (this.sourceMesh) {
  59428. this.sourceMesh.setIndices(indices, totalVertices);
  59429. }
  59430. return this.sourceMesh;
  59431. };
  59432. /**
  59433. * Boolean : True if the mesh owns the requested kind of data.
  59434. */
  59435. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59436. return this._sourceMesh.isVerticesDataPresent(kind);
  59437. };
  59438. /**
  59439. * Returns an array of indices (IndicesArray).
  59440. */
  59441. InstancedMesh.prototype.getIndices = function () {
  59442. return this._sourceMesh.getIndices();
  59443. };
  59444. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59445. get: function () {
  59446. return this._sourceMesh._positions;
  59447. },
  59448. enumerable: true,
  59449. configurable: true
  59450. });
  59451. /**
  59452. * Sets a new updated BoundingInfo to the mesh.
  59453. * Returns the mesh.
  59454. */
  59455. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59456. var meshBB = this._sourceMesh.getBoundingInfo();
  59457. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59458. this._updateBoundingInfo();
  59459. return this;
  59460. };
  59461. InstancedMesh.prototype._preActivate = function () {
  59462. if (this._currentLOD) {
  59463. this._currentLOD._preActivate();
  59464. }
  59465. return this;
  59466. };
  59467. InstancedMesh.prototype._activate = function (renderId) {
  59468. if (this._currentLOD) {
  59469. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59470. }
  59471. return this;
  59472. };
  59473. /**
  59474. * Returns the current associated LOD AbstractMesh.
  59475. */
  59476. InstancedMesh.prototype.getLOD = function (camera) {
  59477. if (!camera) {
  59478. return this;
  59479. }
  59480. var boundingInfo = this.getBoundingInfo();
  59481. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59482. if (this._currentLOD === this.sourceMesh) {
  59483. return this;
  59484. }
  59485. return this._currentLOD;
  59486. };
  59487. InstancedMesh.prototype._syncSubMeshes = function () {
  59488. this.releaseSubMeshes();
  59489. if (this._sourceMesh.subMeshes) {
  59490. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59491. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59492. }
  59493. }
  59494. return this;
  59495. };
  59496. InstancedMesh.prototype._generatePointsArray = function () {
  59497. return this._sourceMesh._generatePointsArray();
  59498. };
  59499. /**
  59500. * Creates a new InstancedMesh from the current mesh.
  59501. * - name (string) : the cloned mesh name
  59502. * - newParent (optional Node) : the optional Node to parent the clone to.
  59503. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59504. *
  59505. * Returns the clone.
  59506. */
  59507. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59508. var result = this._sourceMesh.createInstance(name);
  59509. // Deep copy
  59510. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59511. // Bounding info
  59512. this.refreshBoundingInfo();
  59513. // Parent
  59514. if (newParent) {
  59515. result.parent = newParent;
  59516. }
  59517. if (!doNotCloneChildren) {
  59518. // Children
  59519. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59520. var mesh = this.getScene().meshes[index];
  59521. if (mesh.parent === this) {
  59522. mesh.clone(mesh.name, result);
  59523. }
  59524. }
  59525. }
  59526. result.computeWorldMatrix(true);
  59527. return result;
  59528. };
  59529. /**
  59530. * Disposes the InstancedMesh.
  59531. * Returns nothing.
  59532. */
  59533. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59534. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59535. // Remove from mesh
  59536. var index = this._sourceMesh.instances.indexOf(this);
  59537. this._sourceMesh.instances.splice(index, 1);
  59538. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59539. };
  59540. return InstancedMesh;
  59541. }(BABYLON.AbstractMesh));
  59542. BABYLON.InstancedMesh = InstancedMesh;
  59543. })(BABYLON || (BABYLON = {}));
  59544. //# sourceMappingURL=babylon.instancedMesh.js.map
  59545. var BABYLON;
  59546. (function (BABYLON) {
  59547. var LinesMesh = /** @class */ (function (_super) {
  59548. __extends(LinesMesh, _super);
  59549. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59550. if (scene === void 0) { scene = null; }
  59551. if (parent === void 0) { parent = null; }
  59552. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59553. _this.useVertexColor = useVertexColor;
  59554. _this.useVertexAlpha = useVertexAlpha;
  59555. _this.color = new BABYLON.Color3(1, 1, 1);
  59556. _this.alpha = 1;
  59557. if (source) {
  59558. _this.color = source.color.clone();
  59559. _this.alpha = source.alpha;
  59560. _this.useVertexColor = source.useVertexColor;
  59561. _this.useVertexAlpha = source.useVertexAlpha;
  59562. }
  59563. _this._intersectionThreshold = 0.1;
  59564. var defines = [];
  59565. var options = {
  59566. attributes: [BABYLON.VertexBuffer.PositionKind],
  59567. uniforms: ["world", "viewProjection"],
  59568. needAlphaBlending: true,
  59569. defines: defines
  59570. };
  59571. if (useVertexAlpha === false) {
  59572. options.needAlphaBlending = false;
  59573. }
  59574. if (!useVertexColor) {
  59575. options.uniforms.push("color");
  59576. }
  59577. else {
  59578. options.defines.push("#define VERTEXCOLOR");
  59579. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59580. }
  59581. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59582. return _this;
  59583. }
  59584. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59585. /**
  59586. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59587. * This margin is expressed in world space coordinates, so its value may vary.
  59588. * Default value is 0.1
  59589. * @returns the intersection Threshold value.
  59590. */
  59591. get: function () {
  59592. return this._intersectionThreshold;
  59593. },
  59594. /**
  59595. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59596. * This margin is expressed in world space coordinates, so its value may vary.
  59597. * @param value the new threshold to apply
  59598. */
  59599. set: function (value) {
  59600. if (this._intersectionThreshold === value) {
  59601. return;
  59602. }
  59603. this._intersectionThreshold = value;
  59604. if (this.geometry) {
  59605. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59606. }
  59607. },
  59608. enumerable: true,
  59609. configurable: true
  59610. });
  59611. /**
  59612. * Returns the string "LineMesh"
  59613. */
  59614. LinesMesh.prototype.getClassName = function () {
  59615. return "LinesMesh";
  59616. };
  59617. Object.defineProperty(LinesMesh.prototype, "material", {
  59618. get: function () {
  59619. return this._colorShader;
  59620. },
  59621. set: function (value) {
  59622. // Do nothing
  59623. },
  59624. enumerable: true,
  59625. configurable: true
  59626. });
  59627. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59628. get: function () {
  59629. return false;
  59630. },
  59631. enumerable: true,
  59632. configurable: true
  59633. });
  59634. LinesMesh.prototype.createInstance = function (name) {
  59635. throw new Error("LinesMeshes do not support createInstance.");
  59636. };
  59637. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59638. if (!this._geometry) {
  59639. return this;
  59640. }
  59641. // VBOs
  59642. this._geometry._bind(this._colorShader.getEffect());
  59643. // Color
  59644. if (!this.useVertexColor) {
  59645. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59646. }
  59647. return this;
  59648. };
  59649. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59650. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59651. return this;
  59652. }
  59653. var engine = this.getScene().getEngine();
  59654. // Draw order
  59655. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59656. return this;
  59657. };
  59658. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59659. this._colorShader.dispose();
  59660. _super.prototype.dispose.call(this, doNotRecurse);
  59661. };
  59662. /**
  59663. * Returns a new LineMesh object cloned from the current one.
  59664. */
  59665. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59666. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59667. };
  59668. return LinesMesh;
  59669. }(BABYLON.Mesh));
  59670. BABYLON.LinesMesh = LinesMesh;
  59671. })(BABYLON || (BABYLON = {}));
  59672. //# sourceMappingURL=babylon.linesMesh.js.map
  59673. var BABYLON;
  59674. (function (BABYLON) {
  59675. /**
  59676. * Class containing static functions to help procedurally build meshes
  59677. */
  59678. var MeshBuilder = /** @class */ (function () {
  59679. function MeshBuilder() {
  59680. }
  59681. MeshBuilder.updateSideOrientation = function (orientation) {
  59682. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59683. return BABYLON.Mesh.DOUBLESIDE;
  59684. }
  59685. if (orientation === undefined || orientation === null) {
  59686. return BABYLON.Mesh.FRONTSIDE;
  59687. }
  59688. return orientation;
  59689. };
  59690. /**
  59691. * Creates a box mesh
  59692. * * The parameter `size` sets the size (float) of each box side (default 1)
  59693. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59694. * * 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)
  59695. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59696. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59697. * * 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
  59698. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59699. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59700. * @param name defines the name of the mesh
  59701. * @param options defines the options used to create the mesh
  59702. * @param scene defines the hosting scene
  59703. * @returns the box mesh
  59704. */
  59705. MeshBuilder.CreateBox = function (name, options, scene) {
  59706. if (scene === void 0) { scene = null; }
  59707. var box = new BABYLON.Mesh(name, scene);
  59708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59709. box._originalBuilderSideOrientation = options.sideOrientation;
  59710. var vertexData = BABYLON.VertexData.CreateBox(options);
  59711. vertexData.applyToMesh(box, options.updatable);
  59712. return box;
  59713. };
  59714. /**
  59715. * Creates a sphere mesh
  59716. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59717. * * 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`)
  59718. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59719. * * 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
  59720. * * 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)
  59721. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59722. * * 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
  59723. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59724. * @param name defines the name of the mesh
  59725. * @param options defines the options used to create the mesh
  59726. * @param scene defines the hosting scene
  59727. * @returns the sphere mesh
  59728. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59729. */
  59730. MeshBuilder.CreateSphere = function (name, options, scene) {
  59731. var sphere = new BABYLON.Mesh(name, scene);
  59732. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59733. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59734. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59735. vertexData.applyToMesh(sphere, options.updatable);
  59736. return sphere;
  59737. };
  59738. /**
  59739. * Creates a plane polygonal mesh. By default, this is a disc
  59740. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59741. * * 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
  59742. * * 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
  59743. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59744. * * 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
  59745. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59746. * @param name defines the name of the mesh
  59747. * @param options defines the options used to create the mesh
  59748. * @param scene defines the hosting scene
  59749. * @returns the plane polygonal mesh
  59750. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  59751. */
  59752. MeshBuilder.CreateDisc = function (name, options, scene) {
  59753. if (scene === void 0) { scene = null; }
  59754. var disc = new BABYLON.Mesh(name, scene);
  59755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59756. disc._originalBuilderSideOrientation = options.sideOrientation;
  59757. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59758. vertexData.applyToMesh(disc, options.updatable);
  59759. return disc;
  59760. };
  59761. /**
  59762. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59763. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59764. * * 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`)
  59765. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59766. * * 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
  59767. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59768. * * 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
  59769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59770. * @param name defines the name of the mesh
  59771. * @param options defines the options used to create the mesh
  59772. * @param scene defines the hosting scene
  59773. * @returns the icosahedron mesh
  59774. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  59775. */
  59776. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59777. var sphere = new BABYLON.Mesh(name, scene);
  59778. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59779. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59780. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59781. vertexData.applyToMesh(sphere, options.updatable);
  59782. return sphere;
  59783. };
  59784. ;
  59785. /**
  59786. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59787. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59788. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59789. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59790. * * 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
  59791. * * 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
  59792. * * 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
  59793. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59794. * * 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
  59795. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59796. * * 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
  59797. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59798. * * 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
  59799. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59801. * @param name defines the name of the mesh
  59802. * @param options defines the options used to create the mesh
  59803. * @param scene defines the hosting scene
  59804. * @returns the ribbon mesh
  59805. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59806. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59807. */
  59808. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59809. if (scene === void 0) { scene = null; }
  59810. var pathArray = options.pathArray;
  59811. var closeArray = options.closeArray;
  59812. var closePath = options.closePath;
  59813. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59814. var instance = options.instance;
  59815. var updatable = options.updatable;
  59816. if (instance) { // existing ribbon instance update
  59817. // positionFunction : ribbon case
  59818. // only pathArray and sideOrientation parameters are taken into account for positions update
  59819. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59820. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59821. var positionFunction = function (positions) {
  59822. var minlg = pathArray[0].length;
  59823. var i = 0;
  59824. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59825. for (var si = 1; si <= ns; si++) {
  59826. for (var p = 0; p < pathArray.length; p++) {
  59827. var path = pathArray[p];
  59828. var l = path.length;
  59829. minlg = (minlg < l) ? minlg : l;
  59830. var j = 0;
  59831. while (j < minlg) {
  59832. positions[i] = path[j].x;
  59833. positions[i + 1] = path[j].y;
  59834. positions[i + 2] = path[j].z;
  59835. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59836. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59837. }
  59838. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59839. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59840. }
  59841. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59842. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59843. }
  59844. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59845. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59846. }
  59847. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59848. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59849. }
  59850. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59851. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59852. }
  59853. j++;
  59854. i += 3;
  59855. }
  59856. if (instance._closePath) {
  59857. positions[i] = path[0].x;
  59858. positions[i + 1] = path[0].y;
  59859. positions[i + 2] = path[0].z;
  59860. i += 3;
  59861. }
  59862. }
  59863. }
  59864. };
  59865. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59866. positionFunction(positions);
  59867. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59868. instance._boundingInfo.update(instance._worldMatrix);
  59869. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59870. if (options.colors) {
  59871. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59872. for (var c = 0; c < options.colors.length; c++) {
  59873. colors[c * 4] = options.colors[c].r;
  59874. colors[c * 4 + 1] = options.colors[c].g;
  59875. colors[c * 4 + 2] = options.colors[c].b;
  59876. colors[c * 4 + 3] = options.colors[c].a;
  59877. }
  59878. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59879. }
  59880. if (options.uvs) {
  59881. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59882. for (var i = 0; i < options.uvs.length; i++) {
  59883. uvs[i * 2] = options.uvs[i].x;
  59884. uvs[i * 2 + 1] = options.uvs[i].y;
  59885. }
  59886. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59887. }
  59888. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59889. var indices = instance.getIndices();
  59890. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59891. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59892. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59893. if (instance._closePath) {
  59894. var indexFirst = 0;
  59895. var indexLast = 0;
  59896. for (var p = 0; p < pathArray.length; p++) {
  59897. indexFirst = instance._idx[p] * 3;
  59898. if (p + 1 < pathArray.length) {
  59899. indexLast = (instance._idx[p + 1] - 1) * 3;
  59900. }
  59901. else {
  59902. indexLast = normals.length - 3;
  59903. }
  59904. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59905. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59906. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59907. normals[indexLast] = normals[indexFirst];
  59908. normals[indexLast + 1] = normals[indexFirst + 1];
  59909. normals[indexLast + 2] = normals[indexFirst + 2];
  59910. }
  59911. }
  59912. if (!(instance.areNormalsFrozen)) {
  59913. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59914. }
  59915. }
  59916. return instance;
  59917. }
  59918. else { // new ribbon creation
  59919. var ribbon = new BABYLON.Mesh(name, scene);
  59920. ribbon._originalBuilderSideOrientation = sideOrientation;
  59921. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59922. if (closePath) {
  59923. ribbon._idx = vertexData._idx;
  59924. }
  59925. ribbon._closePath = closePath;
  59926. ribbon._closeArray = closeArray;
  59927. vertexData.applyToMesh(ribbon, updatable);
  59928. return ribbon;
  59929. }
  59930. };
  59931. /**
  59932. * Creates a cylinder or a cone mesh
  59933. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59934. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59935. * * 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.
  59936. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59937. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59938. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59939. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59940. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59941. * * 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).
  59942. * * 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
  59943. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59944. * * 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
  59945. * * 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.
  59946. * * If `enclose` is false, a ring surface is one element.
  59947. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59948. * * 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
  59949. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59950. * * 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
  59951. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59952. * @param name defines the name of the mesh
  59953. * @param options defines the options used to create the mesh
  59954. * @param scene defines the hosting scene
  59955. * @returns the cylinder mesh
  59956. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59957. */
  59958. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59959. var cylinder = new BABYLON.Mesh(name, scene);
  59960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59961. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59962. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59963. vertexData.applyToMesh(cylinder, options.updatable);
  59964. return cylinder;
  59965. };
  59966. /**
  59967. * Creates a torus mesh
  59968. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59969. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59970. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59971. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59972. * * 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
  59973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59974. * @param name defines the name of the mesh
  59975. * @param options defines the options used to create the mesh
  59976. * @param scene defines the hosting scene
  59977. * @returns the torus mesh
  59978. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59979. */
  59980. MeshBuilder.CreateTorus = function (name, options, scene) {
  59981. var torus = new BABYLON.Mesh(name, scene);
  59982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59983. torus._originalBuilderSideOrientation = options.sideOrientation;
  59984. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59985. vertexData.applyToMesh(torus, options.updatable);
  59986. return torus;
  59987. };
  59988. /**
  59989. * Creates a torus knot mesh
  59990. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59991. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59992. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59993. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59994. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59995. * * 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
  59996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59997. * @param name defines the name of the mesh
  59998. * @param options defines the options used to create the mesh
  59999. * @param scene defines the hosting scene
  60000. * @returns the torus knot mesh
  60001. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60002. */
  60003. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60004. var torusKnot = new BABYLON.Mesh(name, scene);
  60005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60006. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60007. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60008. vertexData.applyToMesh(torusKnot, options.updatable);
  60009. return torusKnot;
  60010. };
  60011. /**
  60012. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60013. * * 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
  60014. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60015. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60016. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60017. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60018. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60019. * * 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
  60020. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60022. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60023. * @param name defines the name of the new line system
  60024. * @param options defines the options used to create the line system
  60025. * @param scene defines the hosting scene
  60026. * @returns a new line system mesh
  60027. */
  60028. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60029. var instance = options.instance;
  60030. var lines = options.lines;
  60031. var colors = options.colors;
  60032. if (instance) { // lines update
  60033. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60034. var vertexColor;
  60035. var lineColors;
  60036. if (colors) {
  60037. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60038. }
  60039. var i = 0;
  60040. var c = 0;
  60041. for (var l = 0; l < lines.length; l++) {
  60042. var points = lines[l];
  60043. for (var p = 0; p < points.length; p++) {
  60044. positions[i] = points[p].x;
  60045. positions[i + 1] = points[p].y;
  60046. positions[i + 2] = points[p].z;
  60047. if (colors && vertexColor) {
  60048. lineColors = colors[l];
  60049. vertexColor[c] = lineColors[p].r;
  60050. vertexColor[c + 1] = lineColors[p].g;
  60051. vertexColor[c + 2] = lineColors[p].b;
  60052. vertexColor[c + 3] = lineColors[p].a;
  60053. c += 4;
  60054. }
  60055. i += 3;
  60056. }
  60057. }
  60058. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60059. if (colors && vertexColor) {
  60060. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60061. }
  60062. return instance;
  60063. }
  60064. // line system creation
  60065. var useVertexColor = (colors) ? true : false;
  60066. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60067. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60068. vertexData.applyToMesh(lineSystem, options.updatable);
  60069. return lineSystem;
  60070. };
  60071. /**
  60072. * Creates a line mesh
  60073. * 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
  60074. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60075. * * The parameter `points` is an array successive Vector3
  60076. * * 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
  60077. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60078. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60079. * * When updating an instance, remember that only point positions can change, not the number of points
  60080. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60081. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60082. * @param name defines the name of the new line system
  60083. * @param options defines the options used to create the line system
  60084. * @param scene defines the hosting scene
  60085. * @returns a new line mesh
  60086. */
  60087. MeshBuilder.CreateLines = function (name, options, scene) {
  60088. if (scene === void 0) { scene = null; }
  60089. var colors = (options.colors) ? [options.colors] : null;
  60090. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60091. return lines;
  60092. };
  60093. /**
  60094. * Creates a dashed line mesh
  60095. * * 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
  60096. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60097. * * The parameter `points` is an array successive Vector3
  60098. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60099. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60100. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60101. * * 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
  60102. * * When updating an instance, remember that only point positions can change, not the number of points
  60103. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60104. * @param name defines the name of the mesh
  60105. * @param options defines the options used to create the mesh
  60106. * @param scene defines the hosting scene
  60107. * @returns the dashed line mesh
  60108. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60109. */
  60110. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60111. if (scene === void 0) { scene = null; }
  60112. var points = options.points;
  60113. var instance = options.instance;
  60114. var gapSize = options.gapSize || 1;
  60115. var dashSize = options.dashSize || 3;
  60116. if (instance) { // dashed lines update
  60117. var positionFunction = function (positions) {
  60118. var curvect = BABYLON.Vector3.Zero();
  60119. var nbSeg = positions.length / 6;
  60120. var lg = 0;
  60121. var nb = 0;
  60122. var shft = 0;
  60123. var dashshft = 0;
  60124. var curshft = 0;
  60125. var p = 0;
  60126. var i = 0;
  60127. var j = 0;
  60128. for (i = 0; i < points.length - 1; i++) {
  60129. points[i + 1].subtractToRef(points[i], curvect);
  60130. lg += curvect.length();
  60131. }
  60132. shft = lg / nbSeg;
  60133. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60134. for (i = 0; i < points.length - 1; i++) {
  60135. points[i + 1].subtractToRef(points[i], curvect);
  60136. nb = Math.floor(curvect.length() / shft);
  60137. curvect.normalize();
  60138. j = 0;
  60139. while (j < nb && p < positions.length) {
  60140. curshft = shft * j;
  60141. positions[p] = points[i].x + curshft * curvect.x;
  60142. positions[p + 1] = points[i].y + curshft * curvect.y;
  60143. positions[p + 2] = points[i].z + curshft * curvect.z;
  60144. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60145. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60146. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60147. p += 6;
  60148. j++;
  60149. }
  60150. }
  60151. while (p < positions.length) {
  60152. positions[p] = points[i].x;
  60153. positions[p + 1] = points[i].y;
  60154. positions[p + 2] = points[i].z;
  60155. p += 3;
  60156. }
  60157. };
  60158. instance.updateMeshPositions(positionFunction, false);
  60159. return instance;
  60160. }
  60161. // dashed lines creation
  60162. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60163. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60164. vertexData.applyToMesh(dashedLines, options.updatable);
  60165. dashedLines.dashSize = dashSize;
  60166. dashedLines.gapSize = gapSize;
  60167. return dashedLines;
  60168. };
  60169. /**
  60170. * 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.
  60171. * * 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.
  60172. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60173. * * 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.
  60174. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60175. * * 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
  60176. * * 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
  60177. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60179. * * 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
  60180. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60181. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60182. * @param name defines the name of the mesh
  60183. * @param options defines the options used to create the mesh
  60184. * @param scene defines the hosting scene
  60185. * @returns the extruded shape mesh
  60186. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60187. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60189. */
  60190. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60191. if (scene === void 0) { scene = null; }
  60192. var path = options.path;
  60193. var shape = options.shape;
  60194. var scale = options.scale || 1;
  60195. var rotation = options.rotation || 0;
  60196. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60197. var updatable = options.updatable;
  60198. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60199. var instance = options.instance || null;
  60200. var invertUV = options.invertUV || false;
  60201. 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);
  60202. };
  60203. /**
  60204. * Creates an custom extruded shape mesh.
  60205. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60206. * * 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.
  60207. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60208. * * 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
  60209. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60210. * * 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
  60211. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60212. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60213. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60214. * * 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
  60215. * * 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
  60216. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60217. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60218. * * 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
  60219. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60220. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60221. * @param name defines the name of the mesh
  60222. * @param options defines the options used to create the mesh
  60223. * @param scene defines the hosting scene
  60224. * @returns the custom extruded shape mesh
  60225. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60226. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60227. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60228. */
  60229. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60230. var path = options.path;
  60231. var shape = options.shape;
  60232. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60233. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60234. var ribbonCloseArray = options.ribbonCloseArray || false;
  60235. var ribbonClosePath = options.ribbonClosePath || false;
  60236. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60237. var updatable = options.updatable;
  60238. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60239. var instance = options.instance;
  60240. var invertUV = options.invertUV || false;
  60241. 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);
  60242. };
  60243. /**
  60244. * Creates lathe mesh.
  60245. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60246. * * 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
  60247. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60248. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60249. * * 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
  60250. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60251. * * 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
  60252. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60253. * * 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
  60254. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60256. * @param name defines the name of the mesh
  60257. * @param options defines the options used to create the mesh
  60258. * @param scene defines the hosting scene
  60259. * @returns the lathe mesh
  60260. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60261. */
  60262. MeshBuilder.CreateLathe = function (name, options, scene) {
  60263. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60264. var closed = (options.closed === undefined) ? true : options.closed;
  60265. var shape = options.shape;
  60266. var radius = options.radius || 1;
  60267. var tessellation = options.tessellation || 64;
  60268. var updatable = options.updatable;
  60269. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60270. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60271. var pi2 = Math.PI * 2;
  60272. var paths = new Array();
  60273. var invertUV = options.invertUV || false;
  60274. var i = 0;
  60275. var p = 0;
  60276. var step = pi2 / tessellation * arc;
  60277. var rotated;
  60278. var path = new Array();
  60279. for (i = 0; i <= tessellation; i++) {
  60280. var path = [];
  60281. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60282. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60283. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60284. }
  60285. for (p = 0; p < shape.length; p++) {
  60286. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60287. path.push(rotated);
  60288. }
  60289. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60290. 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));
  60291. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60292. }
  60293. paths.push(path);
  60294. }
  60295. // lathe ribbon
  60296. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60297. return lathe;
  60298. };
  60299. /**
  60300. * Creates a plane mesh
  60301. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60302. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60303. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60304. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60305. * * 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
  60306. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60307. * @param name defines the name of the mesh
  60308. * @param options defines the options used to create the mesh
  60309. * @param scene defines the hosting scene
  60310. * @returns the plane mesh
  60311. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60312. */
  60313. MeshBuilder.CreatePlane = function (name, options, scene) {
  60314. var plane = new BABYLON.Mesh(name, scene);
  60315. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60316. plane._originalBuilderSideOrientation = options.sideOrientation;
  60317. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60318. vertexData.applyToMesh(plane, options.updatable);
  60319. if (options.sourcePlane) {
  60320. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60321. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60322. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60323. plane.rotate(vectorProduct, product);
  60324. }
  60325. return plane;
  60326. };
  60327. /**
  60328. * Creates a ground mesh
  60329. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60330. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60332. * @param name defines the name of the mesh
  60333. * @param options defines the options used to create the mesh
  60334. * @param scene defines the hosting scene
  60335. * @returns the ground mesh
  60336. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60337. */
  60338. MeshBuilder.CreateGround = function (name, options, scene) {
  60339. var ground = new BABYLON.GroundMesh(name, scene);
  60340. ground._setReady(false);
  60341. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60342. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60343. ground._width = options.width || 1;
  60344. ground._height = options.height || 1;
  60345. ground._maxX = ground._width / 2;
  60346. ground._maxZ = ground._height / 2;
  60347. ground._minX = -ground._maxX;
  60348. ground._minZ = -ground._maxZ;
  60349. var vertexData = BABYLON.VertexData.CreateGround(options);
  60350. vertexData.applyToMesh(ground, options.updatable);
  60351. ground._setReady(true);
  60352. return ground;
  60353. };
  60354. /**
  60355. * Creates a tiled ground mesh
  60356. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60357. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60358. * * 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
  60359. * * 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
  60360. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60361. * @param name defines the name of the mesh
  60362. * @param options defines the options used to create the mesh
  60363. * @param scene defines the hosting scene
  60364. * @returns the tiled ground mesh
  60365. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60366. */
  60367. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60368. var tiledGround = new BABYLON.Mesh(name, scene);
  60369. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60370. vertexData.applyToMesh(tiledGround, options.updatable);
  60371. return tiledGround;
  60372. };
  60373. /**
  60374. * Creates a ground mesh from a height map
  60375. * * The parameter `url` sets the URL of the height map image resource.
  60376. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60377. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60378. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60379. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60380. * * 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.
  60381. * * 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).
  60382. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60383. * @param name defines the name of the mesh
  60384. * @param url defines the url to the height map
  60385. * @param options defines the options used to create the mesh
  60386. * @param scene defines the hosting scene
  60387. * @returns the ground mesh
  60388. * @see http://doc.babylonjs.com/babylon101/height_map
  60389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60390. */
  60391. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60392. var width = options.width || 10.0;
  60393. var height = options.height || 10.0;
  60394. var subdivisions = options.subdivisions || 1 | 0;
  60395. var minHeight = options.minHeight || 0.0;
  60396. var maxHeight = options.maxHeight || 1.0;
  60397. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60398. var updatable = options.updatable;
  60399. var onReady = options.onReady;
  60400. var ground = new BABYLON.GroundMesh(name, scene);
  60401. ground._subdivisionsX = subdivisions;
  60402. ground._subdivisionsY = subdivisions;
  60403. ground._width = width;
  60404. ground._height = height;
  60405. ground._maxX = ground._width / 2.0;
  60406. ground._maxZ = ground._height / 2.0;
  60407. ground._minX = -ground._maxX;
  60408. ground._minZ = -ground._maxZ;
  60409. ground._setReady(false);
  60410. var onload = function (img) {
  60411. // Getting height map data
  60412. var canvas = document.createElement("canvas");
  60413. var context = canvas.getContext("2d");
  60414. if (!context) {
  60415. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60416. }
  60417. if (scene.isDisposed) {
  60418. return;
  60419. }
  60420. var bufferWidth = img.width;
  60421. var bufferHeight = img.height;
  60422. canvas.width = bufferWidth;
  60423. canvas.height = bufferHeight;
  60424. context.drawImage(img, 0, 0);
  60425. // Create VertexData from map data
  60426. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60427. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60428. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60429. width: width, height: height,
  60430. subdivisions: subdivisions,
  60431. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60432. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60433. });
  60434. vertexData.applyToMesh(ground, updatable);
  60435. //execute ready callback, if set
  60436. if (onReady) {
  60437. onReady(ground);
  60438. }
  60439. ground._setReady(true);
  60440. };
  60441. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60442. return ground;
  60443. };
  60444. /**
  60445. * Creates a polygon mesh
  60446. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60447. * * 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
  60448. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60449. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60450. * * 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)
  60451. * * Remember you can only change the shape positions, not their number when updating a polygon
  60452. * @param name defines the name of the mesh
  60453. * @param options defines the options used to create the mesh
  60454. * @param scene defines the hosting scene
  60455. * @returns the polygon mesh
  60456. */
  60457. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60458. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60459. var shape = options.shape;
  60460. var holes = options.holes || [];
  60461. var depth = options.depth || 0;
  60462. var contours = [];
  60463. var hole = [];
  60464. for (var i = 0; i < shape.length; i++) {
  60465. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60466. }
  60467. var epsilon = 0.00000001;
  60468. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60469. contours.pop();
  60470. }
  60471. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60472. for (var hNb = 0; hNb < holes.length; hNb++) {
  60473. hole = [];
  60474. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60475. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60476. }
  60477. polygonTriangulation.addHole(hole);
  60478. }
  60479. var polygon = polygonTriangulation.build(options.updatable, depth);
  60480. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60481. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60482. vertexData.applyToMesh(polygon, options.updatable);
  60483. return polygon;
  60484. };
  60485. ;
  60486. /**
  60487. * Creates an extruded polygon mesh, with depth in the Y direction.
  60488. * * 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)
  60489. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60490. * @param name defines the name of the mesh
  60491. * @param options defines the options used to create the mesh
  60492. * @param scene defines the hosting scene
  60493. * @returns the polygon mesh
  60494. */
  60495. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60496. return MeshBuilder.CreatePolygon(name, options, scene);
  60497. };
  60498. ;
  60499. /**
  60500. * Creates a tube mesh.
  60501. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60502. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60503. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60504. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60505. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60506. * * 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)
  60507. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60508. * * 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
  60509. * * 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
  60510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60511. * * 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
  60512. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60513. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60514. * @param name defines the name of the mesh
  60515. * @param options defines the options used to create the mesh
  60516. * @param scene defines the hosting scene
  60517. * @returns the tube mesh
  60518. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60519. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60520. */
  60521. MeshBuilder.CreateTube = function (name, options, scene) {
  60522. var path = options.path;
  60523. var instance = options.instance;
  60524. var radius = 1.0;
  60525. if (instance) {
  60526. radius = instance.radius;
  60527. }
  60528. if (options.radius !== undefined) {
  60529. radius = options.radius;
  60530. }
  60531. ;
  60532. var tessellation = options.tessellation || 64 | 0;
  60533. var radiusFunction = options.radiusFunction || null;
  60534. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60535. var invertUV = options.invertUV || false;
  60536. var updatable = options.updatable;
  60537. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60538. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60539. // tube geometry
  60540. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60541. var tangents = path3D.getTangents();
  60542. var normals = path3D.getNormals();
  60543. var distances = path3D.getDistances();
  60544. var pi2 = Math.PI * 2;
  60545. var step = pi2 / tessellation * arc;
  60546. var returnRadius = function () { return radius; };
  60547. var radiusFunctionFinal = radiusFunction || returnRadius;
  60548. var circlePath;
  60549. var rad;
  60550. var normal;
  60551. var rotated;
  60552. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60553. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60554. for (var i = 0; i < path.length; i++) {
  60555. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60556. circlePath = Array(); // current circle array
  60557. normal = normals[i]; // current normal
  60558. for (var t = 0; t < tessellation; t++) {
  60559. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60560. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60561. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60562. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60563. circlePath[t] = rotated;
  60564. }
  60565. circlePaths[index] = circlePath;
  60566. index++;
  60567. }
  60568. // cap
  60569. var capPath = function (nbPoints, pathIndex) {
  60570. var pointCap = Array();
  60571. for (var i = 0; i < nbPoints; i++) {
  60572. pointCap.push(path[pathIndex]);
  60573. }
  60574. return pointCap;
  60575. };
  60576. switch (cap) {
  60577. case BABYLON.Mesh.NO_CAP:
  60578. break;
  60579. case BABYLON.Mesh.CAP_START:
  60580. circlePaths[0] = capPath(tessellation, 0);
  60581. circlePaths[1] = circlePaths[2].slice(0);
  60582. break;
  60583. case BABYLON.Mesh.CAP_END:
  60584. circlePaths[index] = circlePaths[index - 1].slice(0);
  60585. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60586. break;
  60587. case BABYLON.Mesh.CAP_ALL:
  60588. circlePaths[0] = capPath(tessellation, 0);
  60589. circlePaths[1] = circlePaths[2].slice(0);
  60590. circlePaths[index] = circlePaths[index - 1].slice(0);
  60591. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60592. break;
  60593. default:
  60594. break;
  60595. }
  60596. return circlePaths;
  60597. };
  60598. var path3D;
  60599. var pathArray;
  60600. if (instance) { // tube update
  60601. var arc = options.arc || instance.arc;
  60602. path3D = (instance.path3D).update(path);
  60603. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60604. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60605. instance.path3D = path3D;
  60606. instance.pathArray = pathArray;
  60607. instance.arc = arc;
  60608. instance.radius = radius;
  60609. return instance;
  60610. }
  60611. // tube creation
  60612. path3D = new BABYLON.Path3D(path);
  60613. var newPathArray = new Array();
  60614. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60615. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60616. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60617. tube.pathArray = pathArray;
  60618. tube.path3D = path3D;
  60619. tube.tessellation = tessellation;
  60620. tube.cap = cap;
  60621. tube.arc = options.arc;
  60622. tube.radius = radius;
  60623. return tube;
  60624. };
  60625. /**
  60626. * Creates a polyhedron mesh
  60627. * * 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
  60628. * * The parameter `size` (positive float, default 1) sets the polygon size
  60629. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60630. * * 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`
  60631. * * 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
  60632. * * 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)`)
  60633. * * 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
  60634. * * 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
  60635. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60636. * * 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
  60637. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60638. * @param name defines the name of the mesh
  60639. * @param options defines the options used to create the mesh
  60640. * @param scene defines the hosting scene
  60641. * @returns the polyhedron mesh
  60642. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  60643. */
  60644. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60645. var polyhedron = new BABYLON.Mesh(name, scene);
  60646. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60647. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60648. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60649. vertexData.applyToMesh(polyhedron, options.updatable);
  60650. return polyhedron;
  60651. };
  60652. /**
  60653. * Creates a decal mesh.
  60654. * 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
  60655. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60656. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60657. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60658. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60659. * @param name defines the name of the mesh
  60660. * @param sourceMesh defines the mesh where the decal must be applied
  60661. * @param options defines the options used to create the mesh
  60662. * @param scene defines the hosting scene
  60663. * @returns the decal mesh
  60664. * @see http://doc.babylonjs.com/how_to/decals
  60665. */
  60666. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60667. var indices = sourceMesh.getIndices();
  60668. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60669. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60670. var position = options.position || BABYLON.Vector3.Zero();
  60671. var normal = options.normal || BABYLON.Vector3.Up();
  60672. var size = options.size || BABYLON.Vector3.One();
  60673. var angle = options.angle || 0;
  60674. // Getting correct rotation
  60675. if (!normal) {
  60676. var target = new BABYLON.Vector3(0, 0, 1);
  60677. var camera = sourceMesh.getScene().activeCamera;
  60678. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60679. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60680. }
  60681. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60682. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60683. var pitch = Math.atan2(normal.y, len);
  60684. // Matrix
  60685. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60686. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60687. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60688. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60689. var vertexData = new BABYLON.VertexData();
  60690. vertexData.indices = [];
  60691. vertexData.positions = [];
  60692. vertexData.normals = [];
  60693. vertexData.uvs = [];
  60694. var currentVertexDataIndex = 0;
  60695. var extractDecalVector3 = function (indexId) {
  60696. var result = new BABYLON.PositionNormalVertex();
  60697. if (!indices || !positions || !normals) {
  60698. return result;
  60699. }
  60700. var vertexId = indices[indexId];
  60701. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60702. // Send vector to decal local world
  60703. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60704. // Get normal
  60705. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60706. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60707. return result;
  60708. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60709. var clip = function (vertices, axis) {
  60710. if (vertices.length === 0) {
  60711. return vertices;
  60712. }
  60713. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60714. var clipVertices = function (v0, v1) {
  60715. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60716. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60717. };
  60718. var result = new Array();
  60719. for (var index = 0; index < vertices.length; index += 3) {
  60720. var v1Out;
  60721. var v2Out;
  60722. var v3Out;
  60723. var total = 0;
  60724. var nV1 = null;
  60725. var nV2 = null;
  60726. var nV3 = null;
  60727. var nV4 = null;
  60728. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60729. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60730. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60731. v1Out = d1 > 0;
  60732. v2Out = d2 > 0;
  60733. v3Out = d3 > 0;
  60734. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60735. switch (total) {
  60736. case 0:
  60737. result.push(vertices[index]);
  60738. result.push(vertices[index + 1]);
  60739. result.push(vertices[index + 2]);
  60740. break;
  60741. case 1:
  60742. if (v1Out) {
  60743. nV1 = vertices[index + 1];
  60744. nV2 = vertices[index + 2];
  60745. nV3 = clipVertices(vertices[index], nV1);
  60746. nV4 = clipVertices(vertices[index], nV2);
  60747. }
  60748. if (v2Out) {
  60749. nV1 = vertices[index];
  60750. nV2 = vertices[index + 2];
  60751. nV3 = clipVertices(vertices[index + 1], nV1);
  60752. nV4 = clipVertices(vertices[index + 1], nV2);
  60753. result.push(nV3);
  60754. result.push(nV2.clone());
  60755. result.push(nV1.clone());
  60756. result.push(nV2.clone());
  60757. result.push(nV3.clone());
  60758. result.push(nV4);
  60759. break;
  60760. }
  60761. if (v3Out) {
  60762. nV1 = vertices[index];
  60763. nV2 = vertices[index + 1];
  60764. nV3 = clipVertices(vertices[index + 2], nV1);
  60765. nV4 = clipVertices(vertices[index + 2], nV2);
  60766. }
  60767. if (nV1 && nV2 && nV3 && nV4) {
  60768. result.push(nV1.clone());
  60769. result.push(nV2.clone());
  60770. result.push(nV3);
  60771. result.push(nV4);
  60772. result.push(nV3.clone());
  60773. result.push(nV2.clone());
  60774. }
  60775. break;
  60776. case 2:
  60777. if (!v1Out) {
  60778. nV1 = vertices[index].clone();
  60779. nV2 = clipVertices(nV1, vertices[index + 1]);
  60780. nV3 = clipVertices(nV1, vertices[index + 2]);
  60781. result.push(nV1);
  60782. result.push(nV2);
  60783. result.push(nV3);
  60784. }
  60785. if (!v2Out) {
  60786. nV1 = vertices[index + 1].clone();
  60787. nV2 = clipVertices(nV1, vertices[index + 2]);
  60788. nV3 = clipVertices(nV1, vertices[index]);
  60789. result.push(nV1);
  60790. result.push(nV2);
  60791. result.push(nV3);
  60792. }
  60793. if (!v3Out) {
  60794. nV1 = vertices[index + 2].clone();
  60795. nV2 = clipVertices(nV1, vertices[index]);
  60796. nV3 = clipVertices(nV1, vertices[index + 1]);
  60797. result.push(nV1);
  60798. result.push(nV2);
  60799. result.push(nV3);
  60800. }
  60801. break;
  60802. case 3:
  60803. break;
  60804. }
  60805. }
  60806. return result;
  60807. };
  60808. for (var index = 0; index < indices.length; index += 3) {
  60809. var faceVertices = new Array();
  60810. faceVertices.push(extractDecalVector3(index));
  60811. faceVertices.push(extractDecalVector3(index + 1));
  60812. faceVertices.push(extractDecalVector3(index + 2));
  60813. // Clip
  60814. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60815. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60816. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60817. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60818. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60820. if (faceVertices.length === 0) {
  60821. continue;
  60822. }
  60823. // Add UVs and get back to world
  60824. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60825. var vertex = faceVertices[vIndex];
  60826. //TODO check for Int32Array | Uint32Array | Uint16Array
  60827. vertexData.indices.push(currentVertexDataIndex);
  60828. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60829. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60830. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60831. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60832. currentVertexDataIndex++;
  60833. }
  60834. }
  60835. // Return mesh
  60836. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60837. vertexData.applyToMesh(decal);
  60838. decal.position = position.clone();
  60839. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60840. return decal;
  60841. };
  60842. // Privates
  60843. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60844. // extrusion geometry
  60845. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60846. var tangents = path3D.getTangents();
  60847. var normals = path3D.getNormals();
  60848. var binormals = path3D.getBinormals();
  60849. var distances = path3D.getDistances();
  60850. var angle = 0;
  60851. var returnScale = function () { return scale !== null ? scale : 1; };
  60852. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60853. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60854. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60855. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60856. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60857. for (var i = 0; i < curve.length; i++) {
  60858. var shapePath = new Array();
  60859. var angleStep = rotate(i, distances[i]);
  60860. var scaleRatio = scl(i, distances[i]);
  60861. for (var p = 0; p < shape.length; p++) {
  60862. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60863. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60864. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60865. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60866. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60867. shapePath[p] = rotated;
  60868. }
  60869. shapePaths[index] = shapePath;
  60870. angle += angleStep;
  60871. index++;
  60872. }
  60873. // cap
  60874. var capPath = function (shapePath) {
  60875. var pointCap = Array();
  60876. var barycenter = BABYLON.Vector3.Zero();
  60877. var i;
  60878. for (i = 0; i < shapePath.length; i++) {
  60879. barycenter.addInPlace(shapePath[i]);
  60880. }
  60881. barycenter.scaleInPlace(1.0 / shapePath.length);
  60882. for (i = 0; i < shapePath.length; i++) {
  60883. pointCap.push(barycenter);
  60884. }
  60885. return pointCap;
  60886. };
  60887. switch (cap) {
  60888. case BABYLON.Mesh.NO_CAP:
  60889. break;
  60890. case BABYLON.Mesh.CAP_START:
  60891. shapePaths[0] = capPath(shapePaths[2]);
  60892. shapePaths[1] = shapePaths[2];
  60893. break;
  60894. case BABYLON.Mesh.CAP_END:
  60895. shapePaths[index] = shapePaths[index - 1];
  60896. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60897. break;
  60898. case BABYLON.Mesh.CAP_ALL:
  60899. shapePaths[0] = capPath(shapePaths[2]);
  60900. shapePaths[1] = shapePaths[2];
  60901. shapePaths[index] = shapePaths[index - 1];
  60902. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60903. break;
  60904. default:
  60905. break;
  60906. }
  60907. return shapePaths;
  60908. };
  60909. var path3D;
  60910. var pathArray;
  60911. if (instance) { // instance update
  60912. path3D = (instance.path3D).update(curve);
  60913. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60914. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60915. return instance;
  60916. }
  60917. // extruded shape creation
  60918. path3D = new BABYLON.Path3D(curve);
  60919. var newShapePaths = new Array();
  60920. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60921. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60922. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60923. extrudedGeneric.pathArray = pathArray;
  60924. extrudedGeneric.path3D = path3D;
  60925. extrudedGeneric.cap = cap;
  60926. return extrudedGeneric;
  60927. };
  60928. return MeshBuilder;
  60929. }());
  60930. BABYLON.MeshBuilder = MeshBuilder;
  60931. })(BABYLON || (BABYLON = {}));
  60932. //# sourceMappingURL=babylon.meshBuilder.js.map
  60933. var BABYLON;
  60934. (function (BABYLON) {
  60935. /**
  60936. * Draco compression (https://google.github.io/draco/)
  60937. *
  60938. * This class wraps the Draco module.
  60939. *
  60940. * **Encoder**
  60941. *
  60942. * The encoder is not currently implemented.
  60943. *
  60944. * **Decoder**
  60945. *
  60946. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  60947. *
  60948. * To update the configuration, use the following code:
  60949. * ```javascript
  60950. * BABYLON.DracoCompression.Configuration = {
  60951. * decoder: {
  60952. * wasmUrl: "<url to the WebAssembly library>",
  60953. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  60954. * fallbackUrl: "<url to the fallback JavaScript library>",
  60955. * }
  60956. * };
  60957. * ```
  60958. *
  60959. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  60960. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  60961. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  60962. *
  60963. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  60964. * ```javascript
  60965. * var dracoCompression = new BABYLON.DracoCompression();
  60966. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  60967. * [BABYLON.VertexBuffer.PositionKind]: 0
  60968. * });
  60969. * ```
  60970. *
  60971. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  60972. */
  60973. var DracoCompression = /** @class */ (function () {
  60974. /**
  60975. * Constructor
  60976. */
  60977. function DracoCompression() {
  60978. }
  60979. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  60980. /**
  60981. * Returns true if the decoder is available.
  60982. */
  60983. get: function () {
  60984. if (typeof DracoDecoderModule !== "undefined") {
  60985. return true;
  60986. }
  60987. var decoder = DracoCompression.Configuration.decoder;
  60988. if (decoder) {
  60989. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  60990. return true;
  60991. }
  60992. if (decoder.fallbackUrl) {
  60993. return true;
  60994. }
  60995. }
  60996. return false;
  60997. },
  60998. enumerable: true,
  60999. configurable: true
  61000. });
  61001. /**
  61002. * Stop all async operations and release resources.
  61003. */
  61004. DracoCompression.prototype.dispose = function () {
  61005. };
  61006. /**
  61007. * Decode Draco compressed mesh data to vertex data.
  61008. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61009. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61010. * @returns A promise that resolves with the decoded vertex data
  61011. */
  61012. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61013. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61014. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61015. var module = wrappedModule.module;
  61016. var vertexData = new BABYLON.VertexData();
  61017. var buffer = new module.DecoderBuffer();
  61018. buffer.Init(dataView, dataView.byteLength);
  61019. var decoder = new module.Decoder();
  61020. var geometry;
  61021. var status;
  61022. try {
  61023. var type = decoder.GetEncodedGeometryType(buffer);
  61024. switch (type) {
  61025. case module.TRIANGULAR_MESH:
  61026. geometry = new module.Mesh();
  61027. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61028. break;
  61029. case module.POINT_CLOUD:
  61030. geometry = new module.PointCloud();
  61031. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61032. break;
  61033. default:
  61034. throw new Error("Invalid geometry type " + type);
  61035. }
  61036. if (!status.ok() || !geometry.ptr) {
  61037. throw new Error(status.error_msg());
  61038. }
  61039. var numPoints = geometry.num_points();
  61040. if (type === module.TRIANGULAR_MESH) {
  61041. var numFaces = geometry.num_faces();
  61042. var faceIndices = new module.DracoInt32Array();
  61043. try {
  61044. var indices = new Uint32Array(numFaces * 3);
  61045. for (var i = 0; i < numFaces; i++) {
  61046. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61047. var offset = i * 3;
  61048. indices[offset + 0] = faceIndices.GetValue(0);
  61049. indices[offset + 1] = faceIndices.GetValue(1);
  61050. indices[offset + 2] = faceIndices.GetValue(2);
  61051. }
  61052. vertexData.indices = indices;
  61053. }
  61054. finally {
  61055. module.destroy(faceIndices);
  61056. }
  61057. }
  61058. for (var kind in attributes) {
  61059. var uniqueId = attributes[kind];
  61060. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61061. var dracoData = new module.DracoFloat32Array();
  61062. try {
  61063. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61064. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61065. for (var i = 0; i < babylonData.length; i++) {
  61066. babylonData[i] = dracoData.GetValue(i);
  61067. }
  61068. vertexData.set(babylonData, kind);
  61069. }
  61070. finally {
  61071. module.destroy(dracoData);
  61072. }
  61073. }
  61074. }
  61075. finally {
  61076. if (geometry) {
  61077. module.destroy(geometry);
  61078. }
  61079. module.destroy(decoder);
  61080. module.destroy(buffer);
  61081. }
  61082. return vertexData;
  61083. });
  61084. };
  61085. DracoCompression._GetDecoderModule = function () {
  61086. if (!DracoCompression._DecoderModulePromise) {
  61087. var promise = null;
  61088. var config_1 = {};
  61089. if (typeof DracoDecoderModule !== "undefined") {
  61090. promise = Promise.resolve();
  61091. }
  61092. else {
  61093. var decoder = DracoCompression.Configuration.decoder;
  61094. if (decoder) {
  61095. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61096. promise = Promise.all([
  61097. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61098. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61099. config_1.wasmBinary = data;
  61100. })
  61101. ]);
  61102. }
  61103. else if (decoder.fallbackUrl) {
  61104. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61105. }
  61106. }
  61107. }
  61108. if (!promise) {
  61109. throw new Error("Draco decoder module is not available");
  61110. }
  61111. DracoCompression._DecoderModulePromise = promise.then(function () {
  61112. return new Promise(function (resolve) {
  61113. config_1.onModuleLoaded = function (decoderModule) {
  61114. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61115. resolve({ module: decoderModule });
  61116. };
  61117. DracoDecoderModule(config_1);
  61118. });
  61119. });
  61120. }
  61121. return DracoCompression._DecoderModulePromise;
  61122. };
  61123. DracoCompression._LoadScriptAsync = function (url) {
  61124. return new Promise(function (resolve, reject) {
  61125. BABYLON.Tools.LoadScript(url, function () {
  61126. resolve();
  61127. }, function (message) {
  61128. reject(new Error(message));
  61129. });
  61130. });
  61131. };
  61132. DracoCompression._LoadFileAsync = function (url) {
  61133. return new Promise(function (resolve, reject) {
  61134. BABYLON.Tools.LoadFile(url, function (data) {
  61135. resolve(data);
  61136. }, undefined, undefined, true, function (request, exception) {
  61137. reject(exception);
  61138. });
  61139. });
  61140. };
  61141. /**
  61142. * The configuration. Defaults to the following urls:
  61143. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61144. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61145. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61146. */
  61147. DracoCompression.Configuration = {
  61148. decoder: {
  61149. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61150. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61151. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61152. }
  61153. };
  61154. return DracoCompression;
  61155. }());
  61156. BABYLON.DracoCompression = DracoCompression;
  61157. })(BABYLON || (BABYLON = {}));
  61158. //# sourceMappingURL=babylon.dracoCompression.js.map
  61159. var BABYLON;
  61160. (function (BABYLON) {
  61161. var AudioEngine = /** @class */ (function () {
  61162. function AudioEngine() {
  61163. this._audioContext = null;
  61164. this._audioContextInitialized = false;
  61165. this.canUseWebAudio = false;
  61166. this.WarnedWebAudioUnsupported = false;
  61167. this.unlocked = false;
  61168. this.isMP3supported = false;
  61169. this.isOGGsupported = false;
  61170. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61171. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61172. this.canUseWebAudio = true;
  61173. }
  61174. var audioElem = document.createElement('audio');
  61175. try {
  61176. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61177. this.isMP3supported = true;
  61178. }
  61179. }
  61180. catch (e) {
  61181. // protect error during capability check.
  61182. }
  61183. try {
  61184. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61185. this.isOGGsupported = true;
  61186. }
  61187. }
  61188. catch (e) {
  61189. // protect error during capability check.
  61190. }
  61191. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61192. this._unlockiOSaudio();
  61193. }
  61194. else {
  61195. this.unlocked = true;
  61196. }
  61197. }
  61198. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61199. get: function () {
  61200. if (!this._audioContextInitialized) {
  61201. this._initializeAudioContext();
  61202. }
  61203. return this._audioContext;
  61204. },
  61205. enumerable: true,
  61206. configurable: true
  61207. });
  61208. AudioEngine.prototype._unlockiOSaudio = function () {
  61209. var _this = this;
  61210. var unlockaudio = function () {
  61211. if (!_this.audioContext) {
  61212. return;
  61213. }
  61214. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61215. var source = _this.audioContext.createBufferSource();
  61216. source.buffer = buffer;
  61217. source.connect(_this.audioContext.destination);
  61218. source.start(0);
  61219. setTimeout(function () {
  61220. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61221. _this.unlocked = true;
  61222. window.removeEventListener('touchend', unlockaudio, false);
  61223. if (_this.onAudioUnlocked) {
  61224. _this.onAudioUnlocked();
  61225. }
  61226. }
  61227. }, 0);
  61228. };
  61229. window.addEventListener('touchend', unlockaudio, false);
  61230. };
  61231. AudioEngine.prototype._initializeAudioContext = function () {
  61232. try {
  61233. if (this.canUseWebAudio) {
  61234. this._audioContext = new AudioContext();
  61235. // create a global volume gain node
  61236. this.masterGain = this._audioContext.createGain();
  61237. this.masterGain.gain.value = 1;
  61238. this.masterGain.connect(this._audioContext.destination);
  61239. this._audioContextInitialized = true;
  61240. }
  61241. }
  61242. catch (e) {
  61243. this.canUseWebAudio = false;
  61244. BABYLON.Tools.Error("Web Audio: " + e.message);
  61245. }
  61246. };
  61247. AudioEngine.prototype.dispose = function () {
  61248. if (this.canUseWebAudio && this._audioContextInitialized) {
  61249. if (this._connectedAnalyser && this._audioContext) {
  61250. this._connectedAnalyser.stopDebugCanvas();
  61251. this._connectedAnalyser.dispose();
  61252. this.masterGain.disconnect();
  61253. this.masterGain.connect(this._audioContext.destination);
  61254. this._connectedAnalyser = null;
  61255. }
  61256. this.masterGain.gain.value = 1;
  61257. }
  61258. this.WarnedWebAudioUnsupported = false;
  61259. };
  61260. AudioEngine.prototype.getGlobalVolume = function () {
  61261. if (this.canUseWebAudio && this._audioContextInitialized) {
  61262. return this.masterGain.gain.value;
  61263. }
  61264. else {
  61265. return -1;
  61266. }
  61267. };
  61268. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61269. if (this.canUseWebAudio && this._audioContextInitialized) {
  61270. this.masterGain.gain.value = newVolume;
  61271. }
  61272. };
  61273. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61274. if (this._connectedAnalyser) {
  61275. this._connectedAnalyser.stopDebugCanvas();
  61276. }
  61277. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61278. this._connectedAnalyser = analyser;
  61279. this.masterGain.disconnect();
  61280. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61281. }
  61282. };
  61283. return AudioEngine;
  61284. }());
  61285. BABYLON.AudioEngine = AudioEngine;
  61286. })(BABYLON || (BABYLON = {}));
  61287. //# sourceMappingURL=babylon.audioEngine.js.map
  61288. var BABYLON;
  61289. (function (BABYLON) {
  61290. var Sound = /** @class */ (function () {
  61291. /**
  61292. * Create a sound and attach it to a scene
  61293. * @param name Name of your sound
  61294. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61295. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61296. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61297. */
  61298. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61299. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61300. var _this = this;
  61301. this.autoplay = false;
  61302. this.loop = false;
  61303. this.useCustomAttenuation = false;
  61304. this.spatialSound = false;
  61305. this.refDistance = 1;
  61306. this.rolloffFactor = 1;
  61307. this.maxDistance = 100;
  61308. this.distanceModel = "linear";
  61309. this._panningModel = "equalpower";
  61310. this._playbackRate = 1;
  61311. this._streaming = false;
  61312. this._startTime = 0;
  61313. this._startOffset = 0;
  61314. this._position = BABYLON.Vector3.Zero();
  61315. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61316. this._volume = 1;
  61317. this._isReadyToPlay = false;
  61318. this.isPlaying = false;
  61319. this.isPaused = false;
  61320. this._isDirectional = false;
  61321. // Used if you'd like to create a directional sound.
  61322. // If not set, the sound will be omnidirectional
  61323. this._coneInnerAngle = 360;
  61324. this._coneOuterAngle = 360;
  61325. this._coneOuterGain = 0;
  61326. this._isOutputConnected = false;
  61327. this._urlType = "Unknown";
  61328. this.name = name;
  61329. this._scene = scene;
  61330. this._readyToPlayCallback = readyToPlayCallback;
  61331. // Default custom attenuation function is a linear attenuation
  61332. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61333. if (currentDistance < maxDistance) {
  61334. return currentVolume * (1 - currentDistance / maxDistance);
  61335. }
  61336. else {
  61337. return 0;
  61338. }
  61339. };
  61340. if (options) {
  61341. this.autoplay = options.autoplay || false;
  61342. this.loop = options.loop || false;
  61343. // if volume === 0, we need another way to check this option
  61344. if (options.volume !== undefined) {
  61345. this._volume = options.volume;
  61346. }
  61347. this.spatialSound = options.spatialSound || false;
  61348. this.maxDistance = options.maxDistance || 100;
  61349. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61350. this.rolloffFactor = options.rolloffFactor || 1;
  61351. this.refDistance = options.refDistance || 1;
  61352. this.distanceModel = options.distanceModel || "linear";
  61353. this._playbackRate = options.playbackRate || 1;
  61354. this._streaming = options.streaming || false;
  61355. }
  61356. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61357. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61358. this._soundGain.gain.value = this._volume;
  61359. this._inputAudioNode = this._soundGain;
  61360. this._ouputAudioNode = this._soundGain;
  61361. if (this.spatialSound) {
  61362. this._createSpatialParameters();
  61363. }
  61364. this._scene.mainSoundTrack.AddSound(this);
  61365. var validParameter = true;
  61366. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61367. if (urlOrArrayBuffer) {
  61368. try {
  61369. if (typeof (urlOrArrayBuffer) === "string")
  61370. this._urlType = "String";
  61371. if (Array.isArray(urlOrArrayBuffer))
  61372. this._urlType = "Array";
  61373. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61374. this._urlType = "ArrayBuffer";
  61375. var urls = [];
  61376. var codecSupportedFound = false;
  61377. switch (this._urlType) {
  61378. case "ArrayBuffer":
  61379. if (urlOrArrayBuffer.byteLength > 0) {
  61380. codecSupportedFound = true;
  61381. this._soundLoaded(urlOrArrayBuffer);
  61382. }
  61383. break;
  61384. case "String":
  61385. urls.push(urlOrArrayBuffer);
  61386. case "Array":
  61387. if (urls.length === 0)
  61388. urls = urlOrArrayBuffer;
  61389. // If we found a supported format, we load it immediately and stop the loop
  61390. for (var i = 0; i < urls.length; i++) {
  61391. var url = urls[i];
  61392. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61393. codecSupportedFound = true;
  61394. }
  61395. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61396. codecSupportedFound = true;
  61397. }
  61398. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61399. codecSupportedFound = true;
  61400. }
  61401. if (url.indexOf("blob:") !== -1) {
  61402. codecSupportedFound = true;
  61403. }
  61404. if (codecSupportedFound) {
  61405. // Loading sound using XHR2
  61406. if (!this._streaming) {
  61407. this._scene._loadFile(url, function (data) {
  61408. _this._soundLoaded(data);
  61409. }, undefined, true, true, function (exception) {
  61410. if (exception) {
  61411. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61412. }
  61413. BABYLON.Tools.Error("Sound creation aborted.");
  61414. _this._scene.mainSoundTrack.RemoveSound(_this);
  61415. });
  61416. }
  61417. // Streaming sound using HTML5 Audio tag
  61418. else {
  61419. this._htmlAudioElement = new Audio(url);
  61420. this._htmlAudioElement.controls = false;
  61421. this._htmlAudioElement.loop = this.loop;
  61422. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61423. this._htmlAudioElement.preload = "auto";
  61424. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61425. _this._isReadyToPlay = true;
  61426. if (_this.autoplay) {
  61427. _this.play();
  61428. }
  61429. if (_this._readyToPlayCallback) {
  61430. _this._readyToPlayCallback();
  61431. }
  61432. });
  61433. document.body.appendChild(this._htmlAudioElement);
  61434. }
  61435. break;
  61436. }
  61437. }
  61438. break;
  61439. default:
  61440. validParameter = false;
  61441. break;
  61442. }
  61443. if (!validParameter) {
  61444. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61445. }
  61446. else {
  61447. if (!codecSupportedFound) {
  61448. this._isReadyToPlay = true;
  61449. // Simulating a ready to play event to avoid breaking code path
  61450. if (this._readyToPlayCallback) {
  61451. window.setTimeout(function () {
  61452. if (_this._readyToPlayCallback) {
  61453. _this._readyToPlayCallback();
  61454. }
  61455. }, 1000);
  61456. }
  61457. }
  61458. }
  61459. }
  61460. catch (ex) {
  61461. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61462. this._scene.mainSoundTrack.RemoveSound(this);
  61463. }
  61464. }
  61465. }
  61466. else {
  61467. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61468. this._scene.mainSoundTrack.AddSound(this);
  61469. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61470. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61471. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61472. }
  61473. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61474. if (this._readyToPlayCallback) {
  61475. window.setTimeout(function () {
  61476. if (_this._readyToPlayCallback) {
  61477. _this._readyToPlayCallback();
  61478. }
  61479. }, 1000);
  61480. }
  61481. }
  61482. }
  61483. Sound.prototype.dispose = function () {
  61484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61485. if (this.isPlaying) {
  61486. this.stop();
  61487. }
  61488. this._isReadyToPlay = false;
  61489. if (this.soundTrackId === -1) {
  61490. this._scene.mainSoundTrack.RemoveSound(this);
  61491. }
  61492. else {
  61493. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61494. }
  61495. if (this._soundGain) {
  61496. this._soundGain.disconnect();
  61497. this._soundGain = null;
  61498. }
  61499. if (this._soundPanner) {
  61500. this._soundPanner.disconnect();
  61501. this._soundPanner = null;
  61502. }
  61503. if (this._soundSource) {
  61504. this._soundSource.disconnect();
  61505. this._soundSource = null;
  61506. }
  61507. this._audioBuffer = null;
  61508. if (this._htmlAudioElement) {
  61509. this._htmlAudioElement.pause();
  61510. this._htmlAudioElement.src = "";
  61511. document.body.removeChild(this._htmlAudioElement);
  61512. }
  61513. if (this._connectedMesh && this._registerFunc) {
  61514. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61515. this._connectedMesh = null;
  61516. }
  61517. }
  61518. };
  61519. Sound.prototype.isReady = function () {
  61520. return this._isReadyToPlay;
  61521. };
  61522. Sound.prototype._soundLoaded = function (audioData) {
  61523. var _this = this;
  61524. if (!BABYLON.Engine.audioEngine.audioContext) {
  61525. return;
  61526. }
  61527. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61528. _this._audioBuffer = buffer;
  61529. _this._isReadyToPlay = true;
  61530. if (_this.autoplay) {
  61531. _this.play();
  61532. }
  61533. if (_this._readyToPlayCallback) {
  61534. _this._readyToPlayCallback();
  61535. }
  61536. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61537. };
  61538. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61539. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61540. this._audioBuffer = audioBuffer;
  61541. this._isReadyToPlay = true;
  61542. }
  61543. };
  61544. Sound.prototype.updateOptions = function (options) {
  61545. if (options) {
  61546. this.loop = options.loop || this.loop;
  61547. this.maxDistance = options.maxDistance || this.maxDistance;
  61548. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61549. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61550. this.refDistance = options.refDistance || this.refDistance;
  61551. this.distanceModel = options.distanceModel || this.distanceModel;
  61552. this._playbackRate = options.playbackRate || this._playbackRate;
  61553. this._updateSpatialParameters();
  61554. if (this.isPlaying) {
  61555. if (this._streaming) {
  61556. this._htmlAudioElement.playbackRate = this._playbackRate;
  61557. }
  61558. else {
  61559. if (this._soundSource) {
  61560. this._soundSource.playbackRate.value = this._playbackRate;
  61561. }
  61562. }
  61563. }
  61564. }
  61565. };
  61566. Sound.prototype._createSpatialParameters = function () {
  61567. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61568. if (this._scene.headphone) {
  61569. this._panningModel = "HRTF";
  61570. }
  61571. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61572. this._updateSpatialParameters();
  61573. this._soundPanner.connect(this._ouputAudioNode);
  61574. this._inputAudioNode = this._soundPanner;
  61575. }
  61576. };
  61577. Sound.prototype._updateSpatialParameters = function () {
  61578. if (this.spatialSound && this._soundPanner) {
  61579. if (this.useCustomAttenuation) {
  61580. // Tricks to disable in a way embedded Web Audio attenuation
  61581. this._soundPanner.distanceModel = "linear";
  61582. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61583. this._soundPanner.refDistance = 1;
  61584. this._soundPanner.rolloffFactor = 1;
  61585. this._soundPanner.panningModel = this._panningModel;
  61586. }
  61587. else {
  61588. this._soundPanner.distanceModel = this.distanceModel;
  61589. this._soundPanner.maxDistance = this.maxDistance;
  61590. this._soundPanner.refDistance = this.refDistance;
  61591. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61592. this._soundPanner.panningModel = this._panningModel;
  61593. }
  61594. }
  61595. };
  61596. Sound.prototype.switchPanningModelToHRTF = function () {
  61597. this._panningModel = "HRTF";
  61598. this._switchPanningModel();
  61599. };
  61600. Sound.prototype.switchPanningModelToEqualPower = function () {
  61601. this._panningModel = "equalpower";
  61602. this._switchPanningModel();
  61603. };
  61604. Sound.prototype._switchPanningModel = function () {
  61605. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61606. this._soundPanner.panningModel = this._panningModel;
  61607. }
  61608. };
  61609. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61610. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61611. if (this._isOutputConnected) {
  61612. this._ouputAudioNode.disconnect();
  61613. }
  61614. this._ouputAudioNode.connect(soundTrackAudioNode);
  61615. this._isOutputConnected = true;
  61616. }
  61617. };
  61618. /**
  61619. * Transform this sound into a directional source
  61620. * @param coneInnerAngle Size of the inner cone in degree
  61621. * @param coneOuterAngle Size of the outer cone in degree
  61622. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61623. */
  61624. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61625. if (coneOuterAngle < coneInnerAngle) {
  61626. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61627. return;
  61628. }
  61629. this._coneInnerAngle = coneInnerAngle;
  61630. this._coneOuterAngle = coneOuterAngle;
  61631. this._coneOuterGain = coneOuterGain;
  61632. this._isDirectional = true;
  61633. if (this.isPlaying && this.loop) {
  61634. this.stop();
  61635. this.play();
  61636. }
  61637. };
  61638. Sound.prototype.setPosition = function (newPosition) {
  61639. this._position = newPosition;
  61640. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61641. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61642. }
  61643. };
  61644. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61645. this._localDirection = newLocalDirection;
  61646. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61647. this._updateDirection();
  61648. }
  61649. };
  61650. Sound.prototype._updateDirection = function () {
  61651. if (!this._connectedMesh || !this._soundPanner) {
  61652. return;
  61653. }
  61654. var mat = this._connectedMesh.getWorldMatrix();
  61655. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61656. direction.normalize();
  61657. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61658. };
  61659. Sound.prototype.updateDistanceFromListener = function () {
  61660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61661. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61662. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61663. }
  61664. };
  61665. Sound.prototype.setAttenuationFunction = function (callback) {
  61666. this._customAttenuationFunction = callback;
  61667. };
  61668. /**
  61669. * Play the sound
  61670. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61671. * @param offset (optional) Start the sound setting it at a specific time
  61672. */
  61673. Sound.prototype.play = function (time, offset) {
  61674. var _this = this;
  61675. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61676. try {
  61677. if (this._startOffset < 0) {
  61678. time = -this._startOffset;
  61679. this._startOffset = 0;
  61680. }
  61681. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61682. if (!this._soundSource || !this._streamingSource) {
  61683. if (this.spatialSound && this._soundPanner) {
  61684. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61685. if (this._isDirectional) {
  61686. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61687. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61688. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61689. if (this._connectedMesh) {
  61690. this._updateDirection();
  61691. }
  61692. else {
  61693. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61694. }
  61695. }
  61696. }
  61697. }
  61698. if (this._streaming) {
  61699. if (!this._streamingSource) {
  61700. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61701. this._htmlAudioElement.onended = function () { _this._onended(); };
  61702. this._htmlAudioElement.playbackRate = this._playbackRate;
  61703. }
  61704. this._streamingSource.disconnect();
  61705. this._streamingSource.connect(this._inputAudioNode);
  61706. this._htmlAudioElement.play();
  61707. }
  61708. else {
  61709. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61710. this._soundSource.buffer = this._audioBuffer;
  61711. this._soundSource.connect(this._inputAudioNode);
  61712. this._soundSource.loop = this.loop;
  61713. this._soundSource.playbackRate.value = this._playbackRate;
  61714. this._soundSource.onended = function () { _this._onended(); };
  61715. if (this._soundSource.buffer) {
  61716. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61717. }
  61718. }
  61719. this._startTime = startTime;
  61720. this.isPlaying = true;
  61721. this.isPaused = false;
  61722. }
  61723. catch (ex) {
  61724. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61725. }
  61726. }
  61727. };
  61728. Sound.prototype._onended = function () {
  61729. this.isPlaying = false;
  61730. if (this.onended) {
  61731. this.onended();
  61732. }
  61733. };
  61734. /**
  61735. * Stop the sound
  61736. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61737. */
  61738. Sound.prototype.stop = function (time) {
  61739. if (this.isPlaying) {
  61740. if (this._streaming) {
  61741. this._htmlAudioElement.pause();
  61742. // Test needed for Firefox or it will generate an Invalid State Error
  61743. if (this._htmlAudioElement.currentTime > 0) {
  61744. this._htmlAudioElement.currentTime = 0;
  61745. }
  61746. }
  61747. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61748. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61749. this._soundSource.stop(stopTime);
  61750. this._soundSource.onended = function () { };
  61751. if (!this.isPaused) {
  61752. this._startOffset = 0;
  61753. }
  61754. }
  61755. this.isPlaying = false;
  61756. }
  61757. };
  61758. Sound.prototype.pause = function () {
  61759. if (this.isPlaying) {
  61760. this.isPaused = true;
  61761. if (this._streaming) {
  61762. this._htmlAudioElement.pause();
  61763. }
  61764. else if (BABYLON.Engine.audioEngine.audioContext) {
  61765. this.stop(0);
  61766. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61767. }
  61768. }
  61769. };
  61770. Sound.prototype.setVolume = function (newVolume, time) {
  61771. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61772. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61773. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61774. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61775. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61776. }
  61777. else {
  61778. this._soundGain.gain.value = newVolume;
  61779. }
  61780. }
  61781. this._volume = newVolume;
  61782. };
  61783. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61784. this._playbackRate = newPlaybackRate;
  61785. if (this.isPlaying) {
  61786. if (this._streaming) {
  61787. this._htmlAudioElement.playbackRate = this._playbackRate;
  61788. }
  61789. else if (this._soundSource) {
  61790. this._soundSource.playbackRate.value = this._playbackRate;
  61791. }
  61792. }
  61793. };
  61794. Sound.prototype.getVolume = function () {
  61795. return this._volume;
  61796. };
  61797. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61798. var _this = this;
  61799. if (this._connectedMesh && this._registerFunc) {
  61800. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61801. this._registerFunc = null;
  61802. }
  61803. this._connectedMesh = meshToConnectTo;
  61804. if (!this.spatialSound) {
  61805. this.spatialSound = true;
  61806. this._createSpatialParameters();
  61807. if (this.isPlaying && this.loop) {
  61808. this.stop();
  61809. this.play();
  61810. }
  61811. }
  61812. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61813. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61814. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61815. };
  61816. Sound.prototype.detachFromMesh = function () {
  61817. if (this._connectedMesh && this._registerFunc) {
  61818. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61819. this._registerFunc = null;
  61820. this._connectedMesh = null;
  61821. }
  61822. };
  61823. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61824. if (!node.getBoundingInfo) {
  61825. return;
  61826. }
  61827. var mesh = node;
  61828. var boundingInfo = mesh.getBoundingInfo();
  61829. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61831. this._updateDirection();
  61832. }
  61833. };
  61834. Sound.prototype.clone = function () {
  61835. var _this = this;
  61836. if (!this._streaming) {
  61837. var setBufferAndRun = function () {
  61838. if (_this._isReadyToPlay) {
  61839. clonedSound._audioBuffer = _this.getAudioBuffer();
  61840. clonedSound._isReadyToPlay = true;
  61841. if (clonedSound.autoplay) {
  61842. clonedSound.play();
  61843. }
  61844. }
  61845. else {
  61846. window.setTimeout(setBufferAndRun, 300);
  61847. }
  61848. };
  61849. var currentOptions = {
  61850. autoplay: this.autoplay, loop: this.loop,
  61851. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61852. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61853. refDistance: this.refDistance, distanceModel: this.distanceModel
  61854. };
  61855. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61856. if (this.useCustomAttenuation) {
  61857. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61858. }
  61859. clonedSound.setPosition(this._position);
  61860. clonedSound.setPlaybackRate(this._playbackRate);
  61861. setBufferAndRun();
  61862. return clonedSound;
  61863. }
  61864. // Can't clone a streaming sound
  61865. else {
  61866. return null;
  61867. }
  61868. };
  61869. Sound.prototype.getAudioBuffer = function () {
  61870. return this._audioBuffer;
  61871. };
  61872. Sound.prototype.serialize = function () {
  61873. var serializationObject = {
  61874. name: this.name,
  61875. url: this.name,
  61876. autoplay: this.autoplay,
  61877. loop: this.loop,
  61878. volume: this._volume,
  61879. spatialSound: this.spatialSound,
  61880. maxDistance: this.maxDistance,
  61881. rolloffFactor: this.rolloffFactor,
  61882. refDistance: this.refDistance,
  61883. distanceModel: this.distanceModel,
  61884. playbackRate: this._playbackRate,
  61885. panningModel: this._panningModel,
  61886. soundTrackId: this.soundTrackId
  61887. };
  61888. if (this.spatialSound) {
  61889. if (this._connectedMesh)
  61890. serializationObject.connectedMeshId = this._connectedMesh.id;
  61891. serializationObject.position = this._position.asArray();
  61892. serializationObject.refDistance = this.refDistance;
  61893. serializationObject.distanceModel = this.distanceModel;
  61894. serializationObject.isDirectional = this._isDirectional;
  61895. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61896. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61897. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61898. serializationObject.coneOuterGain = this._coneOuterGain;
  61899. }
  61900. return serializationObject;
  61901. };
  61902. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61903. var soundName = parsedSound.name;
  61904. var soundUrl;
  61905. if (parsedSound.url) {
  61906. soundUrl = rootUrl + parsedSound.url;
  61907. }
  61908. else {
  61909. soundUrl = rootUrl + soundName;
  61910. }
  61911. var options = {
  61912. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61913. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61914. rolloffFactor: parsedSound.rolloffFactor,
  61915. refDistance: parsedSound.refDistance,
  61916. distanceModel: parsedSound.distanceModel,
  61917. playbackRate: parsedSound.playbackRate
  61918. };
  61919. var newSound;
  61920. if (!sourceSound) {
  61921. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61922. scene._addPendingData(newSound);
  61923. }
  61924. else {
  61925. var setBufferAndRun = function () {
  61926. if (sourceSound._isReadyToPlay) {
  61927. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61928. newSound._isReadyToPlay = true;
  61929. if (newSound.autoplay) {
  61930. newSound.play();
  61931. }
  61932. }
  61933. else {
  61934. window.setTimeout(setBufferAndRun, 300);
  61935. }
  61936. };
  61937. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61938. setBufferAndRun();
  61939. }
  61940. if (parsedSound.position) {
  61941. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61942. newSound.setPosition(soundPosition);
  61943. }
  61944. if (parsedSound.isDirectional) {
  61945. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61946. if (parsedSound.localDirectionToMesh) {
  61947. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61948. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61949. }
  61950. }
  61951. if (parsedSound.connectedMeshId) {
  61952. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61953. if (connectedMesh) {
  61954. newSound.attachToMesh(connectedMesh);
  61955. }
  61956. }
  61957. return newSound;
  61958. };
  61959. return Sound;
  61960. }());
  61961. BABYLON.Sound = Sound;
  61962. })(BABYLON || (BABYLON = {}));
  61963. //# sourceMappingURL=babylon.sound.js.map
  61964. var BABYLON;
  61965. (function (BABYLON) {
  61966. var SoundTrack = /** @class */ (function () {
  61967. function SoundTrack(scene, options) {
  61968. this.id = -1;
  61969. this._isMainTrack = false;
  61970. this._isInitialized = false;
  61971. this._scene = scene;
  61972. this.soundCollection = new Array();
  61973. this._options = options;
  61974. if (!this._isMainTrack) {
  61975. this._scene.soundTracks.push(this);
  61976. this.id = this._scene.soundTracks.length - 1;
  61977. }
  61978. }
  61979. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61980. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61981. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61982. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61983. if (this._options) {
  61984. if (this._options.volume) {
  61985. this._outputAudioNode.gain.value = this._options.volume;
  61986. }
  61987. if (this._options.mainTrack) {
  61988. this._isMainTrack = this._options.mainTrack;
  61989. }
  61990. }
  61991. this._isInitialized = true;
  61992. }
  61993. };
  61994. SoundTrack.prototype.dispose = function () {
  61995. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61996. if (this._connectedAnalyser) {
  61997. this._connectedAnalyser.stopDebugCanvas();
  61998. }
  61999. while (this.soundCollection.length) {
  62000. this.soundCollection[0].dispose();
  62001. }
  62002. if (this._outputAudioNode) {
  62003. this._outputAudioNode.disconnect();
  62004. }
  62005. this._outputAudioNode = null;
  62006. }
  62007. };
  62008. SoundTrack.prototype.AddSound = function (sound) {
  62009. if (!this._isInitialized) {
  62010. this._initializeSoundTrackAudioGraph();
  62011. }
  62012. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62013. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62014. }
  62015. if (sound.soundTrackId) {
  62016. if (sound.soundTrackId === -1) {
  62017. this._scene.mainSoundTrack.RemoveSound(sound);
  62018. }
  62019. else {
  62020. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62021. }
  62022. }
  62023. this.soundCollection.push(sound);
  62024. sound.soundTrackId = this.id;
  62025. };
  62026. SoundTrack.prototype.RemoveSound = function (sound) {
  62027. var index = this.soundCollection.indexOf(sound);
  62028. if (index !== -1) {
  62029. this.soundCollection.splice(index, 1);
  62030. }
  62031. };
  62032. SoundTrack.prototype.setVolume = function (newVolume) {
  62033. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62034. this._outputAudioNode.gain.value = newVolume;
  62035. }
  62036. };
  62037. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62039. for (var i = 0; i < this.soundCollection.length; i++) {
  62040. this.soundCollection[i].switchPanningModelToHRTF();
  62041. }
  62042. }
  62043. };
  62044. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62046. for (var i = 0; i < this.soundCollection.length; i++) {
  62047. this.soundCollection[i].switchPanningModelToEqualPower();
  62048. }
  62049. }
  62050. };
  62051. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62052. if (this._connectedAnalyser) {
  62053. this._connectedAnalyser.stopDebugCanvas();
  62054. }
  62055. this._connectedAnalyser = analyser;
  62056. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62057. this._outputAudioNode.disconnect();
  62058. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62059. }
  62060. };
  62061. return SoundTrack;
  62062. }());
  62063. BABYLON.SoundTrack = SoundTrack;
  62064. })(BABYLON || (BABYLON = {}));
  62065. //# sourceMappingURL=babylon.soundtrack.js.map
  62066. var BABYLON;
  62067. (function (BABYLON) {
  62068. /**
  62069. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62070. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62071. */
  62072. var Analyser = /** @class */ (function () {
  62073. /**
  62074. * Creates a new analyser
  62075. * @param scene defines hosting scene
  62076. */
  62077. function Analyser(scene) {
  62078. /**
  62079. * Gets or sets the smoothing
  62080. * @ignorenaming
  62081. */
  62082. this.SMOOTHING = 0.75;
  62083. /**
  62084. * Gets or sets the FFT table size
  62085. * @ignorenaming
  62086. */
  62087. this.FFT_SIZE = 512;
  62088. /**
  62089. * Gets or sets the bar graph amplitude
  62090. * @ignorenaming
  62091. */
  62092. this.BARGRAPHAMPLITUDE = 256;
  62093. /**
  62094. * Gets or sets the position of the debug canvas
  62095. * @ignorenaming
  62096. */
  62097. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62098. /**
  62099. * Gets or sets the debug canvas size
  62100. * @ignorenaming
  62101. */
  62102. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62103. this._scene = scene;
  62104. this._audioEngine = BABYLON.Engine.audioEngine;
  62105. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62106. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62107. this._webAudioAnalyser.minDecibels = -140;
  62108. this._webAudioAnalyser.maxDecibels = 0;
  62109. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62110. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62111. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62112. }
  62113. }
  62114. /**
  62115. * Get the number of data values you will have to play with for the visualization
  62116. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62117. * @returns a number
  62118. */
  62119. Analyser.prototype.getFrequencyBinCount = function () {
  62120. if (this._audioEngine.canUseWebAudio) {
  62121. return this._webAudioAnalyser.frequencyBinCount;
  62122. }
  62123. else {
  62124. return 0;
  62125. }
  62126. };
  62127. /**
  62128. * Gets the current frequency data as a byte array
  62129. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62130. * @returns a Uint8Array
  62131. */
  62132. Analyser.prototype.getByteFrequencyData = function () {
  62133. if (this._audioEngine.canUseWebAudio) {
  62134. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62135. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62136. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62137. }
  62138. return this._byteFreqs;
  62139. };
  62140. /**
  62141. * Gets the current waveform as a byte array
  62142. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62143. * @returns a Uint8Array
  62144. */
  62145. Analyser.prototype.getByteTimeDomainData = function () {
  62146. if (this._audioEngine.canUseWebAudio) {
  62147. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62148. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62149. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62150. }
  62151. return this._byteTime;
  62152. };
  62153. /**
  62154. * Gets the current frequency data as a float array
  62155. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62156. * @returns a Float32Array
  62157. */
  62158. Analyser.prototype.getFloatFrequencyData = function () {
  62159. if (this._audioEngine.canUseWebAudio) {
  62160. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62161. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62162. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62163. }
  62164. return this._floatFreqs;
  62165. };
  62166. /**
  62167. * Renders the debug canvas
  62168. */
  62169. Analyser.prototype.drawDebugCanvas = function () {
  62170. var _this = this;
  62171. if (this._audioEngine.canUseWebAudio) {
  62172. if (!this._debugCanvas) {
  62173. this._debugCanvas = document.createElement("canvas");
  62174. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62175. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62176. this._debugCanvas.style.position = "absolute";
  62177. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62178. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62179. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62180. document.body.appendChild(this._debugCanvas);
  62181. this._registerFunc = function () {
  62182. _this.drawDebugCanvas();
  62183. };
  62184. this._scene.registerBeforeRender(this._registerFunc);
  62185. }
  62186. if (this._registerFunc && this._debugCanvasContext) {
  62187. var workingArray = this.getByteFrequencyData();
  62188. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62189. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62190. // Draw the frequency domain chart.
  62191. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62192. var value = workingArray[i];
  62193. var percent = value / this.BARGRAPHAMPLITUDE;
  62194. var height = this.DEBUGCANVASSIZE.height * percent;
  62195. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62196. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62197. var hue = i / this.getFrequencyBinCount() * 360;
  62198. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62199. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62200. }
  62201. }
  62202. }
  62203. };
  62204. /**
  62205. * Stops rendering the debug canvas and removes it
  62206. */
  62207. Analyser.prototype.stopDebugCanvas = function () {
  62208. if (this._debugCanvas) {
  62209. if (this._registerFunc) {
  62210. this._scene.unregisterBeforeRender(this._registerFunc);
  62211. this._registerFunc = null;
  62212. }
  62213. document.body.removeChild(this._debugCanvas);
  62214. this._debugCanvas = null;
  62215. this._debugCanvasContext = null;
  62216. }
  62217. };
  62218. /**
  62219. * Connects two audio nodes
  62220. * @param inputAudioNode defines first node to connect
  62221. * @param outputAudioNode defines second node to connect
  62222. */
  62223. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62224. if (this._audioEngine.canUseWebAudio) {
  62225. inputAudioNode.connect(this._webAudioAnalyser);
  62226. this._webAudioAnalyser.connect(outputAudioNode);
  62227. }
  62228. };
  62229. /**
  62230. * Releases all associated resources
  62231. */
  62232. Analyser.prototype.dispose = function () {
  62233. if (this._audioEngine.canUseWebAudio) {
  62234. this._webAudioAnalyser.disconnect();
  62235. }
  62236. };
  62237. return Analyser;
  62238. }());
  62239. BABYLON.Analyser = Analyser;
  62240. })(BABYLON || (BABYLON = {}));
  62241. //# sourceMappingURL=babylon.analyser.js.map
  62242. var BABYLON;
  62243. (function (BABYLON) {
  62244. var CubeTexture = /** @class */ (function (_super) {
  62245. __extends(CubeTexture, _super);
  62246. /**
  62247. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62248. * as prefiltered data.
  62249. * @param rootUrl defines the url of the texture or the root name of the six images
  62250. * @param scene defines the scene the texture is attached to
  62251. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62252. * @param noMipmap defines if mipmaps should be created or not
  62253. * @param files defines the six files to load for the different faces
  62254. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62255. * @param onError defines a callback triggered in case of error during load
  62256. * @param format defines the internal format to use for the texture once loaded
  62257. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62258. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62259. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62260. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62261. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62262. * @return the cube texture
  62263. */
  62264. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62265. if (extensions === void 0) { extensions = null; }
  62266. if (noMipmap === void 0) { noMipmap = false; }
  62267. if (files === void 0) { files = null; }
  62268. if (onLoad === void 0) { onLoad = null; }
  62269. if (onError === void 0) { onError = null; }
  62270. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62271. if (prefiltered === void 0) { prefiltered = false; }
  62272. if (forcedExtension === void 0) { forcedExtension = null; }
  62273. if (createPolynomials === void 0) { createPolynomials = false; }
  62274. if (lodScale === void 0) { lodScale = 0.8; }
  62275. if (lodOffset === void 0) { lodOffset = 0; }
  62276. var _this = _super.call(this, scene) || this;
  62277. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62278. /**
  62279. * Gets or sets the center of the bounding box associated with the cube texture
  62280. * It must define where the camera used to render the texture was set
  62281. */
  62282. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62283. _this._rotationY = 0;
  62284. /** @hidden */
  62285. _this._prefiltered = false;
  62286. _this.name = rootUrl;
  62287. _this.url = rootUrl;
  62288. _this._noMipmap = noMipmap;
  62289. _this.hasAlpha = false;
  62290. _this._format = format;
  62291. _this.isCube = true;
  62292. _this._textureMatrix = BABYLON.Matrix.Identity();
  62293. _this._createPolynomials = createPolynomials;
  62294. if (!rootUrl && !files) {
  62295. return _this;
  62296. }
  62297. var lastDot = rootUrl.lastIndexOf(".");
  62298. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62299. var isDDS = (extension === ".dds");
  62300. var isEnv = (extension === ".env");
  62301. if (isEnv) {
  62302. _this.gammaSpace = false;
  62303. _this._prefiltered = false;
  62304. }
  62305. else {
  62306. _this._prefiltered = prefiltered;
  62307. if (prefiltered) {
  62308. _this.gammaSpace = false;
  62309. }
  62310. }
  62311. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62312. if (!files) {
  62313. if (!isEnv && !isDDS && !extensions) {
  62314. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62315. }
  62316. files = [];
  62317. if (extensions) {
  62318. for (var index = 0; index < extensions.length; index++) {
  62319. files.push(rootUrl + extensions[index]);
  62320. }
  62321. }
  62322. }
  62323. _this._files = files;
  62324. if (!_this._texture) {
  62325. if (!scene.useDelayedTextureLoading) {
  62326. if (prefiltered) {
  62327. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62328. }
  62329. else {
  62330. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62331. }
  62332. }
  62333. else {
  62334. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62335. }
  62336. }
  62337. else if (onLoad) {
  62338. if (_this._texture.isReady) {
  62339. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62340. }
  62341. else {
  62342. _this._texture.onLoadedObservable.add(onLoad);
  62343. }
  62344. }
  62345. return _this;
  62346. }
  62347. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62348. get: function () {
  62349. return this._boundingBoxSize;
  62350. },
  62351. /**
  62352. * Gets or sets the size of the bounding box associated with the cube texture
  62353. * When defined, the cubemap will switch to local mode
  62354. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62355. * @example https://www.babylonjs-playground.com/#RNASML
  62356. */
  62357. set: function (value) {
  62358. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62359. return;
  62360. }
  62361. this._boundingBoxSize = value;
  62362. var scene = this.getScene();
  62363. if (scene) {
  62364. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62365. }
  62366. },
  62367. enumerable: true,
  62368. configurable: true
  62369. });
  62370. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62371. /**
  62372. * Gets texture matrix rotation angle around Y axis radians.
  62373. */
  62374. get: function () {
  62375. return this._rotationY;
  62376. },
  62377. /**
  62378. * Sets texture matrix rotation angle around Y axis in radians.
  62379. */
  62380. set: function (value) {
  62381. this._rotationY = value;
  62382. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62383. },
  62384. enumerable: true,
  62385. configurable: true
  62386. });
  62387. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62388. var rootUrlKey = "";
  62389. files.forEach(function (url) { return rootUrlKey += url; });
  62390. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62391. };
  62392. /**
  62393. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62394. * @param url defines the url of the prefiltered texture
  62395. * @param scene defines the scene the texture is attached to
  62396. * @param forcedExtension defines the extension of the file if different from the url
  62397. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62398. * @return the prefiltered texture
  62399. */
  62400. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62401. if (forcedExtension === void 0) { forcedExtension = null; }
  62402. if (createPolynomials === void 0) { createPolynomials = true; }
  62403. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62404. };
  62405. // Methods
  62406. CubeTexture.prototype.delayLoad = function () {
  62407. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62408. return;
  62409. }
  62410. var scene = this.getScene();
  62411. if (!scene) {
  62412. return;
  62413. }
  62414. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62415. this._texture = this._getFromCache(this.url, this._noMipmap);
  62416. if (!this._texture) {
  62417. if (this._prefiltered) {
  62418. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62419. }
  62420. else {
  62421. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62422. }
  62423. }
  62424. };
  62425. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62426. return this._textureMatrix;
  62427. };
  62428. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62429. this._textureMatrix = value;
  62430. };
  62431. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62432. var texture = BABYLON.SerializationHelper.Parse(function () {
  62433. var prefiltered = false;
  62434. if (parsedTexture.prefiltered) {
  62435. prefiltered = parsedTexture.prefiltered;
  62436. }
  62437. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62438. }, parsedTexture, scene);
  62439. // Local Cubemaps
  62440. if (parsedTexture.boundingBoxPosition) {
  62441. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62442. }
  62443. if (parsedTexture.boundingBoxSize) {
  62444. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62445. }
  62446. // Animations
  62447. if (parsedTexture.animations) {
  62448. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62449. var parsedAnimation = parsedTexture.animations[animationIndex];
  62450. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62451. }
  62452. }
  62453. return texture;
  62454. };
  62455. CubeTexture.prototype.clone = function () {
  62456. var _this = this;
  62457. return BABYLON.SerializationHelper.Clone(function () {
  62458. var scene = _this.getScene();
  62459. if (!scene) {
  62460. return _this;
  62461. }
  62462. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62463. }, this);
  62464. };
  62465. __decorate([
  62466. BABYLON.serialize("rotationY")
  62467. ], CubeTexture.prototype, "_rotationY", void 0);
  62468. return CubeTexture;
  62469. }(BABYLON.BaseTexture));
  62470. BABYLON.CubeTexture = CubeTexture;
  62471. })(BABYLON || (BABYLON = {}));
  62472. //# sourceMappingURL=babylon.cubeTexture.js.map
  62473. var BABYLON;
  62474. (function (BABYLON) {
  62475. var RenderTargetTexture = /** @class */ (function (_super) {
  62476. __extends(RenderTargetTexture, _super);
  62477. /**
  62478. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62479. * or used a shadow, depth texture...
  62480. * @param name The friendly name of the texture
  62481. * @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)
  62482. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62483. * @param generateMipMaps True if mip maps need to be generated after render.
  62484. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62485. * @param type The type of the buffer in the RTT (int, half float, float...)
  62486. * @param isCube True if a cube texture needs to be created
  62487. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62488. * @param generateDepthBuffer True to generate a depth buffer
  62489. * @param generateStencilBuffer True to generate a stencil buffer
  62490. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62491. */
  62492. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62493. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62494. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62495. if (isCube === void 0) { isCube = false; }
  62496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62497. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62498. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62499. if (isMulti === void 0) { isMulti = false; }
  62500. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62501. _this.isCube = isCube;
  62502. /**
  62503. * Use this list to define the list of mesh you want to render.
  62504. */
  62505. _this.renderList = new Array();
  62506. _this.renderParticles = true;
  62507. _this.renderSprites = false;
  62508. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62509. _this.ignoreCameraViewport = false;
  62510. // Events
  62511. /**
  62512. * An event triggered when the texture is unbind.
  62513. */
  62514. _this.onBeforeBindObservable = new BABYLON.Observable();
  62515. /**
  62516. * An event triggered when the texture is unbind.
  62517. */
  62518. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62519. /**
  62520. * An event triggered before rendering the texture
  62521. */
  62522. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62523. /**
  62524. * An event triggered after rendering the texture
  62525. */
  62526. _this.onAfterRenderObservable = new BABYLON.Observable();
  62527. /**
  62528. * An event triggered after the texture clear
  62529. */
  62530. _this.onClearObservable = new BABYLON.Observable();
  62531. _this._currentRefreshId = -1;
  62532. _this._refreshRate = 1;
  62533. _this._samples = 1;
  62534. /**
  62535. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62536. * It must define where the camera used to render the texture is set
  62537. */
  62538. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62539. scene = _this.getScene();
  62540. if (!scene) {
  62541. return _this;
  62542. }
  62543. _this._engine = scene.getEngine();
  62544. _this.name = name;
  62545. _this.isRenderTarget = true;
  62546. _this._initialSizeParameter = size;
  62547. _this._processSizeParameter(size);
  62548. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62549. });
  62550. _this._generateMipMaps = generateMipMaps ? true : false;
  62551. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62552. // Rendering groups
  62553. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62554. if (isMulti) {
  62555. return _this;
  62556. }
  62557. _this._renderTargetOptions = {
  62558. generateMipMaps: generateMipMaps,
  62559. type: type,
  62560. samplingMode: samplingMode,
  62561. generateDepthBuffer: generateDepthBuffer,
  62562. generateStencilBuffer: generateStencilBuffer
  62563. };
  62564. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62565. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62566. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62567. }
  62568. if (isCube) {
  62569. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62570. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62571. _this._textureMatrix = BABYLON.Matrix.Identity();
  62572. }
  62573. else {
  62574. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62575. }
  62576. return _this;
  62577. }
  62578. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62579. get: function () {
  62580. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62581. },
  62582. enumerable: true,
  62583. configurable: true
  62584. });
  62585. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62586. get: function () {
  62587. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62588. },
  62589. enumerable: true,
  62590. configurable: true
  62591. });
  62592. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62593. get: function () {
  62594. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62595. },
  62596. enumerable: true,
  62597. configurable: true
  62598. });
  62599. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62600. set: function (callback) {
  62601. if (this._onAfterUnbindObserver) {
  62602. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62603. }
  62604. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62605. },
  62606. enumerable: true,
  62607. configurable: true
  62608. });
  62609. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62610. set: function (callback) {
  62611. if (this._onBeforeRenderObserver) {
  62612. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62613. }
  62614. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62615. },
  62616. enumerable: true,
  62617. configurable: true
  62618. });
  62619. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62620. set: function (callback) {
  62621. if (this._onAfterRenderObserver) {
  62622. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62623. }
  62624. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62625. },
  62626. enumerable: true,
  62627. configurable: true
  62628. });
  62629. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62630. set: function (callback) {
  62631. if (this._onClearObserver) {
  62632. this.onClearObservable.remove(this._onClearObserver);
  62633. }
  62634. this._onClearObserver = this.onClearObservable.add(callback);
  62635. },
  62636. enumerable: true,
  62637. configurable: true
  62638. });
  62639. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62640. get: function () {
  62641. return this._renderTargetOptions;
  62642. },
  62643. enumerable: true,
  62644. configurable: true
  62645. });
  62646. RenderTargetTexture.prototype._onRatioRescale = function () {
  62647. if (this._sizeRatio) {
  62648. this.resize(this._initialSizeParameter);
  62649. }
  62650. };
  62651. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62652. get: function () {
  62653. return this._boundingBoxSize;
  62654. },
  62655. /**
  62656. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62657. * When defined, the cubemap will switch to local mode
  62658. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62659. * @example https://www.babylonjs-playground.com/#RNASML
  62660. */
  62661. set: function (value) {
  62662. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62663. return;
  62664. }
  62665. this._boundingBoxSize = value;
  62666. var scene = this.getScene();
  62667. if (scene) {
  62668. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62669. }
  62670. },
  62671. enumerable: true,
  62672. configurable: true
  62673. });
  62674. /**
  62675. * Creates a depth stencil texture.
  62676. * This is only available in WebGL 2 or with the depth texture extension available.
  62677. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62678. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62679. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62680. */
  62681. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62682. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62683. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62684. if (generateStencil === void 0) { generateStencil = false; }
  62685. if (!this.getScene()) {
  62686. return;
  62687. }
  62688. var engine = this.getScene().getEngine();
  62689. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62690. bilinearFiltering: bilinearFiltering,
  62691. comparisonFunction: comparisonFunction,
  62692. generateStencil: generateStencil,
  62693. isCube: this.isCube
  62694. });
  62695. engine.setFrameBufferDepthStencilTexture(this);
  62696. };
  62697. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62698. if (size.ratio) {
  62699. this._sizeRatio = size.ratio;
  62700. this._size = {
  62701. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62702. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62703. };
  62704. }
  62705. else {
  62706. this._size = size;
  62707. }
  62708. };
  62709. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62710. get: function () {
  62711. return this._samples;
  62712. },
  62713. set: function (value) {
  62714. if (this._samples === value) {
  62715. return;
  62716. }
  62717. var scene = this.getScene();
  62718. if (!scene) {
  62719. return;
  62720. }
  62721. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62722. },
  62723. enumerable: true,
  62724. configurable: true
  62725. });
  62726. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62727. this._currentRefreshId = -1;
  62728. };
  62729. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62730. get: function () {
  62731. return this._refreshRate;
  62732. },
  62733. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62734. set: function (value) {
  62735. this._refreshRate = value;
  62736. this.resetRefreshCounter();
  62737. },
  62738. enumerable: true,
  62739. configurable: true
  62740. });
  62741. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62742. if (!this._postProcessManager) {
  62743. var scene = this.getScene();
  62744. if (!scene) {
  62745. return;
  62746. }
  62747. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62748. this._postProcesses = new Array();
  62749. }
  62750. this._postProcesses.push(postProcess);
  62751. this._postProcesses[0].autoClear = false;
  62752. };
  62753. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62754. if (!this._postProcesses) {
  62755. return;
  62756. }
  62757. if (dispose) {
  62758. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62759. var postProcess = _a[_i];
  62760. postProcess.dispose();
  62761. }
  62762. }
  62763. this._postProcesses = [];
  62764. };
  62765. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62766. if (!this._postProcesses) {
  62767. return;
  62768. }
  62769. var index = this._postProcesses.indexOf(postProcess);
  62770. if (index === -1) {
  62771. return;
  62772. }
  62773. this._postProcesses.splice(index, 1);
  62774. if (this._postProcesses.length > 0) {
  62775. this._postProcesses[0].autoClear = false;
  62776. }
  62777. };
  62778. RenderTargetTexture.prototype._shouldRender = function () {
  62779. if (this._currentRefreshId === -1) { // At least render once
  62780. this._currentRefreshId = 1;
  62781. return true;
  62782. }
  62783. if (this.refreshRate === this._currentRefreshId) {
  62784. this._currentRefreshId = 1;
  62785. return true;
  62786. }
  62787. this._currentRefreshId++;
  62788. return false;
  62789. };
  62790. RenderTargetTexture.prototype.getRenderSize = function () {
  62791. if (this._size.width) {
  62792. return this._size.width;
  62793. }
  62794. return this._size;
  62795. };
  62796. RenderTargetTexture.prototype.getRenderWidth = function () {
  62797. if (this._size.width) {
  62798. return this._size.width;
  62799. }
  62800. return this._size;
  62801. };
  62802. RenderTargetTexture.prototype.getRenderHeight = function () {
  62803. if (this._size.width) {
  62804. return this._size.height;
  62805. }
  62806. return this._size;
  62807. };
  62808. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62809. get: function () {
  62810. return true;
  62811. },
  62812. enumerable: true,
  62813. configurable: true
  62814. });
  62815. RenderTargetTexture.prototype.scale = function (ratio) {
  62816. var newSize = this.getRenderSize() * ratio;
  62817. this.resize(newSize);
  62818. };
  62819. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62820. if (this.isCube) {
  62821. return this._textureMatrix;
  62822. }
  62823. return _super.prototype.getReflectionTextureMatrix.call(this);
  62824. };
  62825. RenderTargetTexture.prototype.resize = function (size) {
  62826. this.releaseInternalTexture();
  62827. var scene = this.getScene();
  62828. if (!scene) {
  62829. return;
  62830. }
  62831. this._processSizeParameter(size);
  62832. if (this.isCube) {
  62833. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62834. }
  62835. else {
  62836. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62837. }
  62838. };
  62839. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62840. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62841. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62842. var scene = this.getScene();
  62843. if (!scene) {
  62844. return;
  62845. }
  62846. var engine = scene.getEngine();
  62847. if (this.useCameraPostProcesses !== undefined) {
  62848. useCameraPostProcess = this.useCameraPostProcesses;
  62849. }
  62850. if (this._waitingRenderList) {
  62851. this.renderList = [];
  62852. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62853. var id = this._waitingRenderList[index];
  62854. var mesh_1 = scene.getMeshByID(id);
  62855. if (mesh_1) {
  62856. this.renderList.push(mesh_1);
  62857. }
  62858. }
  62859. delete this._waitingRenderList;
  62860. }
  62861. // Is predicate defined?
  62862. if (this.renderListPredicate) {
  62863. if (this.renderList) {
  62864. this.renderList.splice(0); // Clear previous renderList
  62865. }
  62866. else {
  62867. this.renderList = [];
  62868. }
  62869. var scene = this.getScene();
  62870. if (!scene) {
  62871. return;
  62872. }
  62873. var sceneMeshes = scene.meshes;
  62874. for (var index = 0; index < sceneMeshes.length; index++) {
  62875. var mesh = sceneMeshes[index];
  62876. if (this.renderListPredicate(mesh)) {
  62877. this.renderList.push(mesh);
  62878. }
  62879. }
  62880. }
  62881. this.onBeforeBindObservable.notifyObservers(this);
  62882. // Set custom projection.
  62883. // Needs to be before binding to prevent changing the aspect ratio.
  62884. var camera;
  62885. if (this.activeCamera) {
  62886. camera = this.activeCamera;
  62887. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62888. if (this.activeCamera !== scene.activeCamera) {
  62889. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62890. }
  62891. }
  62892. else {
  62893. camera = scene.activeCamera;
  62894. if (camera) {
  62895. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62896. }
  62897. }
  62898. // Prepare renderingManager
  62899. this._renderingManager.reset();
  62900. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62901. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62902. var sceneRenderId = scene.getRenderId();
  62903. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62904. var mesh = currentRenderList[meshIndex];
  62905. if (mesh) {
  62906. if (!mesh.isReady(this.refreshRate === 0)) {
  62907. this.resetRefreshCounter();
  62908. continue;
  62909. }
  62910. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62911. var isMasked = void 0;
  62912. if (!this.renderList && camera) {
  62913. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62914. }
  62915. else {
  62916. isMasked = false;
  62917. }
  62918. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62919. mesh._activate(sceneRenderId);
  62920. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62921. var subMesh = mesh.subMeshes[subIndex];
  62922. scene._activeIndices.addCount(subMesh.indexCount, false);
  62923. this._renderingManager.dispatch(subMesh, mesh);
  62924. }
  62925. }
  62926. }
  62927. }
  62928. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62929. var particleSystem = scene.particleSystems[particleIndex];
  62930. var emitter = particleSystem.emitter;
  62931. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62932. continue;
  62933. }
  62934. if (currentRenderList.indexOf(emitter) >= 0) {
  62935. this._renderingManager.dispatchParticles(particleSystem);
  62936. }
  62937. }
  62938. if (this.isCube) {
  62939. for (var face = 0; face < 6; face++) {
  62940. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62941. scene.incrementRenderId();
  62942. scene.resetCachedMaterial();
  62943. }
  62944. }
  62945. else {
  62946. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62947. }
  62948. this.onAfterUnbindObservable.notifyObservers(this);
  62949. if (scene.activeCamera) {
  62950. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62951. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62952. }
  62953. engine.setViewport(scene.activeCamera.viewport);
  62954. }
  62955. scene.resetCachedMaterial();
  62956. };
  62957. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62958. var minimum = 128;
  62959. var x = renderDimension * scale;
  62960. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62961. // Ensure we don't exceed the render dimension (while staying POT)
  62962. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62963. };
  62964. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62965. var _this = this;
  62966. if (!this._texture) {
  62967. return;
  62968. }
  62969. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62970. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62971. });
  62972. };
  62973. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62974. var scene = this.getScene();
  62975. if (!scene) {
  62976. return;
  62977. }
  62978. var engine = scene.getEngine();
  62979. if (!this._texture) {
  62980. return;
  62981. }
  62982. // Bind
  62983. if (this._postProcessManager) {
  62984. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62985. }
  62986. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62987. if (this._texture) {
  62988. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62989. }
  62990. }
  62991. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62992. // Clear
  62993. if (this.onClearObservable.hasObservers()) {
  62994. this.onClearObservable.notifyObservers(engine);
  62995. }
  62996. else {
  62997. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62998. }
  62999. if (!this._doNotChangeAspectRatio) {
  63000. scene.updateTransformMatrix(true);
  63001. }
  63002. // Render
  63003. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63004. if (this._postProcessManager) {
  63005. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63006. }
  63007. else if (useCameraPostProcess) {
  63008. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63009. }
  63010. if (!this._doNotChangeAspectRatio) {
  63011. scene.updateTransformMatrix(true);
  63012. }
  63013. // Dump ?
  63014. if (dumpForDebug) {
  63015. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63016. }
  63017. // Unbind
  63018. if (!this.isCube || faceIndex === 5) {
  63019. if (this.isCube) {
  63020. if (faceIndex === 5) {
  63021. engine.generateMipMapsForCubemap(this._texture);
  63022. }
  63023. }
  63024. this.unbindFrameBuffer(engine, faceIndex);
  63025. }
  63026. else {
  63027. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63028. }
  63029. };
  63030. /**
  63031. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63032. * This allowed control for front to back rendering or reversly depending of the special needs.
  63033. *
  63034. * @param renderingGroupId The rendering group id corresponding to its index
  63035. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63036. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63037. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63038. */
  63039. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63040. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63041. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63042. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63043. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63044. };
  63045. /**
  63046. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63047. *
  63048. * @param renderingGroupId The rendering group id corresponding to its index
  63049. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63050. */
  63051. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63052. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63053. };
  63054. RenderTargetTexture.prototype.clone = function () {
  63055. var textureSize = this.getSize();
  63056. 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);
  63057. // Base texture
  63058. newTexture.hasAlpha = this.hasAlpha;
  63059. newTexture.level = this.level;
  63060. // RenderTarget Texture
  63061. newTexture.coordinatesMode = this.coordinatesMode;
  63062. if (this.renderList) {
  63063. newTexture.renderList = this.renderList.slice(0);
  63064. }
  63065. return newTexture;
  63066. };
  63067. RenderTargetTexture.prototype.serialize = function () {
  63068. if (!this.name) {
  63069. return null;
  63070. }
  63071. var serializationObject = _super.prototype.serialize.call(this);
  63072. serializationObject.renderTargetSize = this.getRenderSize();
  63073. serializationObject.renderList = [];
  63074. if (this.renderList) {
  63075. for (var index = 0; index < this.renderList.length; index++) {
  63076. serializationObject.renderList.push(this.renderList[index].id);
  63077. }
  63078. }
  63079. return serializationObject;
  63080. };
  63081. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63082. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63083. var objBuffer = this.getInternalTexture();
  63084. var scene = this.getScene();
  63085. if (objBuffer && scene) {
  63086. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63087. }
  63088. };
  63089. RenderTargetTexture.prototype.dispose = function () {
  63090. if (this._postProcessManager) {
  63091. this._postProcessManager.dispose();
  63092. this._postProcessManager = null;
  63093. }
  63094. this.clearPostProcesses(true);
  63095. if (this._resizeObserver) {
  63096. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63097. this._resizeObserver = null;
  63098. }
  63099. this.renderList = null;
  63100. // Remove from custom render targets
  63101. var scene = this.getScene();
  63102. if (!scene) {
  63103. return;
  63104. }
  63105. var index = scene.customRenderTargets.indexOf(this);
  63106. if (index >= 0) {
  63107. scene.customRenderTargets.splice(index, 1);
  63108. }
  63109. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63110. var camera = _a[_i];
  63111. index = camera.customRenderTargets.indexOf(this);
  63112. if (index >= 0) {
  63113. camera.customRenderTargets.splice(index, 1);
  63114. }
  63115. }
  63116. _super.prototype.dispose.call(this);
  63117. };
  63118. RenderTargetTexture.prototype._rebuild = function () {
  63119. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63120. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63121. }
  63122. if (this._postProcessManager) {
  63123. this._postProcessManager._rebuild();
  63124. }
  63125. };
  63126. /**
  63127. * Clear the info related to rendering groups preventing retention point in material dispose.
  63128. */
  63129. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63130. if (this._renderingManager) {
  63131. this._renderingManager.freeRenderingGroups();
  63132. }
  63133. };
  63134. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63135. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63136. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63137. return RenderTargetTexture;
  63138. }(BABYLON.Texture));
  63139. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63140. })(BABYLON || (BABYLON = {}));
  63141. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63142. var BABYLON;
  63143. (function (BABYLON) {
  63144. ;
  63145. var MultiRenderTarget = /** @class */ (function (_super) {
  63146. __extends(MultiRenderTarget, _super);
  63147. function MultiRenderTarget(name, size, count, scene, options) {
  63148. var _this = this;
  63149. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63150. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63151. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63152. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63153. _this._engine = scene.getEngine();
  63154. if (!_this.isSupported) {
  63155. _this.dispose();
  63156. return;
  63157. }
  63158. var types = [];
  63159. var samplingModes = [];
  63160. for (var i = 0; i < count; i++) {
  63161. if (options && options.types && options.types[i] !== undefined) {
  63162. types.push(options.types[i]);
  63163. }
  63164. else {
  63165. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63166. }
  63167. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63168. samplingModes.push(options.samplingModes[i]);
  63169. }
  63170. else {
  63171. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63172. }
  63173. }
  63174. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63175. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63176. _this._size = size;
  63177. _this._multiRenderTargetOptions = {
  63178. samplingModes: samplingModes,
  63179. generateMipMaps: generateMipMaps,
  63180. generateDepthBuffer: generateDepthBuffer,
  63181. generateStencilBuffer: generateStencilBuffer,
  63182. generateDepthTexture: generateDepthTexture,
  63183. types: types,
  63184. textureCount: count
  63185. };
  63186. _this._createInternalTextures();
  63187. _this._createTextures();
  63188. return _this;
  63189. }
  63190. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63191. get: function () {
  63192. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63193. },
  63194. enumerable: true,
  63195. configurable: true
  63196. });
  63197. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63198. get: function () {
  63199. return this._textures;
  63200. },
  63201. enumerable: true,
  63202. configurable: true
  63203. });
  63204. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63205. get: function () {
  63206. return this._textures[this._textures.length - 1];
  63207. },
  63208. enumerable: true,
  63209. configurable: true
  63210. });
  63211. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63212. set: function (wrap) {
  63213. if (this._textures) {
  63214. for (var i = 0; i < this._textures.length; i++) {
  63215. this._textures[i].wrapU = wrap;
  63216. }
  63217. }
  63218. },
  63219. enumerable: true,
  63220. configurable: true
  63221. });
  63222. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63223. set: function (wrap) {
  63224. if (this._textures) {
  63225. for (var i = 0; i < this._textures.length; i++) {
  63226. this._textures[i].wrapV = wrap;
  63227. }
  63228. }
  63229. },
  63230. enumerable: true,
  63231. configurable: true
  63232. });
  63233. MultiRenderTarget.prototype._rebuild = function () {
  63234. this.releaseInternalTextures();
  63235. this._createInternalTextures();
  63236. for (var i = 0; i < this._internalTextures.length; i++) {
  63237. var texture = this._textures[i];
  63238. texture._texture = this._internalTextures[i];
  63239. }
  63240. // Keeps references to frame buffer and stencil/depth buffer
  63241. this._texture = this._internalTextures[0];
  63242. };
  63243. MultiRenderTarget.prototype._createInternalTextures = function () {
  63244. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63245. };
  63246. MultiRenderTarget.prototype._createTextures = function () {
  63247. this._textures = [];
  63248. for (var i = 0; i < this._internalTextures.length; i++) {
  63249. var texture = new BABYLON.Texture(null, this.getScene());
  63250. texture._texture = this._internalTextures[i];
  63251. this._textures.push(texture);
  63252. }
  63253. // Keeps references to frame buffer and stencil/depth buffer
  63254. this._texture = this._internalTextures[0];
  63255. };
  63256. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63257. get: function () {
  63258. return this._samples;
  63259. },
  63260. set: function (value) {
  63261. if (this._samples === value) {
  63262. return;
  63263. }
  63264. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63265. },
  63266. enumerable: true,
  63267. configurable: true
  63268. });
  63269. MultiRenderTarget.prototype.resize = function (size) {
  63270. this.releaseInternalTextures();
  63271. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63272. this._createInternalTextures();
  63273. };
  63274. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63275. var _this = this;
  63276. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63277. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63278. });
  63279. };
  63280. MultiRenderTarget.prototype.dispose = function () {
  63281. this.releaseInternalTextures();
  63282. _super.prototype.dispose.call(this);
  63283. };
  63284. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63285. if (!this._internalTextures) {
  63286. return;
  63287. }
  63288. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63289. if (this._internalTextures[i] !== undefined) {
  63290. this._internalTextures[i].dispose();
  63291. this._internalTextures.splice(i, 1);
  63292. }
  63293. }
  63294. };
  63295. return MultiRenderTarget;
  63296. }(BABYLON.RenderTargetTexture));
  63297. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63298. })(BABYLON || (BABYLON = {}));
  63299. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63300. var BABYLON;
  63301. (function (BABYLON) {
  63302. var MirrorTexture = /** @class */ (function (_super) {
  63303. __extends(MirrorTexture, _super);
  63304. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63305. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63307. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63308. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63309. _this.scene = scene;
  63310. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63311. _this._transformMatrix = BABYLON.Matrix.Zero();
  63312. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63313. _this._adaptiveBlurKernel = 0;
  63314. _this._blurKernelX = 0;
  63315. _this._blurKernelY = 0;
  63316. _this._blurRatio = 1.0;
  63317. _this.ignoreCameraViewport = true;
  63318. _this._updateGammaSpace();
  63319. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63320. _this._updateGammaSpace;
  63321. });
  63322. _this.onBeforeRenderObservable.add(function () {
  63323. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63324. _this._savedViewMatrix = scene.getViewMatrix();
  63325. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63326. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63327. scene.clipPlane = _this.mirrorPlane;
  63328. scene.getEngine().cullBackFaces = false;
  63329. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63330. });
  63331. _this.onAfterRenderObservable.add(function () {
  63332. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63333. scene.getEngine().cullBackFaces = true;
  63334. scene._mirroredCameraPosition = null;
  63335. delete scene.clipPlane;
  63336. });
  63337. return _this;
  63338. }
  63339. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63340. get: function () {
  63341. return this._blurRatio;
  63342. },
  63343. set: function (value) {
  63344. if (this._blurRatio === value) {
  63345. return;
  63346. }
  63347. this._blurRatio = value;
  63348. this._preparePostProcesses();
  63349. },
  63350. enumerable: true,
  63351. configurable: true
  63352. });
  63353. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63354. set: function (value) {
  63355. this._adaptiveBlurKernel = value;
  63356. this._autoComputeBlurKernel();
  63357. },
  63358. enumerable: true,
  63359. configurable: true
  63360. });
  63361. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63362. set: function (value) {
  63363. this.blurKernelX = value;
  63364. this.blurKernelY = value;
  63365. },
  63366. enumerable: true,
  63367. configurable: true
  63368. });
  63369. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63370. get: function () {
  63371. return this._blurKernelX;
  63372. },
  63373. set: function (value) {
  63374. if (this._blurKernelX === value) {
  63375. return;
  63376. }
  63377. this._blurKernelX = value;
  63378. this._preparePostProcesses();
  63379. },
  63380. enumerable: true,
  63381. configurable: true
  63382. });
  63383. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63384. get: function () {
  63385. return this._blurKernelY;
  63386. },
  63387. set: function (value) {
  63388. if (this._blurKernelY === value) {
  63389. return;
  63390. }
  63391. this._blurKernelY = value;
  63392. this._preparePostProcesses();
  63393. },
  63394. enumerable: true,
  63395. configurable: true
  63396. });
  63397. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63398. var engine = this.getScene().getEngine();
  63399. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63400. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63401. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63402. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63403. };
  63404. MirrorTexture.prototype._onRatioRescale = function () {
  63405. if (this._sizeRatio) {
  63406. this.resize(this._initialSizeParameter);
  63407. if (!this._adaptiveBlurKernel) {
  63408. this._preparePostProcesses();
  63409. }
  63410. }
  63411. if (this._adaptiveBlurKernel) {
  63412. this._autoComputeBlurKernel();
  63413. }
  63414. };
  63415. MirrorTexture.prototype._updateGammaSpace = function () {
  63416. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63417. };
  63418. MirrorTexture.prototype._preparePostProcesses = function () {
  63419. this.clearPostProcesses(true);
  63420. if (this._blurKernelX && this._blurKernelY) {
  63421. var engine = this.getScene().getEngine();
  63422. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63423. 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);
  63424. this._blurX.autoClear = false;
  63425. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63426. this._blurX.inputTexture = this._texture;
  63427. }
  63428. else {
  63429. this._blurX.alwaysForcePOT = true;
  63430. }
  63431. 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);
  63432. this._blurY.autoClear = false;
  63433. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63434. this.addPostProcess(this._blurX);
  63435. this.addPostProcess(this._blurY);
  63436. }
  63437. else {
  63438. if (this._blurY) {
  63439. this.removePostProcess(this._blurY);
  63440. this._blurY.dispose();
  63441. this._blurY = null;
  63442. }
  63443. if (this._blurX) {
  63444. this.removePostProcess(this._blurX);
  63445. this._blurX.dispose();
  63446. this._blurX = null;
  63447. }
  63448. }
  63449. };
  63450. MirrorTexture.prototype.clone = function () {
  63451. var scene = this.getScene();
  63452. if (!scene) {
  63453. return this;
  63454. }
  63455. var textureSize = this.getSize();
  63456. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63457. // Base texture
  63458. newTexture.hasAlpha = this.hasAlpha;
  63459. newTexture.level = this.level;
  63460. // Mirror Texture
  63461. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63462. if (this.renderList) {
  63463. newTexture.renderList = this.renderList.slice(0);
  63464. }
  63465. return newTexture;
  63466. };
  63467. MirrorTexture.prototype.serialize = function () {
  63468. if (!this.name) {
  63469. return null;
  63470. }
  63471. var serializationObject = _super.prototype.serialize.call(this);
  63472. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63473. return serializationObject;
  63474. };
  63475. MirrorTexture.prototype.dispose = function () {
  63476. _super.prototype.dispose.call(this);
  63477. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63478. };
  63479. return MirrorTexture;
  63480. }(BABYLON.RenderTargetTexture));
  63481. BABYLON.MirrorTexture = MirrorTexture;
  63482. })(BABYLON || (BABYLON = {}));
  63483. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63484. var BABYLON;
  63485. (function (BABYLON) {
  63486. /**
  63487. * Creates a refraction texture used by refraction channel of the standard material.
  63488. * @param name the texture name
  63489. * @param size size of the underlying texture
  63490. * @param scene root scene
  63491. */
  63492. var RefractionTexture = /** @class */ (function (_super) {
  63493. __extends(RefractionTexture, _super);
  63494. function RefractionTexture(name, size, scene, generateMipMaps) {
  63495. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63496. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63497. _this.depth = 2.0;
  63498. _this.onBeforeRenderObservable.add(function () {
  63499. scene.clipPlane = _this.refractionPlane;
  63500. });
  63501. _this.onAfterRenderObservable.add(function () {
  63502. delete scene.clipPlane;
  63503. });
  63504. return _this;
  63505. }
  63506. RefractionTexture.prototype.clone = function () {
  63507. var scene = this.getScene();
  63508. if (!scene) {
  63509. return this;
  63510. }
  63511. var textureSize = this.getSize();
  63512. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63513. // Base texture
  63514. newTexture.hasAlpha = this.hasAlpha;
  63515. newTexture.level = this.level;
  63516. // Refraction Texture
  63517. newTexture.refractionPlane = this.refractionPlane.clone();
  63518. if (this.renderList) {
  63519. newTexture.renderList = this.renderList.slice(0);
  63520. }
  63521. newTexture.depth = this.depth;
  63522. return newTexture;
  63523. };
  63524. RefractionTexture.prototype.serialize = function () {
  63525. if (!this.name) {
  63526. return null;
  63527. }
  63528. var serializationObject = _super.prototype.serialize.call(this);
  63529. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63530. serializationObject.depth = this.depth;
  63531. return serializationObject;
  63532. };
  63533. return RefractionTexture;
  63534. }(BABYLON.RenderTargetTexture));
  63535. BABYLON.RefractionTexture = RefractionTexture;
  63536. })(BABYLON || (BABYLON = {}));
  63537. //# sourceMappingURL=babylon.refractionTexture.js.map
  63538. var BABYLON;
  63539. (function (BABYLON) {
  63540. /**
  63541. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63542. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63543. */
  63544. var DynamicTexture = /** @class */ (function (_super) {
  63545. __extends(DynamicTexture, _super);
  63546. /**
  63547. * Creates a {BABYLON.DynamicTexture}
  63548. * @param name defines the name of the texture
  63549. * @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
  63550. * @param scene defines the scene where you want the texture
  63551. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63552. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63553. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63554. */
  63555. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63556. if (scene === void 0) { scene = null; }
  63557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63558. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63559. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63560. _this.name = name;
  63561. _this._engine = _this.getScene().getEngine();
  63562. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63563. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63564. _this._generateMipMaps = generateMipMaps;
  63565. if (options.getContext) {
  63566. _this._canvas = options;
  63567. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63568. }
  63569. else {
  63570. _this._canvas = document.createElement("canvas");
  63571. if (options.width || options.width === 0) {
  63572. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63573. }
  63574. else {
  63575. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63576. }
  63577. }
  63578. var textureSize = _this.getSize();
  63579. _this._canvas.width = textureSize.width;
  63580. _this._canvas.height = textureSize.height;
  63581. _this._context = _this._canvas.getContext("2d");
  63582. return _this;
  63583. }
  63584. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63585. /**
  63586. * Gets the current state of canRescale
  63587. */
  63588. get: function () {
  63589. return true;
  63590. },
  63591. enumerable: true,
  63592. configurable: true
  63593. });
  63594. DynamicTexture.prototype._recreate = function (textureSize) {
  63595. this._canvas.width = textureSize.width;
  63596. this._canvas.height = textureSize.height;
  63597. this.releaseInternalTexture();
  63598. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63599. };
  63600. /**
  63601. * Scales the texture
  63602. * @param ratio the scale factor to apply to both width and height
  63603. */
  63604. DynamicTexture.prototype.scale = function (ratio) {
  63605. var textureSize = this.getSize();
  63606. textureSize.width *= ratio;
  63607. textureSize.height *= ratio;
  63608. this._recreate(textureSize);
  63609. };
  63610. /**
  63611. * Resizes the texture
  63612. * @param width the new width
  63613. * @param height the new height
  63614. */
  63615. DynamicTexture.prototype.scaleTo = function (width, height) {
  63616. var textureSize = this.getSize();
  63617. textureSize.width = width;
  63618. textureSize.height = height;
  63619. this._recreate(textureSize);
  63620. };
  63621. /**
  63622. * Gets the context of the canvas used by the texture
  63623. * @returns the canvas context of the dynamic texture
  63624. */
  63625. DynamicTexture.prototype.getContext = function () {
  63626. return this._context;
  63627. };
  63628. /**
  63629. * Clears the texture
  63630. */
  63631. DynamicTexture.prototype.clear = function () {
  63632. var size = this.getSize();
  63633. this._context.fillRect(0, 0, size.width, size.height);
  63634. };
  63635. /**
  63636. * Updates the texture
  63637. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63638. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  63639. */
  63640. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  63641. if (premulAlpha === void 0) { premulAlpha = false; }
  63642. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  63643. };
  63644. /**
  63645. * Draws text onto the texture
  63646. * @param text defines the text to be drawn
  63647. * @param x defines the placement of the text from the left
  63648. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63649. * @param font defines the font to be used with font-style, font-size, font-name
  63650. * @param color defines the color used for the text
  63651. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63652. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63653. * @param update defines whether texture is immediately update (default is true)
  63654. */
  63655. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63656. if (update === void 0) { update = true; }
  63657. var size = this.getSize();
  63658. if (clearColor) {
  63659. this._context.fillStyle = clearColor;
  63660. this._context.fillRect(0, 0, size.width, size.height);
  63661. }
  63662. this._context.font = font;
  63663. if (x === null || x === undefined) {
  63664. var textSize = this._context.measureText(text);
  63665. x = (size.width - textSize.width) / 2;
  63666. }
  63667. if (y === null || y === undefined) {
  63668. var fontSize = parseInt((font.replace(/\D/g, '')));
  63669. y = (size.height / 2) + (fontSize / 3.65);
  63670. }
  63671. this._context.fillStyle = color;
  63672. this._context.fillText(text, x, y);
  63673. if (update) {
  63674. this.update(invertY);
  63675. }
  63676. };
  63677. /**
  63678. * Clones the texture
  63679. * @returns the clone of the texture.
  63680. */
  63681. DynamicTexture.prototype.clone = function () {
  63682. var scene = this.getScene();
  63683. if (!scene) {
  63684. return this;
  63685. }
  63686. var textureSize = this.getSize();
  63687. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63688. // Base texture
  63689. newTexture.hasAlpha = this.hasAlpha;
  63690. newTexture.level = this.level;
  63691. // Dynamic Texture
  63692. newTexture.wrapU = this.wrapU;
  63693. newTexture.wrapV = this.wrapV;
  63694. return newTexture;
  63695. };
  63696. /** @hidden */
  63697. DynamicTexture.prototype._rebuild = function () {
  63698. this.update();
  63699. };
  63700. return DynamicTexture;
  63701. }(BABYLON.Texture));
  63702. BABYLON.DynamicTexture = DynamicTexture;
  63703. })(BABYLON || (BABYLON = {}));
  63704. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63705. var BABYLON;
  63706. (function (BABYLON) {
  63707. var VideoTexture = /** @class */ (function (_super) {
  63708. __extends(VideoTexture, _super);
  63709. /**
  63710. * Creates a video texture.
  63711. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63712. * @param {string | null} name optional name, will detect from video source, if not defined
  63713. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63714. * @param {BABYLON.Scene} scene is obviously the current scene.
  63715. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63716. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63717. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63718. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63719. */
  63720. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63721. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63722. if (invertY === void 0) { invertY = false; }
  63723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63724. if (settings === void 0) { settings = {
  63725. autoPlay: true,
  63726. loop: true,
  63727. autoUpdateTexture: true,
  63728. }; }
  63729. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63730. _this._stillImageCaptured = false;
  63731. _this._createInternalTexture = function () {
  63732. if (_this._texture != null) {
  63733. return;
  63734. }
  63735. if (!_this._engine.needPOTTextures ||
  63736. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63737. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63738. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63739. }
  63740. else {
  63741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63743. _this._generateMipMaps = false;
  63744. }
  63745. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63746. if (!_this.video.autoplay) {
  63747. var oldHandler_1 = _this.video.onplaying;
  63748. _this.video.onplaying = function () {
  63749. _this.video.onplaying = oldHandler_1;
  63750. _this._texture.isReady = true;
  63751. _this._updateInternalTexture();
  63752. _this.video.pause();
  63753. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63754. _this.onLoadObservable.notifyObservers(_this);
  63755. }
  63756. };
  63757. _this.video.play();
  63758. }
  63759. else {
  63760. _this._texture.isReady = true;
  63761. _this._updateInternalTexture();
  63762. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63763. _this.onLoadObservable.notifyObservers(_this);
  63764. }
  63765. }
  63766. };
  63767. _this.reset = function () {
  63768. if (_this._texture == null) {
  63769. return;
  63770. }
  63771. _this._texture.dispose();
  63772. _this._texture = null;
  63773. };
  63774. _this._updateInternalTexture = function (e) {
  63775. if (_this._texture == null || !_this._texture.isReady) {
  63776. return;
  63777. }
  63778. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63779. return;
  63780. }
  63781. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63782. };
  63783. _this._engine = _this.getScene().getEngine();
  63784. _this._generateMipMaps = generateMipMaps;
  63785. _this._samplingMode = samplingMode;
  63786. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63787. _this.name = name || _this._getName(src);
  63788. _this.video = _this._getVideo(src);
  63789. if (settings.autoPlay !== undefined) {
  63790. _this.video.autoplay = settings.autoPlay;
  63791. }
  63792. if (settings.loop !== undefined) {
  63793. _this.video.loop = settings.loop;
  63794. }
  63795. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63796. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63797. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63798. _this.video.addEventListener("emptied", _this.reset);
  63799. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63800. _this._createInternalTexture();
  63801. }
  63802. return _this;
  63803. }
  63804. VideoTexture.prototype._getName = function (src) {
  63805. if (src instanceof HTMLVideoElement) {
  63806. return src.currentSrc;
  63807. }
  63808. if (typeof src === "object") {
  63809. return src.toString();
  63810. }
  63811. return src;
  63812. };
  63813. ;
  63814. VideoTexture.prototype._getVideo = function (src) {
  63815. if (src instanceof HTMLVideoElement) {
  63816. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63817. return src;
  63818. }
  63819. var video = document.createElement("video");
  63820. if (typeof src === "string") {
  63821. BABYLON.Tools.SetCorsBehavior(src, video);
  63822. video.src = src;
  63823. }
  63824. else {
  63825. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63826. src.forEach(function (url) {
  63827. var source = document.createElement("source");
  63828. source.src = url;
  63829. video.appendChild(source);
  63830. });
  63831. }
  63832. return video;
  63833. };
  63834. ;
  63835. /**
  63836. * Internal method to initiate `update`.
  63837. */
  63838. VideoTexture.prototype._rebuild = function () {
  63839. this.update();
  63840. };
  63841. /**
  63842. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63843. */
  63844. VideoTexture.prototype.update = function () {
  63845. if (!this.autoUpdateTexture) {
  63846. // Expecting user to call `updateTexture` manually
  63847. return;
  63848. }
  63849. this.updateTexture(true);
  63850. };
  63851. /**
  63852. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63853. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63854. */
  63855. VideoTexture.prototype.updateTexture = function (isVisible) {
  63856. if (!isVisible) {
  63857. return;
  63858. }
  63859. if (this.video.paused && this._stillImageCaptured) {
  63860. return;
  63861. }
  63862. this._stillImageCaptured = true;
  63863. this._updateInternalTexture();
  63864. };
  63865. /**
  63866. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63867. * @param url New url.
  63868. */
  63869. VideoTexture.prototype.updateURL = function (url) {
  63870. this.video.src = url;
  63871. };
  63872. VideoTexture.prototype.dispose = function () {
  63873. _super.prototype.dispose.call(this);
  63874. this.video.removeEventListener("canplay", this._createInternalTexture);
  63875. this.video.removeEventListener("paused", this._updateInternalTexture);
  63876. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63877. this.video.removeEventListener("emptied", this.reset);
  63878. this.video.pause();
  63879. };
  63880. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63881. var video = document.createElement("video");
  63882. var constraintsDeviceId;
  63883. if (constraints && constraints.deviceId) {
  63884. constraintsDeviceId = {
  63885. exact: constraints.deviceId,
  63886. };
  63887. }
  63888. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63889. if (navigator.mediaDevices) {
  63890. navigator.mediaDevices.getUserMedia({ video: constraints })
  63891. .then(function (stream) {
  63892. if (video.mozSrcObject !== undefined) {
  63893. // hack for Firefox < 19
  63894. video.mozSrcObject = stream;
  63895. }
  63896. else {
  63897. video.srcObject = stream;
  63898. }
  63899. var onPlaying = function () {
  63900. if (onReady) {
  63901. onReady(new VideoTexture("video", video, scene, true, true));
  63902. }
  63903. video.removeEventListener("playing", onPlaying);
  63904. };
  63905. video.addEventListener("playing", onPlaying);
  63906. video.play();
  63907. })
  63908. .catch(function (err) {
  63909. BABYLON.Tools.Error(err.name);
  63910. });
  63911. }
  63912. else {
  63913. navigator.getUserMedia =
  63914. navigator.getUserMedia ||
  63915. navigator.webkitGetUserMedia ||
  63916. navigator.mozGetUserMedia ||
  63917. navigator.msGetUserMedia;
  63918. if (navigator.getUserMedia) {
  63919. navigator.getUserMedia({
  63920. video: {
  63921. deviceId: constraintsDeviceId,
  63922. width: {
  63923. min: (constraints && constraints.minWidth) || 256,
  63924. max: (constraints && constraints.maxWidth) || 640,
  63925. },
  63926. height: {
  63927. min: (constraints && constraints.minHeight) || 256,
  63928. max: (constraints && constraints.maxHeight) || 480,
  63929. },
  63930. },
  63931. }, function (stream) {
  63932. if (video.mozSrcObject !== undefined) {
  63933. // hack for Firefox < 19
  63934. video.mozSrcObject = stream;
  63935. }
  63936. else {
  63937. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63938. }
  63939. video.play();
  63940. if (onReady) {
  63941. onReady(new VideoTexture("video", video, scene, true, true));
  63942. }
  63943. }, function (e) {
  63944. BABYLON.Tools.Error(e.name);
  63945. });
  63946. }
  63947. }
  63948. };
  63949. return VideoTexture;
  63950. }(BABYLON.Texture));
  63951. BABYLON.VideoTexture = VideoTexture;
  63952. })(BABYLON || (BABYLON = {}));
  63953. //# sourceMappingURL=babylon.videoTexture.js.map
  63954. var BABYLON;
  63955. (function (BABYLON) {
  63956. var RawTexture = /** @class */ (function (_super) {
  63957. __extends(RawTexture, _super);
  63958. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63959. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63960. if (invertY === void 0) { invertY = false; }
  63961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63962. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63963. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63964. _this.format = format;
  63965. _this._engine = scene.getEngine();
  63966. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63967. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63968. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63969. return _this;
  63970. }
  63971. RawTexture.prototype.update = function (data) {
  63972. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63973. };
  63974. // Statics
  63975. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63976. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63977. if (invertY === void 0) { invertY = false; }
  63978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63979. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63980. };
  63981. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63983. if (invertY === void 0) { invertY = false; }
  63984. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63985. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63986. };
  63987. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63988. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63989. if (invertY === void 0) { invertY = false; }
  63990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63991. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63992. };
  63993. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63994. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63995. if (invertY === void 0) { invertY = false; }
  63996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63997. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63998. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63999. };
  64000. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64001. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64002. if (invertY === void 0) { invertY = false; }
  64003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64004. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64005. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64006. };
  64007. return RawTexture;
  64008. }(BABYLON.Texture));
  64009. BABYLON.RawTexture = RawTexture;
  64010. })(BABYLON || (BABYLON = {}));
  64011. //# sourceMappingURL=babylon.rawTexture.js.map
  64012. var BABYLON;
  64013. (function (BABYLON) {
  64014. /**
  64015. * Class used to store 3D textures containing user data
  64016. */
  64017. var RawTexture3D = /** @class */ (function (_super) {
  64018. __extends(RawTexture3D, _super);
  64019. /**
  64020. * Create a new RawTexture3D
  64021. * @param data defines the data of the texture
  64022. * @param width defines the width of the texture
  64023. * @param height defines the height of the texture
  64024. * @param depth defines the depth of the texture
  64025. * @param format defines the texture format to use
  64026. * @param scene defines the hosting scene
  64027. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64028. * @param invertY defines if texture must be stored with Y axis inverted
  64029. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64030. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64031. */
  64032. function RawTexture3D(data, width, height, depth,
  64033. /** Gets or sets the texture format to use */
  64034. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64036. if (invertY === void 0) { invertY = false; }
  64037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64038. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64039. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64040. _this.format = format;
  64041. _this._engine = scene.getEngine();
  64042. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64043. _this.is3D = true;
  64044. return _this;
  64045. }
  64046. /**
  64047. * Update the texture with new data
  64048. * @param data defines the data to store in the texture
  64049. */
  64050. RawTexture3D.prototype.update = function (data) {
  64051. if (!this._texture) {
  64052. return;
  64053. }
  64054. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64055. };
  64056. return RawTexture3D;
  64057. }(BABYLON.Texture));
  64058. BABYLON.RawTexture3D = RawTexture3D;
  64059. })(BABYLON || (BABYLON = {}));
  64060. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64061. var BABYLON;
  64062. (function (BABYLON) {
  64063. /**
  64064. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64065. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64066. */
  64067. var PostProcessManager = /** @class */ (function () {
  64068. /**
  64069. * Creates a new instance PostProcess
  64070. * @param scene The scene that the post process is associated with.
  64071. */
  64072. function PostProcessManager(scene) {
  64073. this._vertexBuffers = {};
  64074. this._scene = scene;
  64075. }
  64076. PostProcessManager.prototype._prepareBuffers = function () {
  64077. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64078. return;
  64079. }
  64080. // VBO
  64081. var vertices = [];
  64082. vertices.push(1, 1);
  64083. vertices.push(-1, 1);
  64084. vertices.push(-1, -1);
  64085. vertices.push(1, -1);
  64086. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64087. this._buildIndexBuffer();
  64088. };
  64089. PostProcessManager.prototype._buildIndexBuffer = function () {
  64090. // Indices
  64091. var indices = [];
  64092. indices.push(0);
  64093. indices.push(1);
  64094. indices.push(2);
  64095. indices.push(0);
  64096. indices.push(2);
  64097. indices.push(3);
  64098. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64099. };
  64100. /**
  64101. * Rebuilds the vertex buffers of the manager.
  64102. */
  64103. PostProcessManager.prototype._rebuild = function () {
  64104. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64105. if (!vb) {
  64106. return;
  64107. }
  64108. vb._rebuild();
  64109. this._buildIndexBuffer();
  64110. };
  64111. // Methods
  64112. /**
  64113. * Prepares a frame to be run through a post process.
  64114. * @param sourceTexture The input texture to the post procesess. (default: null)
  64115. * @param postProcesses An array of post processes to be run. (default: null)
  64116. * @returns True if the post processes were able to be run.
  64117. */
  64118. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64119. if (sourceTexture === void 0) { sourceTexture = null; }
  64120. if (postProcesses === void 0) { postProcesses = null; }
  64121. var camera = this._scene.activeCamera;
  64122. if (!camera) {
  64123. return false;
  64124. }
  64125. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64126. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64127. return false;
  64128. }
  64129. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64130. return true;
  64131. };
  64132. /**
  64133. * Manually render a set of post processes to a texture.
  64134. * @param postProcesses An array of post processes to be run.
  64135. * @param targetTexture The target texture to render to.
  64136. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64137. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64138. * @param lodLevel defines which lod of the texture to render to
  64139. */
  64140. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64141. if (targetTexture === void 0) { targetTexture = null; }
  64142. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64143. if (faceIndex === void 0) { faceIndex = 0; }
  64144. if (lodLevel === void 0) { lodLevel = 0; }
  64145. var engine = this._scene.getEngine();
  64146. for (var index = 0; index < postProcesses.length; index++) {
  64147. if (index < postProcesses.length - 1) {
  64148. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64149. }
  64150. else {
  64151. if (targetTexture) {
  64152. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64153. }
  64154. else {
  64155. engine.restoreDefaultFramebuffer();
  64156. }
  64157. }
  64158. var pp = postProcesses[index];
  64159. var effect = pp.apply();
  64160. if (effect) {
  64161. pp.onBeforeRenderObservable.notifyObservers(effect);
  64162. // VBOs
  64163. this._prepareBuffers();
  64164. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64165. // Draw order
  64166. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64167. pp.onAfterRenderObservable.notifyObservers(effect);
  64168. }
  64169. }
  64170. // Restore depth buffer
  64171. engine.setDepthBuffer(true);
  64172. engine.setDepthWrite(true);
  64173. };
  64174. /**
  64175. * Finalize the result of the output of the postprocesses.
  64176. * @param doNotPresent If true the result will not be displayed to the screen.
  64177. * @param targetTexture The target texture to render to.
  64178. * @param faceIndex The index of the face to bind the target texture to.
  64179. * @param postProcesses The array of post processes to render.
  64180. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64181. */
  64182. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64183. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64184. var camera = this._scene.activeCamera;
  64185. if (!camera) {
  64186. return;
  64187. }
  64188. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64189. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64190. return;
  64191. }
  64192. var engine = this._scene.getEngine();
  64193. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64194. var pp = postProcesses[index];
  64195. if (index < len - 1) {
  64196. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64197. }
  64198. else {
  64199. if (targetTexture) {
  64200. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64201. pp._outputTexture = targetTexture;
  64202. }
  64203. else {
  64204. engine.restoreDefaultFramebuffer();
  64205. pp._outputTexture = null;
  64206. }
  64207. }
  64208. if (doNotPresent) {
  64209. break;
  64210. }
  64211. var effect = pp.apply();
  64212. if (effect) {
  64213. pp.onBeforeRenderObservable.notifyObservers(effect);
  64214. // VBOs
  64215. this._prepareBuffers();
  64216. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64217. // Draw order
  64218. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64219. pp.onAfterRenderObservable.notifyObservers(effect);
  64220. }
  64221. }
  64222. // Restore states
  64223. engine.setDepthBuffer(true);
  64224. engine.setDepthWrite(true);
  64225. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64226. };
  64227. /**
  64228. * Disposes of the post process manager.
  64229. */
  64230. PostProcessManager.prototype.dispose = function () {
  64231. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64232. if (buffer) {
  64233. buffer.dispose();
  64234. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64235. }
  64236. if (this._indexBuffer) {
  64237. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64238. this._indexBuffer = null;
  64239. }
  64240. };
  64241. return PostProcessManager;
  64242. }());
  64243. BABYLON.PostProcessManager = PostProcessManager;
  64244. })(BABYLON || (BABYLON = {}));
  64245. //# sourceMappingURL=babylon.postProcessManager.js.map
  64246. var BABYLON;
  64247. (function (BABYLON) {
  64248. /**
  64249. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64250. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64251. */
  64252. var PostProcess = /** @class */ (function () {
  64253. /**
  64254. * Creates a new instance PostProcess
  64255. * @param name The name of the PostProcess.
  64256. * @param fragmentUrl The url of the fragment shader to be used.
  64257. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64258. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64259. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64260. * @param camera The camera to apply the render pass to.
  64261. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64262. * @param engine The engine which the post process will be applied. (default: current engine)
  64263. * @param reusable If the post process can be reused on the same frame. (default: false)
  64264. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64265. * @param textureType Type of textures used when performing the post process. (default: 0)
  64266. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64267. * @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
  64268. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64269. */
  64270. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64272. if (defines === void 0) { defines = null; }
  64273. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64274. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64275. if (blockCompilation === void 0) { blockCompilation = false; }
  64276. this.name = name;
  64277. /**
  64278. * Width of the texture to apply the post process on
  64279. */
  64280. this.width = -1;
  64281. /**
  64282. * Height of the texture to apply the post process on
  64283. */
  64284. this.height = -1;
  64285. /**
  64286. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64287. */
  64288. this._outputTexture = null;
  64289. /**
  64290. * If the buffer needs to be cleared before applying the post process. (default: true)
  64291. * Should be set to false if shader will overwrite all previous pixels.
  64292. */
  64293. this.autoClear = true;
  64294. /**
  64295. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64296. */
  64297. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64298. /**
  64299. * Animations to be used for the post processing
  64300. */
  64301. this.animations = new Array();
  64302. /**
  64303. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64304. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64305. */
  64306. this.enablePixelPerfectMode = false;
  64307. /**
  64308. * Force the postprocess to be applied without taking in account viewport
  64309. */
  64310. this.forceFullscreenViewport = true;
  64311. /**
  64312. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64313. *
  64314. * | Value | Type | Description |
  64315. * | ----- | ----------------------------------- | ----------- |
  64316. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64317. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64318. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64319. *
  64320. */
  64321. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64322. /**
  64323. * Force textures to be a power of two (default: false)
  64324. */
  64325. this.alwaysForcePOT = false;
  64326. /**
  64327. * Number of sample textures (default: 1)
  64328. */
  64329. this.samples = 1;
  64330. /**
  64331. * Modify the scale of the post process to be the same as the viewport (default: false)
  64332. */
  64333. this.adaptScaleToCurrentViewport = false;
  64334. this._reusable = false;
  64335. /**
  64336. * Smart array of input and output textures for the post process.
  64337. */
  64338. this._textures = new BABYLON.SmartArray(2);
  64339. /**
  64340. * The index in _textures that corresponds to the output texture.
  64341. */
  64342. this._currentRenderTextureInd = 0;
  64343. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64344. this._texelSize = BABYLON.Vector2.Zero();
  64345. // Events
  64346. /**
  64347. * An event triggered when the postprocess is activated.
  64348. */
  64349. this.onActivateObservable = new BABYLON.Observable();
  64350. /**
  64351. * An event triggered when the postprocess changes its size.
  64352. */
  64353. this.onSizeChangedObservable = new BABYLON.Observable();
  64354. /**
  64355. * An event triggered when the postprocess applies its effect.
  64356. */
  64357. this.onApplyObservable = new BABYLON.Observable();
  64358. /**
  64359. * An event triggered before rendering the postprocess
  64360. */
  64361. this.onBeforeRenderObservable = new BABYLON.Observable();
  64362. /**
  64363. * An event triggered after rendering the postprocess
  64364. */
  64365. this.onAfterRenderObservable = new BABYLON.Observable();
  64366. if (camera != null) {
  64367. this._camera = camera;
  64368. this._scene = camera.getScene();
  64369. camera.attachPostProcess(this);
  64370. this._engine = this._scene.getEngine();
  64371. this._scene.postProcesses.push(this);
  64372. }
  64373. else if (engine) {
  64374. this._engine = engine;
  64375. this._engine.postProcesses.push(this);
  64376. }
  64377. this._options = options;
  64378. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64379. this._reusable = reusable || false;
  64380. this._textureType = textureType;
  64381. this._samplers = samplers || [];
  64382. this._samplers.push("textureSampler");
  64383. this._fragmentUrl = fragmentUrl;
  64384. this._vertexUrl = vertexUrl;
  64385. this._parameters = parameters || [];
  64386. this._parameters.push("scale");
  64387. this._indexParameters = indexParameters;
  64388. if (!blockCompilation) {
  64389. this.updateEffect(defines);
  64390. }
  64391. }
  64392. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64393. /**
  64394. * A function that is added to the onActivateObservable
  64395. */
  64396. set: function (callback) {
  64397. if (this._onActivateObserver) {
  64398. this.onActivateObservable.remove(this._onActivateObserver);
  64399. }
  64400. if (callback) {
  64401. this._onActivateObserver = this.onActivateObservable.add(callback);
  64402. }
  64403. },
  64404. enumerable: true,
  64405. configurable: true
  64406. });
  64407. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64408. /**
  64409. * A function that is added to the onSizeChangedObservable
  64410. */
  64411. set: function (callback) {
  64412. if (this._onSizeChangedObserver) {
  64413. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64414. }
  64415. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64416. },
  64417. enumerable: true,
  64418. configurable: true
  64419. });
  64420. Object.defineProperty(PostProcess.prototype, "onApply", {
  64421. /**
  64422. * A function that is added to the onApplyObservable
  64423. */
  64424. set: function (callback) {
  64425. if (this._onApplyObserver) {
  64426. this.onApplyObservable.remove(this._onApplyObserver);
  64427. }
  64428. this._onApplyObserver = this.onApplyObservable.add(callback);
  64429. },
  64430. enumerable: true,
  64431. configurable: true
  64432. });
  64433. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64434. /**
  64435. * A function that is added to the onBeforeRenderObservable
  64436. */
  64437. set: function (callback) {
  64438. if (this._onBeforeRenderObserver) {
  64439. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64440. }
  64441. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64447. /**
  64448. * A function that is added to the onAfterRenderObservable
  64449. */
  64450. set: function (callback) {
  64451. if (this._onAfterRenderObserver) {
  64452. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64453. }
  64454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64455. },
  64456. enumerable: true,
  64457. configurable: true
  64458. });
  64459. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64460. /**
  64461. * 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
  64462. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64463. */
  64464. get: function () {
  64465. return this._textures.data[this._currentRenderTextureInd];
  64466. },
  64467. set: function (value) {
  64468. this._forcedOutputTexture = value;
  64469. },
  64470. enumerable: true,
  64471. configurable: true
  64472. });
  64473. /**
  64474. * Gets the camera which post process is applied to.
  64475. * @returns The camera the post process is applied to.
  64476. */
  64477. PostProcess.prototype.getCamera = function () {
  64478. return this._camera;
  64479. };
  64480. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64481. /**
  64482. * Gets the texel size of the postprocess.
  64483. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64484. */
  64485. get: function () {
  64486. if (this._shareOutputWithPostProcess) {
  64487. return this._shareOutputWithPostProcess.texelSize;
  64488. }
  64489. if (this._forcedOutputTexture) {
  64490. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64491. }
  64492. return this._texelSize;
  64493. },
  64494. enumerable: true,
  64495. configurable: true
  64496. });
  64497. /**
  64498. * Gets the engine which this post process belongs to.
  64499. * @returns The engine the post process was enabled with.
  64500. */
  64501. PostProcess.prototype.getEngine = function () {
  64502. return this._engine;
  64503. };
  64504. /**
  64505. * The effect that is created when initializing the post process.
  64506. * @returns The created effect corrisponding the the postprocess.
  64507. */
  64508. PostProcess.prototype.getEffect = function () {
  64509. return this._effect;
  64510. };
  64511. /**
  64512. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64513. * @param postProcess The post process to share the output with.
  64514. * @returns This post process.
  64515. */
  64516. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64517. this._disposeTextures();
  64518. this._shareOutputWithPostProcess = postProcess;
  64519. return this;
  64520. };
  64521. /**
  64522. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64523. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64524. */
  64525. PostProcess.prototype.useOwnOutput = function () {
  64526. if (this._textures.length == 0) {
  64527. this._textures = new BABYLON.SmartArray(2);
  64528. }
  64529. this._shareOutputWithPostProcess = null;
  64530. };
  64531. /**
  64532. * Updates the effect with the current post process compile time values and recompiles the shader.
  64533. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64534. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64535. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64536. * @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
  64537. * @param onCompiled Called when the shader has been compiled.
  64538. * @param onError Called if there is an error when compiling a shader.
  64539. */
  64540. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64541. if (defines === void 0) { defines = null; }
  64542. if (uniforms === void 0) { uniforms = null; }
  64543. if (samplers === void 0) { samplers = null; }
  64544. 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);
  64545. };
  64546. /**
  64547. * The post process is reusable if it can be used multiple times within one frame.
  64548. * @returns If the post process is reusable
  64549. */
  64550. PostProcess.prototype.isReusable = function () {
  64551. return this._reusable;
  64552. };
  64553. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64554. PostProcess.prototype.markTextureDirty = function () {
  64555. this.width = -1;
  64556. };
  64557. /**
  64558. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64559. * 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.
  64560. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64561. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64562. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64563. * @returns The target texture that was bound to be written to.
  64564. */
  64565. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64566. var _this = this;
  64567. if (sourceTexture === void 0) { sourceTexture = null; }
  64568. camera = camera || this._camera;
  64569. var scene = camera.getScene();
  64570. var engine = scene.getEngine();
  64571. var maxSize = engine.getCaps().maxTextureSize;
  64572. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64573. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64574. // 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
  64575. var webVRCamera = camera.parent;
  64576. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64577. requiredWidth /= 2;
  64578. }
  64579. var desiredWidth = (this._options.width || requiredWidth);
  64580. var desiredHeight = this._options.height || requiredHeight;
  64581. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64582. if (this.adaptScaleToCurrentViewport) {
  64583. var currentViewport = engine.currentViewport;
  64584. if (currentViewport) {
  64585. desiredWidth *= currentViewport.width;
  64586. desiredHeight *= currentViewport.height;
  64587. }
  64588. }
  64589. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64590. if (!this._options.width) {
  64591. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64592. }
  64593. if (!this._options.height) {
  64594. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64595. }
  64596. }
  64597. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64598. if (this._textures.length > 0) {
  64599. for (var i = 0; i < this._textures.length; i++) {
  64600. this._engine._releaseTexture(this._textures.data[i]);
  64601. }
  64602. this._textures.reset();
  64603. }
  64604. this.width = desiredWidth;
  64605. this.height = desiredHeight;
  64606. var textureSize = { width: this.width, height: this.height };
  64607. var textureOptions = {
  64608. generateMipMaps: false,
  64609. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64610. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64611. samplingMode: this.renderTargetSamplingMode,
  64612. type: this._textureType
  64613. };
  64614. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64615. if (this._reusable) {
  64616. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64617. }
  64618. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64619. this.onSizeChangedObservable.notifyObservers(this);
  64620. }
  64621. this._textures.forEach(function (texture) {
  64622. if (texture.samples !== _this.samples) {
  64623. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64624. }
  64625. });
  64626. }
  64627. var target;
  64628. if (this._shareOutputWithPostProcess) {
  64629. target = this._shareOutputWithPostProcess.inputTexture;
  64630. }
  64631. else if (this._forcedOutputTexture) {
  64632. target = this._forcedOutputTexture;
  64633. this.width = this._forcedOutputTexture.width;
  64634. this.height = this._forcedOutputTexture.height;
  64635. }
  64636. else {
  64637. target = this.inputTexture;
  64638. }
  64639. // Bind the input of this post process to be used as the output of the previous post process.
  64640. if (this.enablePixelPerfectMode) {
  64641. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64642. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  64643. }
  64644. else {
  64645. this._scaleRatio.copyFromFloats(1, 1);
  64646. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  64647. }
  64648. this.onActivateObservable.notifyObservers(camera);
  64649. // Clear
  64650. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64651. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64652. }
  64653. if (this._reusable) {
  64654. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64655. }
  64656. return target;
  64657. };
  64658. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64659. /**
  64660. * If the post process is supported.
  64661. */
  64662. get: function () {
  64663. return this._effect.isSupported;
  64664. },
  64665. enumerable: true,
  64666. configurable: true
  64667. });
  64668. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64669. /**
  64670. * The aspect ratio of the output texture.
  64671. */
  64672. get: function () {
  64673. if (this._shareOutputWithPostProcess) {
  64674. return this._shareOutputWithPostProcess.aspectRatio;
  64675. }
  64676. if (this._forcedOutputTexture) {
  64677. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64678. }
  64679. return this.width / this.height;
  64680. },
  64681. enumerable: true,
  64682. configurable: true
  64683. });
  64684. /**
  64685. * Get a value indicating if the post-process is ready to be used
  64686. * @returns true if the post-process is ready (shader is compiled)
  64687. */
  64688. PostProcess.prototype.isReady = function () {
  64689. return this._effect && this._effect.isReady();
  64690. };
  64691. /**
  64692. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64693. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64694. */
  64695. PostProcess.prototype.apply = function () {
  64696. // Check
  64697. if (!this._effect || !this._effect.isReady())
  64698. return null;
  64699. // States
  64700. this._engine.enableEffect(this._effect);
  64701. this._engine.setState(false);
  64702. this._engine.setDepthBuffer(false);
  64703. this._engine.setDepthWrite(false);
  64704. // Alpha
  64705. this._engine.setAlphaMode(this.alphaMode);
  64706. if (this.alphaConstants) {
  64707. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64708. }
  64709. // Bind the output texture of the preivous post process as the input to this post process.
  64710. var source;
  64711. if (this._shareOutputWithPostProcess) {
  64712. source = this._shareOutputWithPostProcess.inputTexture;
  64713. }
  64714. else if (this._forcedOutputTexture) {
  64715. source = this._forcedOutputTexture;
  64716. }
  64717. else {
  64718. source = this.inputTexture;
  64719. }
  64720. this._effect._bindTexture("textureSampler", source);
  64721. // Parameters
  64722. this._effect.setVector2("scale", this._scaleRatio);
  64723. this.onApplyObservable.notifyObservers(this._effect);
  64724. return this._effect;
  64725. };
  64726. PostProcess.prototype._disposeTextures = function () {
  64727. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64728. return;
  64729. }
  64730. if (this._textures.length > 0) {
  64731. for (var i = 0; i < this._textures.length; i++) {
  64732. this._engine._releaseTexture(this._textures.data[i]);
  64733. }
  64734. }
  64735. this._textures.dispose();
  64736. };
  64737. /**
  64738. * Disposes the post process.
  64739. * @param camera The camera to dispose the post process on.
  64740. */
  64741. PostProcess.prototype.dispose = function (camera) {
  64742. camera = camera || this._camera;
  64743. this._disposeTextures();
  64744. if (this._scene) {
  64745. var index_1 = this._scene.postProcesses.indexOf(this);
  64746. if (index_1 !== -1) {
  64747. this._scene.postProcesses.splice(index_1, 1);
  64748. }
  64749. }
  64750. else {
  64751. var index_2 = this._engine.postProcesses.indexOf(this);
  64752. if (index_2 !== -1) {
  64753. this._engine.postProcesses.splice(index_2, 1);
  64754. }
  64755. }
  64756. if (!camera) {
  64757. return;
  64758. }
  64759. camera.detachPostProcess(this);
  64760. var index = camera._postProcesses.indexOf(this);
  64761. if (index === 0 && camera._postProcesses.length > 0) {
  64762. var firstPostProcess = this._camera._getFirstPostProcess();
  64763. if (firstPostProcess) {
  64764. firstPostProcess.markTextureDirty();
  64765. }
  64766. }
  64767. this.onActivateObservable.clear();
  64768. this.onAfterRenderObservable.clear();
  64769. this.onApplyObservable.clear();
  64770. this.onBeforeRenderObservable.clear();
  64771. this.onSizeChangedObservable.clear();
  64772. };
  64773. return PostProcess;
  64774. }());
  64775. BABYLON.PostProcess = PostProcess;
  64776. })(BABYLON || (BABYLON = {}));
  64777. //# sourceMappingURL=babylon.postProcess.js.map
  64778. var BABYLON;
  64779. (function (BABYLON) {
  64780. var PassPostProcess = /** @class */ (function (_super) {
  64781. __extends(PassPostProcess, _super);
  64782. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64783. if (camera === void 0) { camera = null; }
  64784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64785. if (blockCompilation === void 0) { blockCompilation = false; }
  64786. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64787. }
  64788. return PassPostProcess;
  64789. }(BABYLON.PostProcess));
  64790. BABYLON.PassPostProcess = PassPostProcess;
  64791. })(BABYLON || (BABYLON = {}));
  64792. //# sourceMappingURL=babylon.passPostProcess.js.map
  64793. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64794. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64795. s = arguments[i];
  64796. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64797. t[p] = s[p];
  64798. }
  64799. return t;
  64800. };
  64801. var BABYLON;
  64802. (function (BABYLON) {
  64803. /**
  64804. * Default implementation IShadowGenerator.
  64805. * This is the main object responsible of generating shadows in the framework.
  64806. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64807. */
  64808. var ShadowGenerator = /** @class */ (function () {
  64809. /**
  64810. * Creates a ShadowGenerator object.
  64811. * A ShadowGenerator is the required tool to use the shadows.
  64812. * Each light casting shadows needs to use its own ShadowGenerator.
  64813. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64814. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64815. * @param light The light object generating the shadows.
  64816. * @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.
  64817. */
  64818. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64819. this._bias = 0.00005;
  64820. this._normalBias = 0;
  64821. this._blurBoxOffset = 1;
  64822. this._blurScale = 2;
  64823. this._blurKernel = 1;
  64824. this._useKernelBlur = false;
  64825. this._filter = ShadowGenerator.FILTER_NONE;
  64826. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64827. this._contactHardeningLightSizeUVRatio = 0.1;
  64828. this._darkness = 0;
  64829. this._transparencyShadow = false;
  64830. /**
  64831. * Controls the extent to which the shadows fade out at the edge of the frustum
  64832. * Used only by directionals and spots
  64833. */
  64834. this.frustumEdgeFalloff = 0;
  64835. /**
  64836. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64837. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64838. * It might on the other hand introduce peter panning.
  64839. */
  64840. this.forceBackFacesOnly = false;
  64841. this._lightDirection = BABYLON.Vector3.Zero();
  64842. this._viewMatrix = BABYLON.Matrix.Zero();
  64843. this._projectionMatrix = BABYLON.Matrix.Zero();
  64844. this._transformMatrix = BABYLON.Matrix.Zero();
  64845. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64846. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64847. this._currentFaceIndex = 0;
  64848. this._currentFaceIndexCache = 0;
  64849. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64850. this._mapSize = mapSize;
  64851. this._light = light;
  64852. this._scene = light.getScene();
  64853. light._shadowGenerator = this;
  64854. // Texture type fallback from float to int if not supported.
  64855. var caps = this._scene.getEngine().getCaps();
  64856. if (!useFullFloatFirst) {
  64857. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64858. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64859. }
  64860. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64861. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64862. }
  64863. else {
  64864. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64865. }
  64866. }
  64867. else {
  64868. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64869. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64870. }
  64871. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64872. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64873. }
  64874. else {
  64875. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64876. }
  64877. }
  64878. this._initializeGenerator();
  64879. this._applyFilterValues();
  64880. }
  64881. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64882. /**
  64883. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64884. */
  64885. get: function () {
  64886. return this._bias;
  64887. },
  64888. /**
  64889. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64890. */
  64891. set: function (bias) {
  64892. this._bias = bias;
  64893. },
  64894. enumerable: true,
  64895. configurable: true
  64896. });
  64897. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64898. /**
  64899. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64900. */
  64901. get: function () {
  64902. return this._normalBias;
  64903. },
  64904. /**
  64905. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64906. */
  64907. set: function (normalBias) {
  64908. this._normalBias = normalBias;
  64909. },
  64910. enumerable: true,
  64911. configurable: true
  64912. });
  64913. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64914. /**
  64915. * Gets the blur box offset: offset applied during the blur pass.
  64916. * Only usefull if useKernelBlur = false
  64917. */
  64918. get: function () {
  64919. return this._blurBoxOffset;
  64920. },
  64921. /**
  64922. * Sets the blur box offset: offset applied during the blur pass.
  64923. * Only usefull if useKernelBlur = false
  64924. */
  64925. set: function (value) {
  64926. if (this._blurBoxOffset === value) {
  64927. return;
  64928. }
  64929. this._blurBoxOffset = value;
  64930. this._disposeBlurPostProcesses();
  64931. },
  64932. enumerable: true,
  64933. configurable: true
  64934. });
  64935. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64936. /**
  64937. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64938. * 2 means half of the size.
  64939. */
  64940. get: function () {
  64941. return this._blurScale;
  64942. },
  64943. /**
  64944. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64945. * 2 means half of the size.
  64946. */
  64947. set: function (value) {
  64948. if (this._blurScale === value) {
  64949. return;
  64950. }
  64951. this._blurScale = value;
  64952. this._disposeBlurPostProcesses();
  64953. },
  64954. enumerable: true,
  64955. configurable: true
  64956. });
  64957. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64958. /**
  64959. * Gets the blur kernel: kernel size of the blur pass.
  64960. * Only usefull if useKernelBlur = true
  64961. */
  64962. get: function () {
  64963. return this._blurKernel;
  64964. },
  64965. /**
  64966. * Sets the blur kernel: kernel size of the blur pass.
  64967. * Only usefull if useKernelBlur = true
  64968. */
  64969. set: function (value) {
  64970. if (this._blurKernel === value) {
  64971. return;
  64972. }
  64973. this._blurKernel = value;
  64974. this._disposeBlurPostProcesses();
  64975. },
  64976. enumerable: true,
  64977. configurable: true
  64978. });
  64979. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64980. /**
  64981. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64982. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64983. */
  64984. get: function () {
  64985. return this._useKernelBlur;
  64986. },
  64987. /**
  64988. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64989. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64990. */
  64991. set: function (value) {
  64992. if (this._useKernelBlur === value) {
  64993. return;
  64994. }
  64995. this._useKernelBlur = value;
  64996. this._disposeBlurPostProcesses();
  64997. },
  64998. enumerable: true,
  64999. configurable: true
  65000. });
  65001. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65002. /**
  65003. * Gets the depth scale used in ESM mode.
  65004. */
  65005. get: function () {
  65006. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65007. },
  65008. /**
  65009. * Sets the depth scale used in ESM mode.
  65010. * This can override the scale stored on the light.
  65011. */
  65012. set: function (value) {
  65013. this._depthScale = value;
  65014. },
  65015. enumerable: true,
  65016. configurable: true
  65017. });
  65018. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65019. /**
  65020. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65021. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65022. */
  65023. get: function () {
  65024. return this._filter;
  65025. },
  65026. /**
  65027. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65028. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65029. */
  65030. set: function (value) {
  65031. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65032. if (this._light.needCube()) {
  65033. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65034. this.useExponentialShadowMap = true;
  65035. return;
  65036. }
  65037. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65038. this.useCloseExponentialShadowMap = true;
  65039. return;
  65040. }
  65041. // PCF on cubemap would also be expensive
  65042. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65043. this.usePoissonSampling = true;
  65044. return;
  65045. }
  65046. }
  65047. // Weblg1 fallback for PCF.
  65048. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65049. if (this._scene.getEngine().webGLVersion === 1) {
  65050. this.usePoissonSampling = true;
  65051. return;
  65052. }
  65053. }
  65054. if (this._filter === value) {
  65055. return;
  65056. }
  65057. this._filter = value;
  65058. this._disposeBlurPostProcesses();
  65059. this._applyFilterValues();
  65060. this._light._markMeshesAsLightDirty();
  65061. },
  65062. enumerable: true,
  65063. configurable: true
  65064. });
  65065. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65066. /**
  65067. * Gets if the current filter is set to Poisson Sampling.
  65068. */
  65069. get: function () {
  65070. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65071. },
  65072. /**
  65073. * Sets the current filter to Poisson Sampling.
  65074. */
  65075. set: function (value) {
  65076. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65077. return;
  65078. }
  65079. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65085. /**
  65086. * Gets if the current filter is set to VSM.
  65087. * DEPRECATED. Should use useExponentialShadowMap instead.
  65088. */
  65089. get: function () {
  65090. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65091. return this.useExponentialShadowMap;
  65092. },
  65093. /**
  65094. * Sets the current filter is to VSM.
  65095. * DEPRECATED. Should use useExponentialShadowMap instead.
  65096. */
  65097. set: function (value) {
  65098. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65099. this.useExponentialShadowMap = value;
  65100. },
  65101. enumerable: true,
  65102. configurable: true
  65103. });
  65104. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65105. /**
  65106. * Gets if the current filter is set to blurred VSM.
  65107. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65108. */
  65109. get: function () {
  65110. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65111. return this.useBlurExponentialShadowMap;
  65112. },
  65113. /**
  65114. * Sets the current filter is to blurred VSM.
  65115. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65116. */
  65117. set: function (value) {
  65118. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65119. this.useBlurExponentialShadowMap = value;
  65120. },
  65121. enumerable: true,
  65122. configurable: true
  65123. });
  65124. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65125. /**
  65126. * Gets if the current filter is set to ESM.
  65127. */
  65128. get: function () {
  65129. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65130. },
  65131. /**
  65132. * Sets the current filter is to ESM.
  65133. */
  65134. set: function (value) {
  65135. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65136. return;
  65137. }
  65138. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65139. },
  65140. enumerable: true,
  65141. configurable: true
  65142. });
  65143. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65144. /**
  65145. * Gets if the current filter is set to filtered ESM.
  65146. */
  65147. get: function () {
  65148. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65149. },
  65150. /**
  65151. * Gets if the current filter is set to filtered ESM.
  65152. */
  65153. set: function (value) {
  65154. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65155. return;
  65156. }
  65157. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65158. },
  65159. enumerable: true,
  65160. configurable: true
  65161. });
  65162. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65163. /**
  65164. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65165. * exponential to prevent steep falloff artifacts).
  65166. */
  65167. get: function () {
  65168. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65169. },
  65170. /**
  65171. * Sets the current filter to "close ESM" (using the inverse of the
  65172. * exponential to prevent steep falloff artifacts).
  65173. */
  65174. set: function (value) {
  65175. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65176. return;
  65177. }
  65178. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65179. },
  65180. enumerable: true,
  65181. configurable: true
  65182. });
  65183. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65184. /**
  65185. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65186. * exponential to prevent steep falloff artifacts).
  65187. */
  65188. get: function () {
  65189. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65190. },
  65191. /**
  65192. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65193. * exponential to prevent steep falloff artifacts).
  65194. */
  65195. set: function (value) {
  65196. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65197. return;
  65198. }
  65199. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65200. },
  65201. enumerable: true,
  65202. configurable: true
  65203. });
  65204. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65205. /**
  65206. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65207. */
  65208. get: function () {
  65209. return this.filter === ShadowGenerator.FILTER_PCF;
  65210. },
  65211. /**
  65212. * Sets the current filter to "PCF" (percentage closer filtering).
  65213. */
  65214. set: function (value) {
  65215. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65216. return;
  65217. }
  65218. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65224. /**
  65225. * Gets the PCF or PCSS Quality.
  65226. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65227. */
  65228. get: function () {
  65229. return this._filteringQuality;
  65230. },
  65231. /**
  65232. * Sets the PCF or PCSS Quality.
  65233. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65234. */
  65235. set: function (filteringQuality) {
  65236. this._filteringQuality = filteringQuality;
  65237. },
  65238. enumerable: true,
  65239. configurable: true
  65240. });
  65241. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65242. /**
  65243. * Gets if the current filter is set to "PCSS" (contact hardening).
  65244. */
  65245. get: function () {
  65246. return this.filter === ShadowGenerator.FILTER_PCSS;
  65247. },
  65248. /**
  65249. * Sets the current filter to "PCSS" (contact hardening).
  65250. */
  65251. set: function (value) {
  65252. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65253. return;
  65254. }
  65255. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65256. },
  65257. enumerable: true,
  65258. configurable: true
  65259. });
  65260. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65261. /**
  65262. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65263. * Using a ratio helps keeping shape stability independently of the map size.
  65264. *
  65265. * It does not account for the light projection as it was having too much
  65266. * instability during the light setup or during light position changes.
  65267. *
  65268. * Only valid if useContactHardeningShadow is true.
  65269. */
  65270. get: function () {
  65271. return this._contactHardeningLightSizeUVRatio;
  65272. },
  65273. /**
  65274. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65275. * Using a ratio helps keeping shape stability independently of the map size.
  65276. *
  65277. * It does not account for the light projection as it was having too much
  65278. * instability during the light setup or during light position changes.
  65279. *
  65280. * Only valid if useContactHardeningShadow is true.
  65281. */
  65282. set: function (contactHardeningLightSizeUVRatio) {
  65283. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65284. },
  65285. enumerable: true,
  65286. configurable: true
  65287. });
  65288. /**
  65289. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65290. * 0 means strongest and 1 would means no shadow.
  65291. * @returns the darkness.
  65292. */
  65293. ShadowGenerator.prototype.getDarkness = function () {
  65294. return this._darkness;
  65295. };
  65296. /**
  65297. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65298. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65299. * @returns the shadow generator allowing fluent coding.
  65300. */
  65301. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65302. if (darkness >= 1.0)
  65303. this._darkness = 1.0;
  65304. else if (darkness <= 0.0)
  65305. this._darkness = 0.0;
  65306. else
  65307. this._darkness = darkness;
  65308. return this;
  65309. };
  65310. /**
  65311. * Sets the ability to have transparent shadow (boolean).
  65312. * @param transparent True if transparent else False
  65313. * @returns the shadow generator allowing fluent coding
  65314. */
  65315. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65316. this._transparencyShadow = transparent;
  65317. return this;
  65318. };
  65319. /**
  65320. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65321. * @returns The render target texture if present otherwise, null
  65322. */
  65323. ShadowGenerator.prototype.getShadowMap = function () {
  65324. return this._shadowMap;
  65325. };
  65326. /**
  65327. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65328. * @returns The render target texture if the shadow map is present otherwise, null
  65329. */
  65330. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65331. if (this._shadowMap2) {
  65332. return this._shadowMap2;
  65333. }
  65334. return this._shadowMap;
  65335. };
  65336. /**
  65337. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65338. * @param mesh Mesh to add
  65339. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65340. * @returns the Shadow Generator itself
  65341. */
  65342. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65343. if (includeDescendants === void 0) { includeDescendants = true; }
  65344. if (!this._shadowMap) {
  65345. return this;
  65346. }
  65347. if (!this._shadowMap.renderList) {
  65348. this._shadowMap.renderList = [];
  65349. }
  65350. this._shadowMap.renderList.push(mesh);
  65351. if (includeDescendants) {
  65352. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65353. }
  65354. return this;
  65355. var _a;
  65356. };
  65357. /**
  65358. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65359. * @param mesh Mesh to remove
  65360. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65361. * @returns the Shadow Generator itself
  65362. */
  65363. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65364. if (includeDescendants === void 0) { includeDescendants = true; }
  65365. if (!this._shadowMap || !this._shadowMap.renderList) {
  65366. return this;
  65367. }
  65368. var index = this._shadowMap.renderList.indexOf(mesh);
  65369. if (index !== -1) {
  65370. this._shadowMap.renderList.splice(index, 1);
  65371. }
  65372. if (includeDescendants) {
  65373. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65374. var child = _a[_i];
  65375. this.removeShadowCaster(child);
  65376. }
  65377. }
  65378. return this;
  65379. };
  65380. /**
  65381. * Returns the associated light object.
  65382. * @returns the light generating the shadow
  65383. */
  65384. ShadowGenerator.prototype.getLight = function () {
  65385. return this._light;
  65386. };
  65387. ShadowGenerator.prototype._initializeGenerator = function () {
  65388. this._light._markMeshesAsLightDirty();
  65389. this._initializeShadowMap();
  65390. };
  65391. ShadowGenerator.prototype._initializeShadowMap = function () {
  65392. var _this = this;
  65393. // Render target
  65394. var engine = this._scene.getEngine();
  65395. if (engine.webGLVersion > 1) {
  65396. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65397. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65398. }
  65399. else {
  65400. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65401. }
  65402. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65403. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65404. this._shadowMap.anisotropicFilteringLevel = 1;
  65405. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65406. this._shadowMap.renderParticles = false;
  65407. this._shadowMap.ignoreCameraViewport = true;
  65408. // Record Face Index before render.
  65409. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65410. _this._currentFaceIndex = faceIndex;
  65411. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65412. engine.setColorWrite(false);
  65413. }
  65414. });
  65415. // Custom render function.
  65416. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65417. // Blur if required afer render.
  65418. this._shadowMap.onAfterUnbindObservable.add(function () {
  65419. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65420. engine.setColorWrite(true);
  65421. }
  65422. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65423. return;
  65424. }
  65425. var shadowMap = _this.getShadowMapForRendering();
  65426. if (shadowMap) {
  65427. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65428. }
  65429. });
  65430. // Clear according to the chosen filter.
  65431. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65432. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65433. this._shadowMap.onClearObservable.add(function (engine) {
  65434. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65435. engine.clear(clearOne, false, true, false);
  65436. }
  65437. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65438. engine.clear(clearZero, true, true, false);
  65439. }
  65440. else {
  65441. engine.clear(clearOne, true, true, false);
  65442. }
  65443. });
  65444. };
  65445. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65446. var _this = this;
  65447. var engine = this._scene.getEngine();
  65448. var targetSize = this._mapSize / this.blurScale;
  65449. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65450. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65451. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65452. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65453. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65454. }
  65455. if (this.useKernelBlur) {
  65456. 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);
  65457. this._kernelBlurXPostprocess.width = targetSize;
  65458. this._kernelBlurXPostprocess.height = targetSize;
  65459. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65460. effect.setTexture("textureSampler", _this._shadowMap);
  65461. });
  65462. 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);
  65463. this._kernelBlurXPostprocess.autoClear = false;
  65464. this._kernelBlurYPostprocess.autoClear = false;
  65465. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65466. this._kernelBlurXPostprocess.packedFloat = true;
  65467. this._kernelBlurYPostprocess.packedFloat = true;
  65468. }
  65469. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65470. }
  65471. else {
  65472. 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);
  65473. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65474. effect.setFloat2("screenSize", targetSize, targetSize);
  65475. effect.setTexture("textureSampler", _this._shadowMap);
  65476. });
  65477. this._boxBlurPostprocess.autoClear = false;
  65478. this._blurPostProcesses = [this._boxBlurPostprocess];
  65479. }
  65480. };
  65481. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65482. var index;
  65483. var engine = this._scene.getEngine();
  65484. if (depthOnlySubMeshes.length) {
  65485. engine.setColorWrite(false);
  65486. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65487. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65488. }
  65489. engine.setColorWrite(true);
  65490. }
  65491. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65492. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65493. }
  65494. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65495. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65496. }
  65497. if (this._transparencyShadow) {
  65498. for (index = 0; index < transparentSubMeshes.length; index++) {
  65499. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65500. }
  65501. }
  65502. };
  65503. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65504. var _this = this;
  65505. var mesh = subMesh.getRenderingMesh();
  65506. var scene = this._scene;
  65507. var engine = scene.getEngine();
  65508. var material = subMesh.getMaterial();
  65509. if (!material) {
  65510. return;
  65511. }
  65512. // Culling
  65513. engine.setState(material.backFaceCulling);
  65514. // Managing instances
  65515. var batch = mesh._getInstancesRenderList(subMesh._id);
  65516. if (batch.mustReturn) {
  65517. return;
  65518. }
  65519. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65520. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65521. engine.enableEffect(this._effect);
  65522. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65523. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65524. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65525. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65526. this._effect.setVector3("lightData", this._cachedDirection);
  65527. }
  65528. else {
  65529. this._effect.setVector3("lightData", this._cachedPosition);
  65530. }
  65531. if (scene.activeCamera) {
  65532. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65533. }
  65534. // Alpha test
  65535. if (material && material.needAlphaTesting()) {
  65536. var alphaTexture = material.getAlphaTestTexture();
  65537. if (alphaTexture) {
  65538. this._effect.setTexture("diffuseSampler", alphaTexture);
  65539. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65540. }
  65541. }
  65542. // Bones
  65543. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65544. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65545. }
  65546. // Morph targets
  65547. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65548. if (this.forceBackFacesOnly) {
  65549. engine.setState(true, 0, false, true);
  65550. }
  65551. // Draw
  65552. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65553. if (this.forceBackFacesOnly) {
  65554. engine.setState(true, 0, false, false);
  65555. }
  65556. }
  65557. else {
  65558. // Need to reset refresh rate of the shadowMap
  65559. if (this._shadowMap) {
  65560. this._shadowMap.resetRefreshCounter();
  65561. }
  65562. }
  65563. };
  65564. ShadowGenerator.prototype._applyFilterValues = function () {
  65565. if (!this._shadowMap) {
  65566. return;
  65567. }
  65568. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65569. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65570. }
  65571. else {
  65572. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65573. }
  65574. };
  65575. /**
  65576. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65577. * @param onCompiled Callback triggered at the and of the effects compilation
  65578. * @param options Sets of optional options forcing the compilation with different modes
  65579. */
  65580. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65581. var _this = this;
  65582. var localOptions = __assign({ useInstances: false }, options);
  65583. var shadowMap = this.getShadowMap();
  65584. if (!shadowMap) {
  65585. if (onCompiled) {
  65586. onCompiled(this);
  65587. }
  65588. return;
  65589. }
  65590. var renderList = shadowMap.renderList;
  65591. if (!renderList) {
  65592. if (onCompiled) {
  65593. onCompiled(this);
  65594. }
  65595. return;
  65596. }
  65597. var subMeshes = new Array();
  65598. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65599. var mesh = renderList_1[_i];
  65600. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65601. }
  65602. if (subMeshes.length === 0) {
  65603. if (onCompiled) {
  65604. onCompiled(this);
  65605. }
  65606. return;
  65607. }
  65608. var currentIndex = 0;
  65609. var checkReady = function () {
  65610. if (!_this._scene || !_this._scene.getEngine()) {
  65611. return;
  65612. }
  65613. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65614. currentIndex++;
  65615. if (currentIndex >= subMeshes.length) {
  65616. if (onCompiled) {
  65617. onCompiled(_this);
  65618. }
  65619. return;
  65620. }
  65621. }
  65622. setTimeout(checkReady, 16);
  65623. };
  65624. checkReady();
  65625. };
  65626. /**
  65627. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65628. * @param options Sets of optional options forcing the compilation with different modes
  65629. * @returns A promise that resolves when the compilation completes
  65630. */
  65631. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65632. var _this = this;
  65633. return new Promise(function (resolve) {
  65634. _this.forceCompilation(function () {
  65635. resolve();
  65636. }, options);
  65637. });
  65638. };
  65639. /**
  65640. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65641. * @param subMesh The submesh we want to render in the shadow map
  65642. * @param useInstances Defines wether will draw in the map using instances
  65643. * @returns true if ready otherwise, false
  65644. */
  65645. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65646. var defines = [];
  65647. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65648. defines.push("#define FLOAT");
  65649. }
  65650. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65651. defines.push("#define ESM");
  65652. }
  65653. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65654. defines.push("#define DEPTHTEXTURE");
  65655. }
  65656. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65657. var mesh = subMesh.getMesh();
  65658. var material = subMesh.getMaterial();
  65659. // Normal bias.
  65660. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65661. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65662. defines.push("#define NORMAL");
  65663. if (mesh.nonUniformScaling) {
  65664. defines.push("#define NONUNIFORMSCALING");
  65665. }
  65666. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65667. defines.push("#define DIRECTIONINLIGHTDATA");
  65668. }
  65669. }
  65670. // Alpha test
  65671. if (material && material.needAlphaTesting()) {
  65672. var alphaTexture = material.getAlphaTestTexture();
  65673. if (alphaTexture) {
  65674. defines.push("#define ALPHATEST");
  65675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65676. attribs.push(BABYLON.VertexBuffer.UVKind);
  65677. defines.push("#define UV1");
  65678. }
  65679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65680. if (alphaTexture.coordinatesIndex === 1) {
  65681. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65682. defines.push("#define UV2");
  65683. }
  65684. }
  65685. }
  65686. }
  65687. // Bones
  65688. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65691. if (mesh.numBoneInfluencers > 4) {
  65692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65694. }
  65695. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65696. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65697. }
  65698. else {
  65699. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65700. }
  65701. // Morph targets
  65702. var manager = mesh.morphTargetManager;
  65703. var morphInfluencers = 0;
  65704. if (manager) {
  65705. if (manager.numInfluencers > 0) {
  65706. defines.push("#define MORPHTARGETS");
  65707. morphInfluencers = manager.numInfluencers;
  65708. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65709. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65710. }
  65711. }
  65712. // Instances
  65713. if (useInstances) {
  65714. defines.push("#define INSTANCES");
  65715. attribs.push("world0");
  65716. attribs.push("world1");
  65717. attribs.push("world2");
  65718. attribs.push("world3");
  65719. }
  65720. // Get correct effect
  65721. var join = defines.join("\n");
  65722. if (this._cachedDefines !== join) {
  65723. this._cachedDefines = join;
  65724. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65725. }
  65726. if (!this._effect.isReady()) {
  65727. return false;
  65728. }
  65729. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65730. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65731. this._initializeBlurRTTAndPostProcesses();
  65732. }
  65733. }
  65734. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65735. return false;
  65736. }
  65737. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65738. return false;
  65739. }
  65740. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65741. return false;
  65742. }
  65743. return true;
  65744. };
  65745. /**
  65746. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65747. * @param defines Defines of the material we want to update
  65748. * @param lightIndex Index of the light in the enabled light list of the material
  65749. */
  65750. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65751. var scene = this._scene;
  65752. var light = this._light;
  65753. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65754. return;
  65755. }
  65756. defines["SHADOW" + lightIndex] = true;
  65757. if (this.useContactHardeningShadow) {
  65758. defines["SHADOWPCSS" + lightIndex] = true;
  65759. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65760. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65761. }
  65762. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65763. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65764. }
  65765. // else default to high.
  65766. }
  65767. if (this.usePercentageCloserFiltering) {
  65768. defines["SHADOWPCF" + lightIndex] = true;
  65769. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65770. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65771. }
  65772. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65773. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65774. }
  65775. // else default to high.
  65776. }
  65777. else if (this.usePoissonSampling) {
  65778. defines["SHADOWPOISSON" + lightIndex] = true;
  65779. }
  65780. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65781. defines["SHADOWESM" + lightIndex] = true;
  65782. }
  65783. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65784. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65785. }
  65786. if (light.needCube()) {
  65787. defines["SHADOWCUBE" + lightIndex] = true;
  65788. }
  65789. };
  65790. /**
  65791. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65792. * defined in the generator but impacting the effect).
  65793. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65794. * @param effect The effect we are binfing the information for
  65795. */
  65796. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65797. var light = this._light;
  65798. var scene = this._scene;
  65799. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65800. return;
  65801. }
  65802. var camera = scene.activeCamera;
  65803. if (!camera) {
  65804. return;
  65805. }
  65806. var shadowMap = this.getShadowMap();
  65807. if (!shadowMap) {
  65808. return;
  65809. }
  65810. if (!light.needCube()) {
  65811. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65812. }
  65813. // Only PCF uses depth stencil texture.
  65814. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65815. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65816. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65817. }
  65818. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65819. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65820. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65821. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65822. }
  65823. else {
  65824. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65825. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65826. }
  65827. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65828. };
  65829. /**
  65830. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65831. * (eq to shadow prjection matrix * light transform matrix)
  65832. * @returns The transform matrix used to create the shadow map
  65833. */
  65834. ShadowGenerator.prototype.getTransformMatrix = function () {
  65835. var scene = this._scene;
  65836. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65837. return this._transformMatrix;
  65838. }
  65839. this._currentRenderID = scene.getRenderId();
  65840. this._currentFaceIndexCache = this._currentFaceIndex;
  65841. var lightPosition = this._light.position;
  65842. if (this._light.computeTransformedInformation()) {
  65843. lightPosition = this._light.transformedPosition;
  65844. }
  65845. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65846. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65847. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65848. }
  65849. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65850. this._cachedPosition.copyFrom(lightPosition);
  65851. this._cachedDirection.copyFrom(this._lightDirection);
  65852. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65853. var shadowMap = this.getShadowMap();
  65854. if (shadowMap) {
  65855. var renderList = shadowMap.renderList;
  65856. if (renderList) {
  65857. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65858. }
  65859. }
  65860. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65861. }
  65862. return this._transformMatrix;
  65863. };
  65864. /**
  65865. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65866. * Cube and 2D textures for instance.
  65867. */
  65868. ShadowGenerator.prototype.recreateShadowMap = function () {
  65869. var shadowMap = this._shadowMap;
  65870. if (!shadowMap) {
  65871. return;
  65872. }
  65873. // Track render list.
  65874. var renderList = shadowMap.renderList;
  65875. // Clean up existing data.
  65876. this._disposeRTTandPostProcesses();
  65877. // Reinitializes.
  65878. this._initializeGenerator();
  65879. // Reaffect the filter to ensure a correct fallback if necessary.
  65880. this.filter = this.filter;
  65881. // Reaffect the filter.
  65882. this._applyFilterValues();
  65883. // Reaffect Render List.
  65884. this._shadowMap.renderList = renderList;
  65885. };
  65886. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65887. if (this._shadowMap2) {
  65888. this._shadowMap2.dispose();
  65889. this._shadowMap2 = null;
  65890. }
  65891. if (this._boxBlurPostprocess) {
  65892. this._boxBlurPostprocess.dispose();
  65893. this._boxBlurPostprocess = null;
  65894. }
  65895. if (this._kernelBlurXPostprocess) {
  65896. this._kernelBlurXPostprocess.dispose();
  65897. this._kernelBlurXPostprocess = null;
  65898. }
  65899. if (this._kernelBlurYPostprocess) {
  65900. this._kernelBlurYPostprocess.dispose();
  65901. this._kernelBlurYPostprocess = null;
  65902. }
  65903. this._blurPostProcesses = [];
  65904. };
  65905. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65906. if (this._shadowMap) {
  65907. this._shadowMap.dispose();
  65908. this._shadowMap = null;
  65909. }
  65910. this._disposeBlurPostProcesses();
  65911. };
  65912. /**
  65913. * Disposes the ShadowGenerator.
  65914. * Returns nothing.
  65915. */
  65916. ShadowGenerator.prototype.dispose = function () {
  65917. this._disposeRTTandPostProcesses();
  65918. if (this._light) {
  65919. this._light._shadowGenerator = null;
  65920. this._light._markMeshesAsLightDirty();
  65921. }
  65922. };
  65923. /**
  65924. * Serializes the shadow generator setup to a json object.
  65925. * @returns The serialized JSON object
  65926. */
  65927. ShadowGenerator.prototype.serialize = function () {
  65928. var serializationObject = {};
  65929. var shadowMap = this.getShadowMap();
  65930. if (!shadowMap) {
  65931. return serializationObject;
  65932. }
  65933. serializationObject.lightId = this._light.id;
  65934. serializationObject.mapSize = shadowMap.getRenderSize();
  65935. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65936. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65937. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65938. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65939. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65940. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65941. serializationObject.depthScale = this.depthScale;
  65942. serializationObject.darkness = this.getDarkness();
  65943. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65944. serializationObject.blurKernel = this.blurKernel;
  65945. serializationObject.blurScale = this.blurScale;
  65946. serializationObject.useKernelBlur = this.useKernelBlur;
  65947. serializationObject.transparencyShadow = this._transparencyShadow;
  65948. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  65949. serializationObject.bias = this.bias;
  65950. serializationObject.normalBias = this.normalBias;
  65951. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65952. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65953. serializationObject.filteringQuality = this.filteringQuality;
  65954. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65955. serializationObject.renderList = [];
  65956. if (shadowMap.renderList) {
  65957. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65958. var mesh = shadowMap.renderList[meshIndex];
  65959. serializationObject.renderList.push(mesh.id);
  65960. }
  65961. }
  65962. return serializationObject;
  65963. };
  65964. /**
  65965. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65966. * @param parsedShadowGenerator The JSON object to parse
  65967. * @param scene The scene to create the shadow map for
  65968. * @returns The parsed shadow generator
  65969. */
  65970. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65971. //casting to point light, as light is missing the position attr and typescript complains.
  65972. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65973. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65974. var shadowMap = shadowGenerator.getShadowMap();
  65975. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65976. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65977. meshes.forEach(function (mesh) {
  65978. if (!shadowMap) {
  65979. return;
  65980. }
  65981. if (!shadowMap.renderList) {
  65982. shadowMap.renderList = [];
  65983. }
  65984. shadowMap.renderList.push(mesh);
  65985. });
  65986. }
  65987. if (parsedShadowGenerator.usePoissonSampling) {
  65988. shadowGenerator.usePoissonSampling = true;
  65989. }
  65990. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65991. shadowGenerator.useExponentialShadowMap = true;
  65992. }
  65993. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65994. shadowGenerator.useBlurExponentialShadowMap = true;
  65995. }
  65996. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65997. shadowGenerator.useCloseExponentialShadowMap = true;
  65998. }
  65999. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66000. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66001. }
  66002. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66003. shadowGenerator.usePercentageCloserFiltering = true;
  66004. }
  66005. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66006. shadowGenerator.useContactHardeningShadow = true;
  66007. }
  66008. if (parsedShadowGenerator.filteringQuality) {
  66009. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66010. }
  66011. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66012. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66013. }
  66014. // Backward compat
  66015. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66016. shadowGenerator.useExponentialShadowMap = true;
  66017. }
  66018. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66019. shadowGenerator.useBlurExponentialShadowMap = true;
  66020. }
  66021. if (parsedShadowGenerator.depthScale) {
  66022. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66023. }
  66024. if (parsedShadowGenerator.blurScale) {
  66025. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66026. }
  66027. if (parsedShadowGenerator.blurBoxOffset) {
  66028. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66029. }
  66030. if (parsedShadowGenerator.useKernelBlur) {
  66031. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66032. }
  66033. if (parsedShadowGenerator.blurKernel) {
  66034. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66035. }
  66036. if (parsedShadowGenerator.bias !== undefined) {
  66037. shadowGenerator.bias = parsedShadowGenerator.bias;
  66038. }
  66039. if (parsedShadowGenerator.normalBias !== undefined) {
  66040. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66041. }
  66042. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66043. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66044. }
  66045. if (parsedShadowGenerator.darkness) {
  66046. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66047. }
  66048. if (parsedShadowGenerator.transparencyShadow) {
  66049. shadowGenerator.setTransparencyShadow(true);
  66050. }
  66051. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66052. return shadowGenerator;
  66053. };
  66054. /**
  66055. * Shadow generator mode None: no filtering applied.
  66056. */
  66057. ShadowGenerator.FILTER_NONE = 0;
  66058. /**
  66059. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66060. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66061. */
  66062. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66063. /**
  66064. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66065. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66066. */
  66067. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66068. /**
  66069. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66070. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66071. */
  66072. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66073. /**
  66074. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66075. * edge artifacts on steep falloff.
  66076. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66077. */
  66078. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66079. /**
  66080. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66081. * edge artifacts on steep falloff.
  66082. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66083. */
  66084. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66085. /**
  66086. * Shadow generator mode PCF: Percentage Closer Filtering
  66087. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66088. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66089. */
  66090. ShadowGenerator.FILTER_PCF = 6;
  66091. /**
  66092. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66093. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66094. * Contact Hardening
  66095. */
  66096. ShadowGenerator.FILTER_PCSS = 7;
  66097. /**
  66098. * Reserved for PCF and PCSS
  66099. * Highest Quality.
  66100. *
  66101. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66102. *
  66103. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66104. */
  66105. ShadowGenerator.QUALITY_HIGH = 0;
  66106. /**
  66107. * Reserved for PCF and PCSS
  66108. * Good tradeoff for quality/perf cross devices
  66109. *
  66110. * Execute PCF on a 3*3 kernel.
  66111. *
  66112. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66113. */
  66114. ShadowGenerator.QUALITY_MEDIUM = 1;
  66115. /**
  66116. * Reserved for PCF and PCSS
  66117. * The lowest quality but the fastest.
  66118. *
  66119. * Execute PCF on a 1*1 kernel.
  66120. *
  66121. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66122. */
  66123. ShadowGenerator.QUALITY_LOW = 2;
  66124. return ShadowGenerator;
  66125. }());
  66126. BABYLON.ShadowGenerator = ShadowGenerator;
  66127. })(BABYLON || (BABYLON = {}));
  66128. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66129. var BABYLON;
  66130. (function (BABYLON) {
  66131. var DefaultLoadingScreen = /** @class */ (function () {
  66132. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66133. if (_loadingText === void 0) { _loadingText = ""; }
  66134. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66135. var _this = this;
  66136. this._renderingCanvas = _renderingCanvas;
  66137. this._loadingText = _loadingText;
  66138. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66139. // Resize
  66140. this._resizeLoadingUI = function () {
  66141. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66142. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66143. if (!_this._loadingDiv) {
  66144. return;
  66145. }
  66146. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66147. _this._loadingDiv.style.left = canvasRect.left + "px";
  66148. _this._loadingDiv.style.top = canvasRect.top + "px";
  66149. _this._loadingDiv.style.width = canvasRect.width + "px";
  66150. _this._loadingDiv.style.height = canvasRect.height + "px";
  66151. };
  66152. }
  66153. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66154. if (this._loadingDiv) {
  66155. // Do not add a loading screen if there is already one
  66156. return;
  66157. }
  66158. this._loadingDiv = document.createElement("div");
  66159. this._loadingDiv.id = "babylonjsLoadingDiv";
  66160. this._loadingDiv.style.opacity = "0";
  66161. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66162. this._loadingDiv.style.pointerEvents = "none";
  66163. // Loading text
  66164. this._loadingTextDiv = document.createElement("div");
  66165. this._loadingTextDiv.style.position = "absolute";
  66166. this._loadingTextDiv.style.left = "0";
  66167. this._loadingTextDiv.style.top = "50%";
  66168. this._loadingTextDiv.style.marginTop = "80px";
  66169. this._loadingTextDiv.style.width = "100%";
  66170. this._loadingTextDiv.style.height = "20px";
  66171. this._loadingTextDiv.style.fontFamily = "Arial";
  66172. this._loadingTextDiv.style.fontSize = "14px";
  66173. this._loadingTextDiv.style.color = "white";
  66174. this._loadingTextDiv.style.textAlign = "center";
  66175. this._loadingTextDiv.innerHTML = "Loading";
  66176. this._loadingDiv.appendChild(this._loadingTextDiv);
  66177. //set the predefined text
  66178. this._loadingTextDiv.innerHTML = this._loadingText;
  66179. // Generating keyframes
  66180. var style = document.createElement('style');
  66181. style.type = 'text/css';
  66182. 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 }";
  66183. style.innerHTML = keyFrames;
  66184. document.getElementsByTagName('head')[0].appendChild(style);
  66185. // Loading img
  66186. var imgBack = new Image();
  66187. 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";
  66188. imgBack.style.position = "absolute";
  66189. imgBack.style.left = "50%";
  66190. imgBack.style.top = "50%";
  66191. imgBack.style.marginLeft = "-60px";
  66192. imgBack.style.marginTop = "-60px";
  66193. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66194. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66195. imgBack.style.transformOrigin = "50% 50%";
  66196. imgBack.style.webkitTransformOrigin = "50% 50%";
  66197. this._loadingDiv.appendChild(imgBack);
  66198. this._resizeLoadingUI();
  66199. window.addEventListener("resize", this._resizeLoadingUI);
  66200. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66201. document.body.appendChild(this._loadingDiv);
  66202. this._loadingDiv.style.opacity = "1";
  66203. };
  66204. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66205. var _this = this;
  66206. if (!this._loadingDiv) {
  66207. return;
  66208. }
  66209. var onTransitionEnd = function () {
  66210. if (!_this._loadingDiv) {
  66211. return;
  66212. }
  66213. document.body.removeChild(_this._loadingDiv);
  66214. window.removeEventListener("resize", _this._resizeLoadingUI);
  66215. _this._loadingDiv = null;
  66216. };
  66217. this._loadingDiv.style.opacity = "0";
  66218. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66219. };
  66220. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66221. set: function (text) {
  66222. this._loadingText = text;
  66223. if (this._loadingTextDiv) {
  66224. this._loadingTextDiv.innerHTML = this._loadingText;
  66225. }
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66231. get: function () {
  66232. return this._loadingDivBackgroundColor;
  66233. },
  66234. set: function (color) {
  66235. this._loadingDivBackgroundColor = color;
  66236. if (!this._loadingDiv) {
  66237. return;
  66238. }
  66239. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66240. },
  66241. enumerable: true,
  66242. configurable: true
  66243. });
  66244. return DefaultLoadingScreen;
  66245. }());
  66246. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66247. })(BABYLON || (BABYLON = {}));
  66248. //# sourceMappingURL=babylon.loadingScreen.js.map
  66249. var BABYLON;
  66250. (function (BABYLON) {
  66251. var SceneLoaderProgressEvent = /** @class */ (function () {
  66252. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66253. this.lengthComputable = lengthComputable;
  66254. this.loaded = loaded;
  66255. this.total = total;
  66256. }
  66257. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66258. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66259. };
  66260. return SceneLoaderProgressEvent;
  66261. }());
  66262. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66263. var SceneLoader = /** @class */ (function () {
  66264. function SceneLoader() {
  66265. }
  66266. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66267. get: function () {
  66268. return 0;
  66269. },
  66270. enumerable: true,
  66271. configurable: true
  66272. });
  66273. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66274. get: function () {
  66275. return 1;
  66276. },
  66277. enumerable: true,
  66278. configurable: true
  66279. });
  66280. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66281. get: function () {
  66282. return 2;
  66283. },
  66284. enumerable: true,
  66285. configurable: true
  66286. });
  66287. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66288. get: function () {
  66289. return 3;
  66290. },
  66291. enumerable: true,
  66292. configurable: true
  66293. });
  66294. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66295. get: function () {
  66296. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66297. },
  66298. set: function (value) {
  66299. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66300. },
  66301. enumerable: true,
  66302. configurable: true
  66303. });
  66304. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66305. get: function () {
  66306. return SceneLoader._ShowLoadingScreen;
  66307. },
  66308. set: function (value) {
  66309. SceneLoader._ShowLoadingScreen = value;
  66310. },
  66311. enumerable: true,
  66312. configurable: true
  66313. });
  66314. Object.defineProperty(SceneLoader, "loggingLevel", {
  66315. get: function () {
  66316. return SceneLoader._loggingLevel;
  66317. },
  66318. set: function (value) {
  66319. SceneLoader._loggingLevel = value;
  66320. },
  66321. enumerable: true,
  66322. configurable: true
  66323. });
  66324. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66325. get: function () {
  66326. return SceneLoader._CleanBoneMatrixWeights;
  66327. },
  66328. set: function (value) {
  66329. SceneLoader._CleanBoneMatrixWeights = value;
  66330. },
  66331. enumerable: true,
  66332. configurable: true
  66333. });
  66334. SceneLoader._getDefaultPlugin = function () {
  66335. return SceneLoader._registeredPlugins[".babylon"];
  66336. };
  66337. SceneLoader._getPluginForExtension = function (extension) {
  66338. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66339. if (registeredPlugin) {
  66340. return registeredPlugin;
  66341. }
  66342. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  66343. return SceneLoader._getDefaultPlugin();
  66344. };
  66345. SceneLoader._getPluginForDirectLoad = function (data) {
  66346. for (var extension in SceneLoader._registeredPlugins) {
  66347. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66348. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66349. return SceneLoader._registeredPlugins[extension];
  66350. }
  66351. }
  66352. return SceneLoader._getDefaultPlugin();
  66353. };
  66354. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66355. if (sceneFilename.name) {
  66356. sceneFilename = sceneFilename.name;
  66357. }
  66358. var queryStringPosition = sceneFilename.indexOf("?");
  66359. if (queryStringPosition !== -1) {
  66360. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66361. }
  66362. var dotPosition = sceneFilename.lastIndexOf(".");
  66363. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66364. return SceneLoader._getPluginForExtension(extension);
  66365. };
  66366. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66367. SceneLoader._getDirectLoad = function (sceneFilename) {
  66368. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66369. return sceneFilename.substr(5);
  66370. }
  66371. return null;
  66372. };
  66373. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66374. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66375. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66376. var plugin;
  66377. if (registeredPlugin.plugin.createPlugin) {
  66378. plugin = registeredPlugin.plugin.createPlugin();
  66379. }
  66380. else {
  66381. plugin = registeredPlugin.plugin;
  66382. }
  66383. var useArrayBuffer = registeredPlugin.isBinary;
  66384. var database;
  66385. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66386. var dataCallback = function (data, responseURL) {
  66387. if (scene.isDisposed) {
  66388. onError("Scene has been disposed");
  66389. return;
  66390. }
  66391. scene.database = database;
  66392. onSuccess(plugin, data, responseURL);
  66393. };
  66394. var request = null;
  66395. var pluginDisposed = false;
  66396. var onDisposeObservable = plugin.onDisposeObservable;
  66397. if (onDisposeObservable) {
  66398. onDisposeObservable.add(function () {
  66399. pluginDisposed = true;
  66400. if (request) {
  66401. request.abort();
  66402. request = null;
  66403. }
  66404. onDispose();
  66405. });
  66406. }
  66407. var manifestChecked = function () {
  66408. if (pluginDisposed) {
  66409. return;
  66410. }
  66411. var url = rootUrl + sceneFilename;
  66412. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66413. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66414. } : undefined, database, useArrayBuffer, function (request, exception) {
  66415. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66416. });
  66417. };
  66418. if (directLoad) {
  66419. dataCallback(directLoad);
  66420. return plugin;
  66421. }
  66422. if (rootUrl.indexOf("file:") === -1) {
  66423. var engine = scene.getEngine();
  66424. var canUseOfflineSupport = engine.enableOfflineSupport;
  66425. if (canUseOfflineSupport) {
  66426. // Also check for exceptions
  66427. var exceptionFound = false;
  66428. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66429. var regex = _a[_i];
  66430. if (regex.test(rootUrl + sceneFilename)) {
  66431. exceptionFound = true;
  66432. break;
  66433. }
  66434. }
  66435. canUseOfflineSupport = !exceptionFound;
  66436. }
  66437. if (canUseOfflineSupport) {
  66438. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66439. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66440. }
  66441. else {
  66442. manifestChecked();
  66443. }
  66444. }
  66445. // Loading file from disk via input file or drag'n'drop
  66446. else {
  66447. var fileOrString = sceneFilename;
  66448. if (fileOrString.name) { // File
  66449. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66450. }
  66451. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66452. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66453. }
  66454. else {
  66455. onError("Unable to find file named " + sceneFilename);
  66456. }
  66457. }
  66458. return plugin;
  66459. };
  66460. // Public functions
  66461. SceneLoader.GetPluginForExtension = function (extension) {
  66462. return SceneLoader._getPluginForExtension(extension).plugin;
  66463. };
  66464. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66465. return !!SceneLoader._registeredPlugins[extension];
  66466. };
  66467. SceneLoader.RegisterPlugin = function (plugin) {
  66468. if (typeof plugin.extensions === "string") {
  66469. var extension = plugin.extensions;
  66470. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66471. plugin: plugin,
  66472. isBinary: false
  66473. };
  66474. }
  66475. else {
  66476. var extensions = plugin.extensions;
  66477. Object.keys(extensions).forEach(function (extension) {
  66478. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66479. plugin: plugin,
  66480. isBinary: extensions[extension].isBinary
  66481. };
  66482. });
  66483. }
  66484. };
  66485. /**
  66486. * Import meshes into a scene
  66487. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66488. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66489. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66490. * @param scene the instance of BABYLON.Scene to append to
  66491. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66492. * @param onProgress a callback with a progress event for each file being loaded
  66493. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66494. * @param pluginExtension the extension used to determine the plugin
  66495. * @returns The loaded plugin
  66496. */
  66497. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66498. if (sceneFilename === void 0) { sceneFilename = ""; }
  66499. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66500. if (onSuccess === void 0) { onSuccess = null; }
  66501. if (onProgress === void 0) { onProgress = null; }
  66502. if (onError === void 0) { onError = null; }
  66503. if (pluginExtension === void 0) { pluginExtension = null; }
  66504. if (!scene) {
  66505. BABYLON.Tools.Error("No scene available to import mesh to");
  66506. return null;
  66507. }
  66508. if (!sceneFilename) {
  66509. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66510. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66511. }
  66512. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66513. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66514. return null;
  66515. }
  66516. var loadingToken = {};
  66517. scene._addPendingData(loadingToken);
  66518. var disposeHandler = function () {
  66519. scene._removePendingData(loadingToken);
  66520. };
  66521. var errorHandler = function (message, exception) {
  66522. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66523. if (onError) {
  66524. onError(scene, errorMessage, exception);
  66525. }
  66526. else {
  66527. BABYLON.Tools.Error(errorMessage);
  66528. // should the exception be thrown?
  66529. }
  66530. disposeHandler();
  66531. };
  66532. var progressHandler = onProgress ? function (event) {
  66533. try {
  66534. onProgress(event);
  66535. }
  66536. catch (e) {
  66537. errorHandler("Error in onProgress callback", e);
  66538. }
  66539. } : undefined;
  66540. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66541. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66542. if (onSuccess) {
  66543. try {
  66544. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66545. }
  66546. catch (e) {
  66547. errorHandler("Error in onSuccess callback", e);
  66548. }
  66549. }
  66550. scene._removePendingData(loadingToken);
  66551. };
  66552. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66553. if (plugin.rewriteRootURL) {
  66554. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66555. }
  66556. if (sceneFilename === "") {
  66557. if (sceneFilename === "") {
  66558. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66559. }
  66560. }
  66561. if (plugin.importMesh) {
  66562. var syncedPlugin = plugin;
  66563. var meshes = new Array();
  66564. var particleSystems = new Array();
  66565. var skeletons = new Array();
  66566. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66567. return;
  66568. }
  66569. scene.loadingPluginName = plugin.name;
  66570. successHandler(meshes, particleSystems, skeletons, []);
  66571. }
  66572. else {
  66573. var asyncedPlugin = plugin;
  66574. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66575. scene.loadingPluginName = plugin.name;
  66576. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66577. }).catch(function (error) {
  66578. errorHandler(error.message, error);
  66579. });
  66580. }
  66581. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66582. };
  66583. /**
  66584. * Import meshes into a scene
  66585. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66586. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66587. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66588. * @param scene the instance of BABYLON.Scene to append to
  66589. * @param onProgress a callback with a progress event for each file being loaded
  66590. * @param pluginExtension the extension used to determine the plugin
  66591. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66592. */
  66593. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66594. if (sceneFilename === void 0) { sceneFilename = ""; }
  66595. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66596. if (onProgress === void 0) { onProgress = null; }
  66597. if (pluginExtension === void 0) { pluginExtension = null; }
  66598. return new Promise(function (resolve, reject) {
  66599. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66600. resolve({
  66601. meshes: meshes,
  66602. particleSystems: particleSystems,
  66603. skeletons: skeletons,
  66604. animationGroups: animationGroups
  66605. });
  66606. }, onProgress, function (scene, message, exception) {
  66607. reject(exception || new Error(message));
  66608. }, pluginExtension);
  66609. });
  66610. };
  66611. /**
  66612. * Load a scene
  66613. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66614. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66615. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66616. * @param onSuccess a callback with the scene when import succeeds
  66617. * @param onProgress a callback with a progress event for each file being loaded
  66618. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66619. * @param pluginExtension the extension used to determine the plugin
  66620. * @returns The loaded plugin
  66621. */
  66622. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66623. if (onSuccess === void 0) { onSuccess = null; }
  66624. if (onProgress === void 0) { onProgress = null; }
  66625. if (onError === void 0) { onError = null; }
  66626. if (pluginExtension === void 0) { pluginExtension = null; }
  66627. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66628. };
  66629. /**
  66630. * Load a scene
  66631. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66632. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66633. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66634. * @param onProgress a callback with a progress event for each file being loaded
  66635. * @param pluginExtension the extension used to determine the plugin
  66636. * @returns The loaded scene
  66637. */
  66638. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66639. if (onProgress === void 0) { onProgress = null; }
  66640. if (pluginExtension === void 0) { pluginExtension = null; }
  66641. return new Promise(function (resolve, reject) {
  66642. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66643. resolve(scene);
  66644. }, onProgress, function (scene, message, exception) {
  66645. reject(exception || new Error(message));
  66646. }, pluginExtension);
  66647. });
  66648. };
  66649. /**
  66650. * Append a scene
  66651. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66652. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66653. * @param scene is the instance of BABYLON.Scene to append to
  66654. * @param onSuccess a callback with the scene when import succeeds
  66655. * @param onProgress a callback with a progress event for each file being loaded
  66656. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66657. * @param pluginExtension the extension used to determine the plugin
  66658. * @returns The loaded plugin
  66659. */
  66660. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66661. if (sceneFilename === void 0) { sceneFilename = ""; }
  66662. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66663. if (onSuccess === void 0) { onSuccess = null; }
  66664. if (onProgress === void 0) { onProgress = null; }
  66665. if (onError === void 0) { onError = null; }
  66666. if (pluginExtension === void 0) { pluginExtension = null; }
  66667. if (!scene) {
  66668. BABYLON.Tools.Error("No scene available to append to");
  66669. return null;
  66670. }
  66671. if (!sceneFilename) {
  66672. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66673. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66674. }
  66675. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66676. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66677. return null;
  66678. }
  66679. if (SceneLoader.ShowLoadingScreen) {
  66680. scene.getEngine().displayLoadingUI();
  66681. }
  66682. var loadingToken = {};
  66683. scene._addPendingData(loadingToken);
  66684. var disposeHandler = function () {
  66685. scene._removePendingData(loadingToken);
  66686. scene.getEngine().hideLoadingUI();
  66687. };
  66688. var errorHandler = function (message, exception) {
  66689. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66690. if (onError) {
  66691. onError(scene, errorMessage, exception);
  66692. }
  66693. else {
  66694. BABYLON.Tools.Error(errorMessage);
  66695. // should the exception be thrown?
  66696. }
  66697. disposeHandler();
  66698. };
  66699. var progressHandler = onProgress ? function (event) {
  66700. try {
  66701. onProgress(event);
  66702. }
  66703. catch (e) {
  66704. errorHandler("Error in onProgress callback", e);
  66705. }
  66706. } : undefined;
  66707. var successHandler = function () {
  66708. if (onSuccess) {
  66709. try {
  66710. onSuccess(scene);
  66711. }
  66712. catch (e) {
  66713. errorHandler("Error in onSuccess callback", e);
  66714. }
  66715. }
  66716. scene._removePendingData(loadingToken);
  66717. };
  66718. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66719. if (sceneFilename === "") {
  66720. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66721. }
  66722. if (plugin.load) {
  66723. var syncedPlugin = plugin;
  66724. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66725. return;
  66726. }
  66727. scene.loadingPluginName = plugin.name;
  66728. successHandler();
  66729. }
  66730. else {
  66731. var asyncedPlugin = plugin;
  66732. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66733. scene.loadingPluginName = plugin.name;
  66734. successHandler();
  66735. }).catch(function (error) {
  66736. errorHandler(error.message, error);
  66737. });
  66738. }
  66739. if (SceneLoader.ShowLoadingScreen) {
  66740. scene.executeWhenReady(function () {
  66741. scene.getEngine().hideLoadingUI();
  66742. });
  66743. }
  66744. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66745. };
  66746. /**
  66747. * Append a scene
  66748. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66749. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66750. * @param scene is the instance of BABYLON.Scene to append to
  66751. * @param onProgress a callback with a progress event for each file being loaded
  66752. * @param pluginExtension the extension used to determine the plugin
  66753. * @returns The given scene
  66754. */
  66755. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66756. if (sceneFilename === void 0) { sceneFilename = ""; }
  66757. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66758. if (onProgress === void 0) { onProgress = null; }
  66759. if (pluginExtension === void 0) { pluginExtension = null; }
  66760. return new Promise(function (resolve, reject) {
  66761. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66762. resolve(scene);
  66763. }, onProgress, function (scene, message, exception) {
  66764. reject(exception || new Error(message));
  66765. }, pluginExtension);
  66766. });
  66767. };
  66768. /**
  66769. * Load a scene into an asset container
  66770. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66771. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66772. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  66773. * @param onSuccess a callback with the scene when import succeeds
  66774. * @param onProgress a callback with a progress event for each file being loaded
  66775. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66776. * @param pluginExtension the extension used to determine the plugin
  66777. * @returns The loaded plugin
  66778. */
  66779. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66780. if (sceneFilename === void 0) { sceneFilename = ""; }
  66781. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66782. if (onSuccess === void 0) { onSuccess = null; }
  66783. if (onProgress === void 0) { onProgress = null; }
  66784. if (onError === void 0) { onError = null; }
  66785. if (pluginExtension === void 0) { pluginExtension = null; }
  66786. if (!scene) {
  66787. BABYLON.Tools.Error("No scene available to load asset container to");
  66788. return null;
  66789. }
  66790. if (!sceneFilename) {
  66791. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66792. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66793. }
  66794. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66795. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66796. return null;
  66797. }
  66798. var loadingToken = {};
  66799. scene._addPendingData(loadingToken);
  66800. var disposeHandler = function () {
  66801. scene._removePendingData(loadingToken);
  66802. };
  66803. var errorHandler = function (message, exception) {
  66804. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66805. if (onError) {
  66806. onError(scene, errorMessage, exception);
  66807. }
  66808. else {
  66809. BABYLON.Tools.Error(errorMessage);
  66810. // should the exception be thrown?
  66811. }
  66812. disposeHandler();
  66813. };
  66814. var progressHandler = onProgress ? function (event) {
  66815. try {
  66816. onProgress(event);
  66817. }
  66818. catch (e) {
  66819. errorHandler("Error in onProgress callback", e);
  66820. }
  66821. } : undefined;
  66822. var successHandler = function (assets) {
  66823. if (onSuccess) {
  66824. try {
  66825. onSuccess(assets);
  66826. }
  66827. catch (e) {
  66828. errorHandler("Error in onSuccess callback", e);
  66829. }
  66830. }
  66831. scene._removePendingData(loadingToken);
  66832. };
  66833. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66834. if (plugin.loadAssetContainer) {
  66835. var syncedPlugin = plugin;
  66836. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66837. if (!assetContainer) {
  66838. return;
  66839. }
  66840. scene.loadingPluginName = plugin.name;
  66841. successHandler(assetContainer);
  66842. }
  66843. else if (plugin.loadAssetContainerAsync) {
  66844. var asyncedPlugin = plugin;
  66845. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66846. scene.loadingPluginName = plugin.name;
  66847. successHandler(assetContainer);
  66848. }).catch(function (error) {
  66849. errorHandler(error.message, error);
  66850. });
  66851. }
  66852. else {
  66853. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66854. }
  66855. if (SceneLoader.ShowLoadingScreen) {
  66856. scene.executeWhenReady(function () {
  66857. scene.getEngine().hideLoadingUI();
  66858. });
  66859. }
  66860. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66861. };
  66862. /**
  66863. * Load a scene into an asset container
  66864. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66865. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66866. * @param scene is the instance of BABYLON.Scene to append to
  66867. * @param onProgress a callback with a progress event for each file being loaded
  66868. * @param pluginExtension the extension used to determine the plugin
  66869. * @returns The loaded asset container
  66870. */
  66871. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66872. if (sceneFilename === void 0) { sceneFilename = ""; }
  66873. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66874. if (onProgress === void 0) { onProgress = null; }
  66875. if (pluginExtension === void 0) { pluginExtension = null; }
  66876. return new Promise(function (resolve, reject) {
  66877. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66878. resolve(assetContainer);
  66879. }, onProgress, function (scene, message, exception) {
  66880. reject(exception || new Error(message));
  66881. }, pluginExtension);
  66882. });
  66883. };
  66884. // Flags
  66885. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66886. SceneLoader._ShowLoadingScreen = true;
  66887. SceneLoader._CleanBoneMatrixWeights = false;
  66888. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66889. // Members
  66890. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66891. SceneLoader._registeredPlugins = {};
  66892. return SceneLoader;
  66893. }());
  66894. BABYLON.SceneLoader = SceneLoader;
  66895. ;
  66896. })(BABYLON || (BABYLON = {}));
  66897. //# sourceMappingURL=babylon.sceneLoader.js.map
  66898. var BABYLON;
  66899. (function (BABYLON) {
  66900. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66901. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66902. var parsedMaterial = parsedData.materials[index];
  66903. if (parsedMaterial.id === id) {
  66904. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66905. }
  66906. }
  66907. return null;
  66908. };
  66909. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66910. for (var i in names) {
  66911. if (mesh.name === names[i]) {
  66912. hierarchyIds.push(mesh.id);
  66913. return true;
  66914. }
  66915. }
  66916. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66917. hierarchyIds.push(mesh.id);
  66918. return true;
  66919. }
  66920. return false;
  66921. };
  66922. var logOperation = function (operation, producer) {
  66923. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66924. };
  66925. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66926. if (addToScene === void 0) { addToScene = false; }
  66927. var container = new BABYLON.AssetContainer(scene);
  66928. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66929. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66930. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66931. // and avoid problems with multiple concurrent .babylon loads.
  66932. var log = "importScene has failed JSON parse";
  66933. try {
  66934. var parsedData = JSON.parse(data);
  66935. log = "";
  66936. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66937. var index;
  66938. var cache;
  66939. // Lights
  66940. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66941. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66942. var parsedLight = parsedData.lights[index];
  66943. var light = BABYLON.Light.Parse(parsedLight, scene);
  66944. if (light) {
  66945. container.lights.push(light);
  66946. log += (index === 0 ? "\n\tLights:" : "");
  66947. log += "\n\t\t" + light.toString(fullDetails);
  66948. }
  66949. }
  66950. }
  66951. // Animations
  66952. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66953. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66954. var parsedAnimation = parsedData.animations[index];
  66955. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66956. scene.animations.push(animation);
  66957. container.animations.push(animation);
  66958. log += (index === 0 ? "\n\tAnimations:" : "");
  66959. log += "\n\t\t" + animation.toString(fullDetails);
  66960. }
  66961. }
  66962. // Materials
  66963. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66964. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66965. var parsedMaterial = parsedData.materials[index];
  66966. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66967. container.materials.push(mat);
  66968. log += (index === 0 ? "\n\tMaterials:" : "");
  66969. log += "\n\t\t" + mat.toString(fullDetails);
  66970. }
  66971. }
  66972. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66973. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66974. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66975. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66976. container.multiMaterials.push(mmat);
  66977. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66978. log += "\n\t\t" + mmat.toString(fullDetails);
  66979. }
  66980. }
  66981. // Morph targets
  66982. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66983. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66984. var managerData = _a[_i];
  66985. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66986. }
  66987. }
  66988. // Skeletons
  66989. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66990. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66991. var parsedSkeleton = parsedData.skeletons[index];
  66992. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66993. container.skeletons.push(skeleton);
  66994. log += (index === 0 ? "\n\tSkeletons:" : "");
  66995. log += "\n\t\t" + skeleton.toString(fullDetails);
  66996. }
  66997. }
  66998. // Geometries
  66999. var geometries = parsedData.geometries;
  67000. if (geometries !== undefined && geometries !== null) {
  67001. var addedGeometry = new Array();
  67002. // Boxes
  67003. var boxes = geometries.boxes;
  67004. if (boxes !== undefined && boxes !== null) {
  67005. for (index = 0, cache = boxes.length; index < cache; index++) {
  67006. var parsedBox = boxes[index];
  67007. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67008. }
  67009. }
  67010. // Spheres
  67011. var spheres = geometries.spheres;
  67012. if (spheres !== undefined && spheres !== null) {
  67013. for (index = 0, cache = spheres.length; index < cache; index++) {
  67014. var parsedSphere = spheres[index];
  67015. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67016. }
  67017. }
  67018. // Cylinders
  67019. var cylinders = geometries.cylinders;
  67020. if (cylinders !== undefined && cylinders !== null) {
  67021. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67022. var parsedCylinder = cylinders[index];
  67023. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67024. }
  67025. }
  67026. // Toruses
  67027. var toruses = geometries.toruses;
  67028. if (toruses !== undefined && toruses !== null) {
  67029. for (index = 0, cache = toruses.length; index < cache; index++) {
  67030. var parsedTorus = toruses[index];
  67031. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67032. }
  67033. }
  67034. // Grounds
  67035. var grounds = geometries.grounds;
  67036. if (grounds !== undefined && grounds !== null) {
  67037. for (index = 0, cache = grounds.length; index < cache; index++) {
  67038. var parsedGround = grounds[index];
  67039. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67040. }
  67041. }
  67042. // Planes
  67043. var planes = geometries.planes;
  67044. if (planes !== undefined && planes !== null) {
  67045. for (index = 0, cache = planes.length; index < cache; index++) {
  67046. var parsedPlane = planes[index];
  67047. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67048. }
  67049. }
  67050. // TorusKnots
  67051. var torusKnots = geometries.torusKnots;
  67052. if (torusKnots !== undefined && torusKnots !== null) {
  67053. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67054. var parsedTorusKnot = torusKnots[index];
  67055. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67056. }
  67057. }
  67058. // VertexData
  67059. var vertexData = geometries.vertexData;
  67060. if (vertexData !== undefined && vertexData !== null) {
  67061. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67062. var parsedVertexData = vertexData[index];
  67063. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67064. }
  67065. }
  67066. addedGeometry.forEach(function (g) {
  67067. if (g) {
  67068. container.geometries.push(g);
  67069. }
  67070. });
  67071. }
  67072. // Transform nodes
  67073. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67074. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67075. var parsedTransformNode = parsedData.transformNodes[index];
  67076. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67077. container.transformNodes.push(node);
  67078. }
  67079. }
  67080. // Meshes
  67081. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67082. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67083. var parsedMesh = parsedData.meshes[index];
  67084. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67085. container.meshes.push(mesh);
  67086. log += (index === 0 ? "\n\tMeshes:" : "");
  67087. log += "\n\t\t" + mesh.toString(fullDetails);
  67088. }
  67089. }
  67090. // Cameras
  67091. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67092. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67093. var parsedCamera = parsedData.cameras[index];
  67094. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67095. container.cameras.push(camera);
  67096. log += (index === 0 ? "\n\tCameras:" : "");
  67097. log += "\n\t\t" + camera.toString(fullDetails);
  67098. }
  67099. }
  67100. // Browsing all the graph to connect the dots
  67101. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67102. var camera = scene.cameras[index];
  67103. if (camera._waitingParentId) {
  67104. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67105. camera._waitingParentId = null;
  67106. }
  67107. }
  67108. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67109. var light_1 = scene.lights[index];
  67110. if (light_1 && light_1._waitingParentId) {
  67111. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67112. light_1._waitingParentId = null;
  67113. }
  67114. }
  67115. // Sounds
  67116. // TODO: add sound
  67117. var loadedSounds = [];
  67118. var loadedSound;
  67119. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67120. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67121. var parsedSound = parsedData.sounds[index];
  67122. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67123. if (!parsedSound.url)
  67124. parsedSound.url = parsedSound.name;
  67125. if (!loadedSounds[parsedSound.url]) {
  67126. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67127. loadedSounds[parsedSound.url] = loadedSound;
  67128. container.sounds.push(loadedSound);
  67129. }
  67130. else {
  67131. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67132. }
  67133. }
  67134. else {
  67135. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67136. }
  67137. }
  67138. }
  67139. loadedSounds = [];
  67140. // Connect parents & children and parse actions
  67141. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67142. var transformNode = scene.transformNodes[index];
  67143. if (transformNode._waitingParentId) {
  67144. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67145. transformNode._waitingParentId = null;
  67146. }
  67147. }
  67148. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67149. var mesh = scene.meshes[index];
  67150. if (mesh._waitingParentId) {
  67151. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67152. mesh._waitingParentId = null;
  67153. }
  67154. if (mesh._waitingActions) {
  67155. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67156. mesh._waitingActions = null;
  67157. }
  67158. }
  67159. // freeze world matrix application
  67160. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67161. var currentMesh = scene.meshes[index];
  67162. if (currentMesh._waitingFreezeWorldMatrix) {
  67163. currentMesh.freezeWorldMatrix();
  67164. currentMesh._waitingFreezeWorldMatrix = null;
  67165. }
  67166. else {
  67167. currentMesh.computeWorldMatrix(true);
  67168. }
  67169. }
  67170. // Particles Systems
  67171. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67172. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67173. var parsedParticleSystem = parsedData.particleSystems[index];
  67174. if (parsedParticleSystem.activeParticleCount) {
  67175. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67176. container.particleSystems.push(ps);
  67177. }
  67178. else {
  67179. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67180. container.particleSystems.push(ps);
  67181. }
  67182. }
  67183. }
  67184. // Lens flares
  67185. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67186. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67187. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67188. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67189. container.lensFlareSystems.push(lf);
  67190. }
  67191. }
  67192. // Shadows
  67193. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67194. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67195. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67196. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67197. container.shadowGenerators.push(sg);
  67198. }
  67199. }
  67200. // Lights exclusions / inclusions
  67201. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67202. var light_2 = scene.lights[index];
  67203. // Excluded check
  67204. if (light_2._excludedMeshesIds.length > 0) {
  67205. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67206. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67207. if (excludedMesh) {
  67208. light_2.excludedMeshes.push(excludedMesh);
  67209. }
  67210. }
  67211. light_2._excludedMeshesIds = [];
  67212. }
  67213. // Included check
  67214. if (light_2._includedOnlyMeshesIds.length > 0) {
  67215. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67216. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67217. if (includedOnlyMesh) {
  67218. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67219. }
  67220. }
  67221. light_2._includedOnlyMeshesIds = [];
  67222. }
  67223. }
  67224. // Effect layers
  67225. if (parsedData.effectLayers) {
  67226. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67227. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67228. container.effectLayers.push(effectLayer);
  67229. }
  67230. }
  67231. // Actions (scene)
  67232. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67233. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67234. }
  67235. if (!addToScene) {
  67236. container.removeAllFromScene();
  67237. }
  67238. }
  67239. catch (err) {
  67240. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67241. if (onError) {
  67242. onError(msg, err);
  67243. }
  67244. else {
  67245. BABYLON.Tools.Log(msg);
  67246. throw err;
  67247. }
  67248. }
  67249. finally {
  67250. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67251. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67252. }
  67253. }
  67254. return container;
  67255. };
  67256. BABYLON.SceneLoader.RegisterPlugin({
  67257. name: "babylon.js",
  67258. extensions: ".babylon",
  67259. canDirectLoad: function (data) {
  67260. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67261. return true;
  67262. }
  67263. return false;
  67264. },
  67265. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67266. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67267. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67268. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67269. // and avoid problems with multiple concurrent .babylon loads.
  67270. var log = "importMesh has failed JSON parse";
  67271. try {
  67272. var parsedData = JSON.parse(data);
  67273. log = "";
  67274. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67275. if (!meshesNames) {
  67276. meshesNames = null;
  67277. }
  67278. else if (!Array.isArray(meshesNames)) {
  67279. meshesNames = [meshesNames];
  67280. }
  67281. var hierarchyIds = new Array();
  67282. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67283. var loadedSkeletonsIds = [];
  67284. var loadedMaterialsIds = [];
  67285. var index;
  67286. var cache;
  67287. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67288. var parsedMesh = parsedData.meshes[index];
  67289. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67290. if (meshesNames !== null) {
  67291. // Remove found mesh name from list.
  67292. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67293. }
  67294. //Geometry?
  67295. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67296. //does the file contain geometries?
  67297. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67298. //find the correct geometry and add it to the scene
  67299. var found = false;
  67300. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67301. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67302. return;
  67303. }
  67304. else {
  67305. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67306. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67307. switch (geometryType) {
  67308. case "boxes":
  67309. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67310. break;
  67311. case "spheres":
  67312. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67313. break;
  67314. case "cylinders":
  67315. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67316. break;
  67317. case "toruses":
  67318. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67319. break;
  67320. case "grounds":
  67321. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67322. break;
  67323. case "planes":
  67324. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67325. break;
  67326. case "torusKnots":
  67327. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67328. break;
  67329. case "vertexData":
  67330. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67331. break;
  67332. }
  67333. found = true;
  67334. }
  67335. });
  67336. }
  67337. });
  67338. if (found === false) {
  67339. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67340. }
  67341. }
  67342. }
  67343. // Material ?
  67344. if (parsedMesh.materialId) {
  67345. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67346. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67347. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67348. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67349. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67350. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67351. var subMatId = parsedMultiMaterial.materials[matIndex];
  67352. loadedMaterialsIds.push(subMatId);
  67353. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67354. if (mat) {
  67355. log += "\n\tMaterial " + mat.toString(fullDetails);
  67356. }
  67357. }
  67358. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67359. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67360. if (mmat) {
  67361. materialFound = true;
  67362. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67363. }
  67364. break;
  67365. }
  67366. }
  67367. }
  67368. if (materialFound === false) {
  67369. loadedMaterialsIds.push(parsedMesh.materialId);
  67370. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67371. if (!mat) {
  67372. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67373. }
  67374. else {
  67375. log += "\n\tMaterial " + mat.toString(fullDetails);
  67376. }
  67377. }
  67378. }
  67379. // Skeleton ?
  67380. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67381. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67382. if (skeletonAlreadyLoaded === false) {
  67383. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67384. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67385. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67386. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67387. skeletons.push(skeleton);
  67388. loadedSkeletonsIds.push(parsedSkeleton.id);
  67389. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67390. }
  67391. }
  67392. }
  67393. }
  67394. // Morph targets ?
  67395. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67396. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67397. var managerData = _a[_i];
  67398. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67399. }
  67400. }
  67401. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67402. meshes.push(mesh);
  67403. log += "\n\tMesh " + mesh.toString(fullDetails);
  67404. }
  67405. }
  67406. // Connecting parents
  67407. var currentMesh;
  67408. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67409. currentMesh = scene.meshes[index];
  67410. if (currentMesh._waitingParentId) {
  67411. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67412. currentMesh._waitingParentId = null;
  67413. }
  67414. }
  67415. // freeze and compute world matrix application
  67416. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67417. currentMesh = scene.meshes[index];
  67418. if (currentMesh._waitingFreezeWorldMatrix) {
  67419. currentMesh.freezeWorldMatrix();
  67420. currentMesh._waitingFreezeWorldMatrix = null;
  67421. }
  67422. else {
  67423. currentMesh.computeWorldMatrix(true);
  67424. }
  67425. }
  67426. }
  67427. // Particles
  67428. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67429. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67430. var parsedParticleSystem = parsedData.particleSystems[index];
  67431. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67432. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67433. }
  67434. }
  67435. }
  67436. return true;
  67437. }
  67438. catch (err) {
  67439. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67440. if (onError) {
  67441. onError(msg, err);
  67442. }
  67443. else {
  67444. BABYLON.Tools.Log(msg);
  67445. throw err;
  67446. }
  67447. }
  67448. finally {
  67449. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67450. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67451. }
  67452. }
  67453. return false;
  67454. },
  67455. load: function (scene, data, rootUrl, onError) {
  67456. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67457. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67458. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67459. // and avoid problems with multiple concurrent .babylon loads.
  67460. var log = "importScene has failed JSON parse";
  67461. try {
  67462. var parsedData = JSON.parse(data);
  67463. log = "";
  67464. // Scene
  67465. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67466. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67467. }
  67468. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67469. scene.autoClear = parsedData.autoClear;
  67470. }
  67471. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67472. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67473. }
  67474. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67475. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67476. }
  67477. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67478. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67479. }
  67480. // Fog
  67481. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67482. scene.fogMode = parsedData.fogMode;
  67483. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67484. scene.fogStart = parsedData.fogStart;
  67485. scene.fogEnd = parsedData.fogEnd;
  67486. scene.fogDensity = parsedData.fogDensity;
  67487. log += "\tFog mode for scene: ";
  67488. switch (scene.fogMode) {
  67489. // getters not compiling, so using hardcoded
  67490. case 1:
  67491. log += "exp\n";
  67492. break;
  67493. case 2:
  67494. log += "exp2\n";
  67495. break;
  67496. case 3:
  67497. log += "linear\n";
  67498. break;
  67499. }
  67500. }
  67501. //Physics
  67502. if (parsedData.physicsEnabled) {
  67503. var physicsPlugin;
  67504. if (parsedData.physicsEngine === "cannon") {
  67505. physicsPlugin = new BABYLON.CannonJSPlugin();
  67506. }
  67507. else if (parsedData.physicsEngine === "oimo") {
  67508. physicsPlugin = new BABYLON.OimoJSPlugin();
  67509. }
  67510. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67511. //else - default engine, which is currently oimo
  67512. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67513. scene.enablePhysics(physicsGravity, physicsPlugin);
  67514. }
  67515. // Metadata
  67516. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67517. scene.metadata = parsedData.metadata;
  67518. }
  67519. //collisions, if defined. otherwise, default is true
  67520. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67521. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67522. }
  67523. scene.workerCollisions = !!parsedData.workerCollisions;
  67524. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67525. if (!container) {
  67526. return false;
  67527. }
  67528. if (parsedData.autoAnimate) {
  67529. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67530. }
  67531. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67532. scene.setActiveCameraByID(parsedData.activeCameraID);
  67533. }
  67534. // Environment texture
  67535. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67536. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67537. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67538. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67539. if (parsedData.environmentTextureRotationY) {
  67540. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67541. }
  67542. scene.environmentTexture = hdrTexture;
  67543. }
  67544. else {
  67545. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67546. if (parsedData.environmentTextureRotationY) {
  67547. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67548. }
  67549. scene.environmentTexture = cubeTexture;
  67550. }
  67551. if (parsedData.createDefaultSkybox === true) {
  67552. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67553. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67554. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67555. }
  67556. }
  67557. // Finish
  67558. return true;
  67559. }
  67560. catch (err) {
  67561. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67562. if (onError) {
  67563. onError(msg, err);
  67564. }
  67565. else {
  67566. BABYLON.Tools.Log(msg);
  67567. throw err;
  67568. }
  67569. }
  67570. finally {
  67571. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67572. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67573. }
  67574. }
  67575. return false;
  67576. },
  67577. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67578. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67579. return container;
  67580. }
  67581. });
  67582. })(BABYLON || (BABYLON = {}));
  67583. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67584. var BABYLON;
  67585. (function (BABYLON) {
  67586. var FilesInput = /** @class */ (function () {
  67587. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67588. this.onProcessFileCallback = function () { return true; };
  67589. this._engine = engine;
  67590. this._currentScene = scene;
  67591. this._sceneLoadedCallback = sceneLoadedCallback;
  67592. this._progressCallback = progressCallback;
  67593. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67594. this._textureLoadingCallback = textureLoadingCallback;
  67595. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67596. this._onReloadCallback = onReloadCallback;
  67597. this._errorCallback = errorCallback;
  67598. }
  67599. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67600. var _this = this;
  67601. if (elementToMonitor) {
  67602. this._elementToMonitor = elementToMonitor;
  67603. this._dragEnterHandler = function (e) { _this.drag(e); };
  67604. this._dragOverHandler = function (e) { _this.drag(e); };
  67605. this._dropHandler = function (e) { _this.drop(e); };
  67606. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67607. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67608. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67609. }
  67610. };
  67611. FilesInput.prototype.dispose = function () {
  67612. if (!this._elementToMonitor) {
  67613. return;
  67614. }
  67615. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67616. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67617. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67618. };
  67619. FilesInput.prototype.renderFunction = function () {
  67620. if (this._additionalRenderLoopLogicCallback) {
  67621. this._additionalRenderLoopLogicCallback();
  67622. }
  67623. if (this._currentScene) {
  67624. if (this._textureLoadingCallback) {
  67625. var remaining = this._currentScene.getWaitingItemsCount();
  67626. if (remaining > 0) {
  67627. this._textureLoadingCallback(remaining);
  67628. }
  67629. }
  67630. this._currentScene.render();
  67631. }
  67632. };
  67633. FilesInput.prototype.drag = function (e) {
  67634. e.stopPropagation();
  67635. e.preventDefault();
  67636. };
  67637. FilesInput.prototype.drop = function (eventDrop) {
  67638. eventDrop.stopPropagation();
  67639. eventDrop.preventDefault();
  67640. this.loadFiles(eventDrop);
  67641. };
  67642. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67643. var _this = this;
  67644. var reader = folder.createReader();
  67645. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67646. reader.readEntries(function (entries) {
  67647. remaining.count += entries.length;
  67648. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67649. var entry = entries_1[_i];
  67650. if (entry.isFile) {
  67651. entry.file(function (file) {
  67652. file.correctName = relativePath + file.name;
  67653. files.push(file);
  67654. if (--remaining.count === 0) {
  67655. callback();
  67656. }
  67657. });
  67658. }
  67659. else if (entry.isDirectory) {
  67660. _this._traverseFolder(entry, files, remaining, callback);
  67661. }
  67662. }
  67663. if (--remaining.count) {
  67664. callback();
  67665. }
  67666. });
  67667. };
  67668. FilesInput.prototype._processFiles = function (files) {
  67669. for (var i = 0; i < files.length; i++) {
  67670. var name = files[i].correctName.toLowerCase();
  67671. var extension = name.split('.').pop();
  67672. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67673. continue;
  67674. }
  67675. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67676. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67677. this._sceneFileToLoad = files[i];
  67678. }
  67679. else {
  67680. FilesInput.FilesToLoad[name] = files[i];
  67681. }
  67682. }
  67683. };
  67684. FilesInput.prototype.loadFiles = function (event) {
  67685. var _this = this;
  67686. if (this._startingProcessingFilesCallback)
  67687. this._startingProcessingFilesCallback();
  67688. // Handling data transfer via drag'n'drop
  67689. if (event && event.dataTransfer && event.dataTransfer.files) {
  67690. this._filesToLoad = event.dataTransfer.files;
  67691. }
  67692. // Handling files from input files
  67693. if (event && event.target && event.target.files) {
  67694. this._filesToLoad = event.target.files;
  67695. }
  67696. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67697. var files_1 = new Array();
  67698. var folders = [];
  67699. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67700. for (var i = 0; i < this._filesToLoad.length; i++) {
  67701. var fileToLoad = this._filesToLoad[i];
  67702. var name_1 = fileToLoad.name.toLowerCase();
  67703. var entry = void 0;
  67704. fileToLoad.correctName = name_1;
  67705. if (items) {
  67706. var item = items[i];
  67707. if (item.getAsEntry) {
  67708. entry = item.getAsEntry();
  67709. }
  67710. else if (item.webkitGetAsEntry) {
  67711. entry = item.webkitGetAsEntry();
  67712. }
  67713. }
  67714. if (!entry) {
  67715. files_1.push(fileToLoad);
  67716. }
  67717. else {
  67718. if (entry.isDirectory) {
  67719. folders.push(entry);
  67720. }
  67721. else {
  67722. files_1.push(fileToLoad);
  67723. }
  67724. }
  67725. }
  67726. if (folders.length === 0) {
  67727. this._processFiles(files_1);
  67728. this._processReload();
  67729. }
  67730. else {
  67731. var remaining = { count: folders.length };
  67732. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67733. var folder = folders_1[_i];
  67734. this._traverseFolder(folder, files_1, remaining, function () {
  67735. _this._processFiles(files_1);
  67736. if (remaining.count === 0) {
  67737. _this._processReload();
  67738. }
  67739. });
  67740. }
  67741. }
  67742. }
  67743. };
  67744. FilesInput.prototype._processReload = function () {
  67745. if (this._onReloadCallback) {
  67746. this._onReloadCallback(this._sceneFileToLoad);
  67747. }
  67748. else {
  67749. this.reload();
  67750. }
  67751. };
  67752. FilesInput.prototype.reload = function () {
  67753. var _this = this;
  67754. // If a scene file has been provided
  67755. if (this._sceneFileToLoad) {
  67756. if (this._currentScene) {
  67757. if (BABYLON.Tools.errorsCount > 0) {
  67758. BABYLON.Tools.ClearLogCache();
  67759. }
  67760. this._engine.stopRenderLoop();
  67761. }
  67762. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67763. if (_this._progressCallback) {
  67764. _this._progressCallback(progress);
  67765. }
  67766. }).then(function (scene) {
  67767. if (_this._currentScene) {
  67768. _this._currentScene.dispose();
  67769. }
  67770. _this._currentScene = scene;
  67771. if (_this._sceneLoadedCallback) {
  67772. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67773. }
  67774. // Wait for textures and shaders to be ready
  67775. _this._currentScene.executeWhenReady(function () {
  67776. _this._engine.runRenderLoop(function () {
  67777. _this.renderFunction();
  67778. });
  67779. });
  67780. }).catch(function (error) {
  67781. if (_this._errorCallback) {
  67782. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67783. }
  67784. });
  67785. }
  67786. else {
  67787. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67788. }
  67789. };
  67790. FilesInput.FilesToLoad = {};
  67791. return FilesInput;
  67792. }());
  67793. BABYLON.FilesInput = FilesInput;
  67794. })(BABYLON || (BABYLON = {}));
  67795. //# sourceMappingURL=babylon.filesInput.js.map
  67796. var BABYLON;
  67797. (function (BABYLON) {
  67798. /**
  67799. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67800. * The underlying implementation relies on an associative array to ensure the best performances.
  67801. * The value can be anything including 'null' but except 'undefined'
  67802. */
  67803. var StringDictionary = /** @class */ (function () {
  67804. function StringDictionary() {
  67805. this._count = 0;
  67806. this._data = {};
  67807. }
  67808. /**
  67809. * This will clear this dictionary and copy the content from the 'source' one.
  67810. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67811. * @param source the dictionary to take the content from and copy to this dictionary
  67812. */
  67813. StringDictionary.prototype.copyFrom = function (source) {
  67814. var _this = this;
  67815. this.clear();
  67816. source.forEach(function (t, v) { return _this.add(t, v); });
  67817. };
  67818. /**
  67819. * Get a value based from its key
  67820. * @param key the given key to get the matching value from
  67821. * @return the value if found, otherwise undefined is returned
  67822. */
  67823. StringDictionary.prototype.get = function (key) {
  67824. var val = this._data[key];
  67825. if (val !== undefined) {
  67826. return val;
  67827. }
  67828. return undefined;
  67829. };
  67830. /**
  67831. * Get a value from its key or add it if it doesn't exist.
  67832. * This method will ensure you that a given key/data will be present in the dictionary.
  67833. * @param key the given key to get the matching value from
  67834. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67835. * The factory will only be invoked if there's no data for the given key.
  67836. * @return the value corresponding to the key.
  67837. */
  67838. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67839. var val = this.get(key);
  67840. if (val !== undefined) {
  67841. return val;
  67842. }
  67843. val = factory(key);
  67844. if (val) {
  67845. this.add(key, val);
  67846. }
  67847. return val;
  67848. };
  67849. /**
  67850. * Get a value from its key if present in the dictionary otherwise add it
  67851. * @param key the key to get the value from
  67852. * @param val if there's no such key/value pair in the dictionary add it with this value
  67853. * @return the value corresponding to the key
  67854. */
  67855. StringDictionary.prototype.getOrAdd = function (key, val) {
  67856. var curVal = this.get(key);
  67857. if (curVal !== undefined) {
  67858. return curVal;
  67859. }
  67860. this.add(key, val);
  67861. return val;
  67862. };
  67863. /**
  67864. * Check if there's a given key in the dictionary
  67865. * @param key the key to check for
  67866. * @return true if the key is present, false otherwise
  67867. */
  67868. StringDictionary.prototype.contains = function (key) {
  67869. return this._data[key] !== undefined;
  67870. };
  67871. /**
  67872. * Add a new key and its corresponding value
  67873. * @param key the key to add
  67874. * @param value the value corresponding to the key
  67875. * @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
  67876. */
  67877. StringDictionary.prototype.add = function (key, value) {
  67878. if (this._data[key] !== undefined) {
  67879. return false;
  67880. }
  67881. this._data[key] = value;
  67882. ++this._count;
  67883. return true;
  67884. };
  67885. StringDictionary.prototype.set = function (key, value) {
  67886. if (this._data[key] === undefined) {
  67887. return false;
  67888. }
  67889. this._data[key] = value;
  67890. return true;
  67891. };
  67892. /**
  67893. * Get the element of the given key and remove it from the dictionary
  67894. * @param key
  67895. */
  67896. StringDictionary.prototype.getAndRemove = function (key) {
  67897. var val = this.get(key);
  67898. if (val !== undefined) {
  67899. delete this._data[key];
  67900. --this._count;
  67901. return val;
  67902. }
  67903. return null;
  67904. };
  67905. /**
  67906. * Remove a key/value from the dictionary.
  67907. * @param key the key to remove
  67908. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67909. */
  67910. StringDictionary.prototype.remove = function (key) {
  67911. if (this.contains(key)) {
  67912. delete this._data[key];
  67913. --this._count;
  67914. return true;
  67915. }
  67916. return false;
  67917. };
  67918. /**
  67919. * Clear the whole content of the dictionary
  67920. */
  67921. StringDictionary.prototype.clear = function () {
  67922. this._data = {};
  67923. this._count = 0;
  67924. };
  67925. Object.defineProperty(StringDictionary.prototype, "count", {
  67926. get: function () {
  67927. return this._count;
  67928. },
  67929. enumerable: true,
  67930. configurable: true
  67931. });
  67932. /**
  67933. * Execute a callback on each key/val of the dictionary.
  67934. * Note that you can remove any element in this dictionary in the callback implementation
  67935. * @param callback the callback to execute on a given key/value pair
  67936. */
  67937. StringDictionary.prototype.forEach = function (callback) {
  67938. for (var cur in this._data) {
  67939. var val = this._data[cur];
  67940. callback(cur, val);
  67941. }
  67942. };
  67943. /**
  67944. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67945. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67946. * Note that you can remove any element in this dictionary in the callback implementation
  67947. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67948. */
  67949. StringDictionary.prototype.first = function (callback) {
  67950. for (var cur in this._data) {
  67951. var val = this._data[cur];
  67952. var res = callback(cur, val);
  67953. if (res) {
  67954. return res;
  67955. }
  67956. }
  67957. return null;
  67958. };
  67959. return StringDictionary;
  67960. }());
  67961. BABYLON.StringDictionary = StringDictionary;
  67962. })(BABYLON || (BABYLON = {}));
  67963. //# sourceMappingURL=babylon.stringDictionary.js.map
  67964. var BABYLON;
  67965. (function (BABYLON) {
  67966. var Tags = /** @class */ (function () {
  67967. function Tags() {
  67968. }
  67969. Tags.EnableFor = function (obj) {
  67970. obj._tags = obj._tags || {};
  67971. obj.hasTags = function () {
  67972. return Tags.HasTags(obj);
  67973. };
  67974. obj.addTags = function (tagsString) {
  67975. return Tags.AddTagsTo(obj, tagsString);
  67976. };
  67977. obj.removeTags = function (tagsString) {
  67978. return Tags.RemoveTagsFrom(obj, tagsString);
  67979. };
  67980. obj.matchesTagsQuery = function (tagsQuery) {
  67981. return Tags.MatchesQuery(obj, tagsQuery);
  67982. };
  67983. };
  67984. Tags.DisableFor = function (obj) {
  67985. delete obj._tags;
  67986. delete obj.hasTags;
  67987. delete obj.addTags;
  67988. delete obj.removeTags;
  67989. delete obj.matchesTagsQuery;
  67990. };
  67991. Tags.HasTags = function (obj) {
  67992. if (!obj._tags) {
  67993. return false;
  67994. }
  67995. return !BABYLON.Tools.IsEmpty(obj._tags);
  67996. };
  67997. Tags.GetTags = function (obj, asString) {
  67998. if (asString === void 0) { asString = true; }
  67999. if (!obj._tags) {
  68000. return null;
  68001. }
  68002. if (asString) {
  68003. var tagsArray = [];
  68004. for (var tag in obj._tags) {
  68005. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68006. tagsArray.push(tag);
  68007. }
  68008. }
  68009. return tagsArray.join(" ");
  68010. }
  68011. else {
  68012. return obj._tags;
  68013. }
  68014. };
  68015. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68016. // a tag cannot start with '||', '&&', and '!'
  68017. // it cannot contain whitespaces
  68018. Tags.AddTagsTo = function (obj, tagsString) {
  68019. if (!tagsString) {
  68020. return;
  68021. }
  68022. if (typeof tagsString !== "string") {
  68023. return;
  68024. }
  68025. var tags = tagsString.split(" ");
  68026. tags.forEach(function (tag, index, array) {
  68027. Tags._AddTagTo(obj, tag);
  68028. });
  68029. };
  68030. Tags._AddTagTo = function (obj, tag) {
  68031. tag = tag.trim();
  68032. if (tag === "" || tag === "true" || tag === "false") {
  68033. return;
  68034. }
  68035. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68036. return;
  68037. }
  68038. Tags.EnableFor(obj);
  68039. obj._tags[tag] = true;
  68040. };
  68041. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68042. if (!Tags.HasTags(obj)) {
  68043. return;
  68044. }
  68045. var tags = tagsString.split(" ");
  68046. for (var t in tags) {
  68047. Tags._RemoveTagFrom(obj, tags[t]);
  68048. }
  68049. };
  68050. Tags._RemoveTagFrom = function (obj, tag) {
  68051. delete obj._tags[tag];
  68052. };
  68053. Tags.MatchesQuery = function (obj, tagsQuery) {
  68054. if (tagsQuery === undefined) {
  68055. return true;
  68056. }
  68057. if (tagsQuery === "") {
  68058. return Tags.HasTags(obj);
  68059. }
  68060. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68061. };
  68062. return Tags;
  68063. }());
  68064. BABYLON.Tags = Tags;
  68065. })(BABYLON || (BABYLON = {}));
  68066. //# sourceMappingURL=babylon.tags.js.map
  68067. var BABYLON;
  68068. (function (BABYLON) {
  68069. /**
  68070. * Class used to evalaute queries containing `and` and `or` operators
  68071. */
  68072. var AndOrNotEvaluator = /** @class */ (function () {
  68073. function AndOrNotEvaluator() {
  68074. }
  68075. /**
  68076. * Evaluate a query
  68077. * @param query defines the query to evaluate
  68078. * @param evaluateCallback defines the callback used to filter result
  68079. * @returns true if the query matches
  68080. */
  68081. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68082. if (!query.match(/\([^\(\)]*\)/g)) {
  68083. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68084. }
  68085. else {
  68086. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68087. // remove parenthesis
  68088. r = r.slice(1, r.length - 1);
  68089. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68090. });
  68091. }
  68092. if (query === "true") {
  68093. return true;
  68094. }
  68095. if (query === "false") {
  68096. return false;
  68097. }
  68098. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68099. };
  68100. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68101. evaluateCallback = evaluateCallback || (function (r) {
  68102. return r === "true" ? true : false;
  68103. });
  68104. var result;
  68105. var or = parenthesisContent.split("||");
  68106. for (var i in or) {
  68107. if (or.hasOwnProperty(i)) {
  68108. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68109. var and = ori.split("&&");
  68110. if (and.length > 1) {
  68111. for (var j = 0; j < and.length; ++j) {
  68112. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68113. if (andj !== "true" && andj !== "false") {
  68114. if (andj[0] === "!") {
  68115. result = !evaluateCallback(andj.substring(1));
  68116. }
  68117. else {
  68118. result = evaluateCallback(andj);
  68119. }
  68120. }
  68121. else {
  68122. result = andj === "true" ? true : false;
  68123. }
  68124. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68125. ori = "false";
  68126. break;
  68127. }
  68128. }
  68129. }
  68130. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68131. result = true;
  68132. break;
  68133. }
  68134. // result equals false (or undefined)
  68135. if (ori !== "true" && ori !== "false") {
  68136. if (ori[0] === "!") {
  68137. result = !evaluateCallback(ori.substring(1));
  68138. }
  68139. else {
  68140. result = evaluateCallback(ori);
  68141. }
  68142. }
  68143. else {
  68144. result = ori === "true" ? true : false;
  68145. }
  68146. }
  68147. }
  68148. // the whole parenthesis scope is replaced by 'true' or 'false'
  68149. return result ? "true" : "false";
  68150. };
  68151. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68152. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68153. // remove whitespaces
  68154. r = r.replace(/[\s]/g, function () { return ""; });
  68155. return r.length % 2 ? "!" : "";
  68156. });
  68157. booleanString = booleanString.trim();
  68158. if (booleanString === "!true") {
  68159. booleanString = "false";
  68160. }
  68161. else if (booleanString === "!false") {
  68162. booleanString = "true";
  68163. }
  68164. return booleanString;
  68165. };
  68166. return AndOrNotEvaluator;
  68167. }());
  68168. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68169. })(BABYLON || (BABYLON = {}));
  68170. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68171. var BABYLON;
  68172. (function (BABYLON) {
  68173. /**
  68174. * Class used to enable access to IndexedDB
  68175. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68176. */
  68177. var Database = /** @class */ (function () {
  68178. /**
  68179. * Creates a new Database
  68180. * @param urlToScene defines the url to load the scene
  68181. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68182. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68183. */
  68184. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68185. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68186. var _this = this;
  68187. // Handling various flavors of prefixed version of IndexedDB
  68188. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68189. this.callbackManifestChecked = callbackManifestChecked;
  68190. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68191. this.db = null;
  68192. this._enableSceneOffline = false;
  68193. this._enableTexturesOffline = false;
  68194. this.manifestVersionFound = 0;
  68195. this.mustUpdateRessources = false;
  68196. this.hasReachedQuota = false;
  68197. if (!Database.IDBStorageEnabled) {
  68198. this.callbackManifestChecked(true);
  68199. }
  68200. else {
  68201. if (disableManifestCheck) {
  68202. this._enableSceneOffline = true;
  68203. this._enableTexturesOffline = true;
  68204. this.manifestVersionFound = 1;
  68205. BABYLON.Tools.SetImmediate(function () {
  68206. _this.callbackManifestChecked(true);
  68207. });
  68208. }
  68209. else {
  68210. this._checkManifestFile();
  68211. }
  68212. }
  68213. }
  68214. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68215. /**
  68216. * Gets a boolean indicating if scene must be saved in the database
  68217. */
  68218. get: function () {
  68219. return this._enableSceneOffline;
  68220. },
  68221. enumerable: true,
  68222. configurable: true
  68223. });
  68224. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68225. /**
  68226. * Gets a boolean indicating if textures must be saved in the database
  68227. */
  68228. get: function () {
  68229. return this._enableTexturesOffline;
  68230. },
  68231. enumerable: true,
  68232. configurable: true
  68233. });
  68234. Database.prototype._checkManifestFile = function () {
  68235. var _this = this;
  68236. var noManifestFile = function () {
  68237. _this._enableSceneOffline = false;
  68238. _this._enableTexturesOffline = false;
  68239. _this.callbackManifestChecked(false);
  68240. };
  68241. var timeStampUsed = false;
  68242. var manifestURL = this.currentSceneUrl + ".manifest";
  68243. var xhr = new XMLHttpRequest();
  68244. if (navigator.onLine) {
  68245. // Adding a timestamp to by-pass browsers' cache
  68246. timeStampUsed = true;
  68247. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68248. }
  68249. xhr.open("GET", manifestURL, true);
  68250. xhr.addEventListener("load", function () {
  68251. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68252. try {
  68253. var manifestFile = JSON.parse(xhr.response);
  68254. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68255. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68256. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68257. _this.manifestVersionFound = manifestFile.version;
  68258. }
  68259. if (_this.callbackManifestChecked) {
  68260. _this.callbackManifestChecked(true);
  68261. }
  68262. }
  68263. catch (ex) {
  68264. noManifestFile();
  68265. }
  68266. }
  68267. else {
  68268. noManifestFile();
  68269. }
  68270. }, false);
  68271. xhr.addEventListener("error", function (event) {
  68272. if (timeStampUsed) {
  68273. timeStampUsed = false;
  68274. // Let's retry without the timeStamp
  68275. // It could fail when coupled with HTML5 Offline API
  68276. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68277. xhr.open("GET", retryManifestURL, true);
  68278. xhr.send();
  68279. }
  68280. else {
  68281. noManifestFile();
  68282. }
  68283. }, false);
  68284. try {
  68285. xhr.send();
  68286. }
  68287. catch (ex) {
  68288. BABYLON.Tools.Error("Error on XHR send request.");
  68289. this.callbackManifestChecked(false);
  68290. }
  68291. };
  68292. /**
  68293. * Open the database and make it available
  68294. * @param successCallback defines the callback to call on success
  68295. * @param errorCallback defines the callback to call on error
  68296. */
  68297. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68298. var _this = this;
  68299. var handleError = function () {
  68300. _this.isSupported = false;
  68301. if (errorCallback)
  68302. errorCallback();
  68303. };
  68304. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68305. // Your browser doesn't support IndexedDB
  68306. this.isSupported = false;
  68307. if (errorCallback)
  68308. errorCallback();
  68309. }
  68310. else {
  68311. // If the DB hasn't been opened or created yet
  68312. if (!this.db) {
  68313. this.hasReachedQuota = false;
  68314. this.isSupported = true;
  68315. var request = this.idbFactory.open("babylonjs", 1);
  68316. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68317. request.onerror = function (event) {
  68318. handleError();
  68319. };
  68320. // executes when a version change transaction cannot complete due to other active transactions
  68321. request.onblocked = function (event) {
  68322. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68323. handleError();
  68324. };
  68325. // DB has been opened successfully
  68326. request.onsuccess = function (event) {
  68327. _this.db = request.result;
  68328. successCallback();
  68329. };
  68330. // Initialization of the DB. Creating Scenes & Textures stores
  68331. request.onupgradeneeded = function (event) {
  68332. _this.db = (event.target).result;
  68333. if (_this.db) {
  68334. try {
  68335. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68336. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68337. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68338. }
  68339. catch (ex) {
  68340. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68341. handleError();
  68342. }
  68343. }
  68344. };
  68345. }
  68346. // DB has already been created and opened
  68347. else {
  68348. if (successCallback)
  68349. successCallback();
  68350. }
  68351. }
  68352. };
  68353. /**
  68354. * Loads an image from the database
  68355. * @param url defines the url to load from
  68356. * @param image defines the target DOM image
  68357. */
  68358. Database.prototype.loadImageFromDB = function (url, image) {
  68359. var _this = this;
  68360. var completeURL = Database._ReturnFullUrlLocation(url);
  68361. var saveAndLoadImage = function () {
  68362. if (!_this.hasReachedQuota && _this.db !== null) {
  68363. // the texture is not yet in the DB, let's try to save it
  68364. _this._saveImageIntoDBAsync(completeURL, image);
  68365. }
  68366. // If the texture is not in the DB and we've reached the DB quota limit
  68367. // let's load it directly from the web
  68368. else {
  68369. image.src = url;
  68370. }
  68371. };
  68372. if (!this.mustUpdateRessources) {
  68373. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68374. }
  68375. // First time we're download the images or update requested in the manifest file by a version change
  68376. else {
  68377. saveAndLoadImage();
  68378. }
  68379. };
  68380. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68381. if (this.isSupported && this.db !== null) {
  68382. var texture;
  68383. var transaction = this.db.transaction(["textures"]);
  68384. transaction.onabort = function (event) {
  68385. image.src = url;
  68386. };
  68387. transaction.oncomplete = function (event) {
  68388. var blobTextureURL;
  68389. if (texture) {
  68390. var URL = window.URL || window.webkitURL;
  68391. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68392. image.onerror = function () {
  68393. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68394. image.src = url;
  68395. };
  68396. image.src = blobTextureURL;
  68397. }
  68398. else {
  68399. notInDBCallback();
  68400. }
  68401. };
  68402. var getRequest = transaction.objectStore("textures").get(url);
  68403. getRequest.onsuccess = function (event) {
  68404. texture = (event.target).result;
  68405. };
  68406. getRequest.onerror = function (event) {
  68407. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68408. image.src = url;
  68409. };
  68410. }
  68411. else {
  68412. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68413. image.src = url;
  68414. }
  68415. };
  68416. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68417. var _this = this;
  68418. if (this.isSupported) {
  68419. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68420. var generateBlobUrl = function () {
  68421. var blobTextureURL;
  68422. if (blob) {
  68423. var URL = window.URL || window.webkitURL;
  68424. try {
  68425. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68426. }
  68427. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68428. catch (ex) {
  68429. blobTextureURL = URL.createObjectURL(blob);
  68430. }
  68431. }
  68432. if (blobTextureURL) {
  68433. image.src = blobTextureURL;
  68434. }
  68435. };
  68436. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68437. var xhr = new XMLHttpRequest(), blob;
  68438. xhr.open("GET", url, true);
  68439. xhr.responseType = "blob";
  68440. xhr.addEventListener("load", function () {
  68441. if (xhr.status === 200 && _this.db) {
  68442. // Blob as response (XHR2)
  68443. blob = xhr.response;
  68444. var transaction = _this.db.transaction(["textures"], "readwrite");
  68445. // the transaction could abort because of a QuotaExceededError error
  68446. transaction.onabort = function (event) {
  68447. try {
  68448. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68449. var srcElement = (event.srcElement || event.target);
  68450. var error = srcElement.error;
  68451. if (error && error.name === "QuotaExceededError") {
  68452. _this.hasReachedQuota = true;
  68453. }
  68454. }
  68455. catch (ex) { }
  68456. generateBlobUrl();
  68457. };
  68458. transaction.oncomplete = function (event) {
  68459. generateBlobUrl();
  68460. };
  68461. var newTexture = { textureUrl: url, data: blob };
  68462. try {
  68463. // Put the blob into the dabase
  68464. var addRequest = transaction.objectStore("textures").put(newTexture);
  68465. addRequest.onsuccess = function (event) {
  68466. };
  68467. addRequest.onerror = function (event) {
  68468. generateBlobUrl();
  68469. };
  68470. }
  68471. catch (ex) {
  68472. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68473. if (ex.code === 25) {
  68474. Database.IsUASupportingBlobStorage = false;
  68475. }
  68476. image.src = url;
  68477. }
  68478. }
  68479. else {
  68480. image.src = url;
  68481. }
  68482. }, false);
  68483. xhr.addEventListener("error", function (event) {
  68484. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68485. image.src = url;
  68486. }, false);
  68487. xhr.send();
  68488. }
  68489. else {
  68490. image.src = url;
  68491. }
  68492. }
  68493. else {
  68494. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68495. image.src = url;
  68496. }
  68497. };
  68498. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68499. var _this = this;
  68500. var updateVersion = function () {
  68501. // the version is not yet in the DB or we need to update it
  68502. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68503. };
  68504. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68505. };
  68506. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68507. var _this = this;
  68508. if (this.isSupported && this.db) {
  68509. var version;
  68510. try {
  68511. var transaction = this.db.transaction(["versions"]);
  68512. transaction.oncomplete = function (event) {
  68513. if (version) {
  68514. // If the version in the JSON file is different from the version in DB
  68515. if (_this.manifestVersionFound !== version.data) {
  68516. _this.mustUpdateRessources = true;
  68517. updateInDBCallback();
  68518. }
  68519. else {
  68520. callback(version.data);
  68521. }
  68522. }
  68523. // version was not found in DB
  68524. else {
  68525. _this.mustUpdateRessources = true;
  68526. updateInDBCallback();
  68527. }
  68528. };
  68529. transaction.onabort = function (event) {
  68530. callback(-1);
  68531. };
  68532. var getRequest = transaction.objectStore("versions").get(url);
  68533. getRequest.onsuccess = function (event) {
  68534. version = (event.target).result;
  68535. };
  68536. getRequest.onerror = function (event) {
  68537. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68538. callback(-1);
  68539. };
  68540. }
  68541. catch (ex) {
  68542. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68543. callback(-1);
  68544. }
  68545. }
  68546. else {
  68547. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68548. callback(-1);
  68549. }
  68550. };
  68551. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68552. var _this = this;
  68553. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68554. try {
  68555. // Open a transaction to the database
  68556. var transaction = this.db.transaction(["versions"], "readwrite");
  68557. // the transaction could abort because of a QuotaExceededError error
  68558. transaction.onabort = function (event) {
  68559. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68560. var error = event.srcElement['error'];
  68561. if (error && error.name === "QuotaExceededError") {
  68562. _this.hasReachedQuota = true;
  68563. }
  68564. }
  68565. catch (ex) { }
  68566. callback(-1);
  68567. };
  68568. transaction.oncomplete = function (event) {
  68569. callback(_this.manifestVersionFound);
  68570. };
  68571. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68572. // Put the scene into the database
  68573. var addRequest = transaction.objectStore("versions").put(newVersion);
  68574. addRequest.onsuccess = function (event) {
  68575. };
  68576. addRequest.onerror = function (event) {
  68577. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68578. };
  68579. }
  68580. catch (ex) {
  68581. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68582. callback(-1);
  68583. }
  68584. }
  68585. else {
  68586. callback(-1);
  68587. }
  68588. };
  68589. /**
  68590. * Loads a file from database
  68591. * @param url defines the URL to load from
  68592. * @param sceneLoaded defines a callback to call on success
  68593. * @param progressCallBack defines a callback to call when progress changed
  68594. * @param errorCallback defines a callback to call on error
  68595. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68596. */
  68597. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68598. var _this = this;
  68599. var completeUrl = Database._ReturnFullUrlLocation(url);
  68600. var saveAndLoadFile = function () {
  68601. // the scene is not yet in the DB, let's try to save it
  68602. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68603. };
  68604. this._checkVersionFromDB(completeUrl, function (version) {
  68605. if (version !== -1) {
  68606. if (!_this.mustUpdateRessources) {
  68607. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68608. }
  68609. else {
  68610. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68611. }
  68612. }
  68613. else {
  68614. if (errorCallback) {
  68615. errorCallback();
  68616. }
  68617. }
  68618. });
  68619. };
  68620. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68621. if (this.isSupported && this.db) {
  68622. var targetStore;
  68623. if (url.indexOf(".babylon") !== -1) {
  68624. targetStore = "scenes";
  68625. }
  68626. else {
  68627. targetStore = "textures";
  68628. }
  68629. var file;
  68630. var transaction = this.db.transaction([targetStore]);
  68631. transaction.oncomplete = function (event) {
  68632. if (file) {
  68633. callback(file.data);
  68634. }
  68635. // file was not found in DB
  68636. else {
  68637. notInDBCallback();
  68638. }
  68639. };
  68640. transaction.onabort = function (event) {
  68641. notInDBCallback();
  68642. };
  68643. var getRequest = transaction.objectStore(targetStore).get(url);
  68644. getRequest.onsuccess = function (event) {
  68645. file = (event.target).result;
  68646. };
  68647. getRequest.onerror = function (event) {
  68648. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68649. notInDBCallback();
  68650. };
  68651. }
  68652. else {
  68653. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68654. callback();
  68655. }
  68656. };
  68657. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68658. var _this = this;
  68659. if (this.isSupported) {
  68660. var targetStore;
  68661. if (url.indexOf(".babylon") !== -1) {
  68662. targetStore = "scenes";
  68663. }
  68664. else {
  68665. targetStore = "textures";
  68666. }
  68667. // Create XHR
  68668. var xhr = new XMLHttpRequest();
  68669. var fileData;
  68670. xhr.open("GET", url, true);
  68671. if (useArrayBuffer) {
  68672. xhr.responseType = "arraybuffer";
  68673. }
  68674. if (progressCallback) {
  68675. xhr.onprogress = progressCallback;
  68676. }
  68677. xhr.addEventListener("load", function () {
  68678. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68679. // Blob as response (XHR2)
  68680. //fileData = xhr.responseText;
  68681. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68682. if (!_this.hasReachedQuota && _this.db) {
  68683. // Open a transaction to the database
  68684. var transaction = _this.db.transaction([targetStore], "readwrite");
  68685. // the transaction could abort because of a QuotaExceededError error
  68686. transaction.onabort = function (event) {
  68687. try {
  68688. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68689. var error = event.srcElement['error'];
  68690. if (error && error.name === "QuotaExceededError") {
  68691. _this.hasReachedQuota = true;
  68692. }
  68693. }
  68694. catch (ex) { }
  68695. callback(fileData);
  68696. };
  68697. transaction.oncomplete = function (event) {
  68698. callback(fileData);
  68699. };
  68700. var newFile;
  68701. if (targetStore === "scenes") {
  68702. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68703. }
  68704. else {
  68705. newFile = { textureUrl: url, data: fileData };
  68706. }
  68707. try {
  68708. // Put the scene into the database
  68709. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68710. addRequest.onsuccess = function (event) {
  68711. };
  68712. addRequest.onerror = function (event) {
  68713. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68714. };
  68715. }
  68716. catch (ex) {
  68717. callback(fileData);
  68718. }
  68719. }
  68720. else {
  68721. callback(fileData);
  68722. }
  68723. }
  68724. else {
  68725. callback();
  68726. }
  68727. }, false);
  68728. xhr.addEventListener("error", function (event) {
  68729. BABYLON.Tools.Error("error on XHR request.");
  68730. callback();
  68731. }, false);
  68732. xhr.send();
  68733. }
  68734. else {
  68735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68736. callback();
  68737. }
  68738. };
  68739. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  68740. Database.IsUASupportingBlobStorage = true;
  68741. /** Gets a boolean indicating if Database storate is enabled */
  68742. Database.IDBStorageEnabled = true;
  68743. Database._ParseURL = function (url) {
  68744. var a = document.createElement('a');
  68745. a.href = url;
  68746. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68747. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68748. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68749. return absLocation;
  68750. };
  68751. Database._ReturnFullUrlLocation = function (url) {
  68752. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68753. return (Database._ParseURL(window.location.href) + url);
  68754. }
  68755. else {
  68756. return url;
  68757. }
  68758. };
  68759. return Database;
  68760. }());
  68761. BABYLON.Database = Database;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.database.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. var FresnelParameters = /** @class */ (function () {
  68767. function FresnelParameters() {
  68768. this._isEnabled = true;
  68769. this.leftColor = BABYLON.Color3.White();
  68770. this.rightColor = BABYLON.Color3.Black();
  68771. this.bias = 0;
  68772. this.power = 1;
  68773. }
  68774. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68775. get: function () {
  68776. return this._isEnabled;
  68777. },
  68778. set: function (value) {
  68779. if (this._isEnabled === value) {
  68780. return;
  68781. }
  68782. this._isEnabled = value;
  68783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68784. },
  68785. enumerable: true,
  68786. configurable: true
  68787. });
  68788. FresnelParameters.prototype.clone = function () {
  68789. var newFresnelParameters = new FresnelParameters();
  68790. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68791. return newFresnelParameters;
  68792. };
  68793. FresnelParameters.prototype.serialize = function () {
  68794. var serializationObject = {};
  68795. serializationObject.isEnabled = this.isEnabled;
  68796. serializationObject.leftColor = this.leftColor.asArray();
  68797. serializationObject.rightColor = this.rightColor.asArray();
  68798. serializationObject.bias = this.bias;
  68799. serializationObject.power = this.power;
  68800. return serializationObject;
  68801. };
  68802. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68803. var fresnelParameters = new FresnelParameters();
  68804. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68805. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68806. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68807. fresnelParameters.bias = parsedFresnelParameters.bias;
  68808. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68809. return fresnelParameters;
  68810. };
  68811. return FresnelParameters;
  68812. }());
  68813. BABYLON.FresnelParameters = FresnelParameters;
  68814. })(BABYLON || (BABYLON = {}));
  68815. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68816. var BABYLON;
  68817. (function (BABYLON) {
  68818. var MultiMaterial = /** @class */ (function (_super) {
  68819. __extends(MultiMaterial, _super);
  68820. function MultiMaterial(name, scene) {
  68821. var _this = _super.call(this, name, scene, true) || this;
  68822. scene.multiMaterials.push(_this);
  68823. _this.subMaterials = new Array();
  68824. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68825. return _this;
  68826. }
  68827. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68828. get: function () {
  68829. return this._subMaterials;
  68830. },
  68831. set: function (value) {
  68832. this._subMaterials = value;
  68833. this._hookArray(value);
  68834. },
  68835. enumerable: true,
  68836. configurable: true
  68837. });
  68838. MultiMaterial.prototype._hookArray = function (array) {
  68839. var _this = this;
  68840. var oldPush = array.push;
  68841. array.push = function () {
  68842. var items = [];
  68843. for (var _i = 0; _i < arguments.length; _i++) {
  68844. items[_i] = arguments[_i];
  68845. }
  68846. var result = oldPush.apply(array, items);
  68847. _this._markAllSubMeshesAsTexturesDirty();
  68848. return result;
  68849. };
  68850. var oldSplice = array.splice;
  68851. array.splice = function (index, deleteCount) {
  68852. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68853. _this._markAllSubMeshesAsTexturesDirty();
  68854. return deleted;
  68855. };
  68856. };
  68857. // Properties
  68858. MultiMaterial.prototype.getSubMaterial = function (index) {
  68859. if (index < 0 || index >= this.subMaterials.length) {
  68860. return this.getScene().defaultMaterial;
  68861. }
  68862. return this.subMaterials[index];
  68863. };
  68864. MultiMaterial.prototype.getActiveTextures = function () {
  68865. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68866. if (subMaterial) {
  68867. return subMaterial.getActiveTextures();
  68868. }
  68869. else {
  68870. return [];
  68871. }
  68872. }));
  68873. var _a;
  68874. };
  68875. // Methods
  68876. MultiMaterial.prototype.getClassName = function () {
  68877. return "MultiMaterial";
  68878. };
  68879. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68880. for (var index = 0; index < this.subMaterials.length; index++) {
  68881. var subMaterial = this.subMaterials[index];
  68882. if (subMaterial) {
  68883. if (subMaterial.storeEffectOnSubMeshes) {
  68884. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68885. return false;
  68886. }
  68887. continue;
  68888. }
  68889. if (!subMaterial.isReady(mesh)) {
  68890. return false;
  68891. }
  68892. }
  68893. }
  68894. return true;
  68895. };
  68896. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68897. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68898. for (var index = 0; index < this.subMaterials.length; index++) {
  68899. var subMaterial = null;
  68900. var current = this.subMaterials[index];
  68901. if (cloneChildren && current) {
  68902. subMaterial = current.clone(name + "-" + current.name);
  68903. }
  68904. else {
  68905. subMaterial = this.subMaterials[index];
  68906. }
  68907. newMultiMaterial.subMaterials.push(subMaterial);
  68908. }
  68909. return newMultiMaterial;
  68910. };
  68911. MultiMaterial.prototype.serialize = function () {
  68912. var serializationObject = {};
  68913. serializationObject.name = this.name;
  68914. serializationObject.id = this.id;
  68915. if (BABYLON.Tags) {
  68916. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68917. }
  68918. serializationObject.materials = [];
  68919. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68920. var subMat = this.subMaterials[matIndex];
  68921. if (subMat) {
  68922. serializationObject.materials.push(subMat.id);
  68923. }
  68924. else {
  68925. serializationObject.materials.push(null);
  68926. }
  68927. }
  68928. return serializationObject;
  68929. };
  68930. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68931. var scene = this.getScene();
  68932. if (!scene) {
  68933. return;
  68934. }
  68935. var index = scene.multiMaterials.indexOf(this);
  68936. if (index >= 0) {
  68937. scene.multiMaterials.splice(index, 1);
  68938. }
  68939. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68940. };
  68941. return MultiMaterial;
  68942. }(BABYLON.Material));
  68943. BABYLON.MultiMaterial = MultiMaterial;
  68944. })(BABYLON || (BABYLON = {}));
  68945. //# sourceMappingURL=babylon.multiMaterial.js.map
  68946. var BABYLON;
  68947. (function (BABYLON) {
  68948. var FreeCameraTouchInput = /** @class */ (function () {
  68949. function FreeCameraTouchInput() {
  68950. this._offsetX = null;
  68951. this._offsetY = null;
  68952. this._pointerPressed = new Array();
  68953. this.touchAngularSensibility = 200000.0;
  68954. this.touchMoveSensibility = 250.0;
  68955. }
  68956. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68957. var _this = this;
  68958. var previousPosition = null;
  68959. if (this._pointerInput === undefined) {
  68960. this._onLostFocus = function (evt) {
  68961. _this._offsetX = null;
  68962. _this._offsetY = null;
  68963. };
  68964. this._pointerInput = function (p, s) {
  68965. var evt = p.event;
  68966. if (evt.pointerType === "mouse") {
  68967. return;
  68968. }
  68969. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68970. if (!noPreventDefault) {
  68971. evt.preventDefault();
  68972. }
  68973. _this._pointerPressed.push(evt.pointerId);
  68974. if (_this._pointerPressed.length !== 1) {
  68975. return;
  68976. }
  68977. previousPosition = {
  68978. x: evt.clientX,
  68979. y: evt.clientY
  68980. };
  68981. }
  68982. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68983. if (!noPreventDefault) {
  68984. evt.preventDefault();
  68985. }
  68986. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68987. if (index === -1) {
  68988. return;
  68989. }
  68990. _this._pointerPressed.splice(index, 1);
  68991. if (index != 0) {
  68992. return;
  68993. }
  68994. previousPosition = null;
  68995. _this._offsetX = null;
  68996. _this._offsetY = null;
  68997. }
  68998. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68999. if (!noPreventDefault) {
  69000. evt.preventDefault();
  69001. }
  69002. if (!previousPosition) {
  69003. return;
  69004. }
  69005. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69006. if (index != 0) {
  69007. return;
  69008. }
  69009. _this._offsetX = evt.clientX - previousPosition.x;
  69010. _this._offsetY = -(evt.clientY - previousPosition.y);
  69011. }
  69012. };
  69013. }
  69014. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69015. if (this._onLostFocus) {
  69016. element.addEventListener("blur", this._onLostFocus);
  69017. }
  69018. };
  69019. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69020. if (this._pointerInput && element) {
  69021. if (this._observer) {
  69022. this.camera.getScene().onPointerObservable.remove(this._observer);
  69023. this._observer = null;
  69024. }
  69025. if (this._onLostFocus) {
  69026. element.removeEventListener("blur", this._onLostFocus);
  69027. this._onLostFocus = null;
  69028. }
  69029. this._pointerPressed = [];
  69030. this._offsetX = null;
  69031. this._offsetY = null;
  69032. }
  69033. };
  69034. FreeCameraTouchInput.prototype.checkInputs = function () {
  69035. if (this._offsetX && this._offsetY) {
  69036. var camera = this.camera;
  69037. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69038. if (this._pointerPressed.length > 1) {
  69039. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69040. }
  69041. else {
  69042. var speed = camera._computeLocalCameraSpeed();
  69043. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69044. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69045. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69046. }
  69047. }
  69048. };
  69049. FreeCameraTouchInput.prototype.getClassName = function () {
  69050. return "FreeCameraTouchInput";
  69051. };
  69052. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69053. return "touch";
  69054. };
  69055. __decorate([
  69056. BABYLON.serialize()
  69057. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69058. __decorate([
  69059. BABYLON.serialize()
  69060. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69061. return FreeCameraTouchInput;
  69062. }());
  69063. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69064. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69065. })(BABYLON || (BABYLON = {}));
  69066. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69067. var BABYLON;
  69068. (function (BABYLON) {
  69069. // We're mainly based on the logic defined into the FreeCamera code
  69070. var TouchCamera = /** @class */ (function (_super) {
  69071. __extends(TouchCamera, _super);
  69072. //-- end properties for backward compatibility for inputs
  69073. function TouchCamera(name, position, scene) {
  69074. var _this = _super.call(this, name, position, scene) || this;
  69075. _this.inputs.addTouch();
  69076. _this._setupInputs();
  69077. return _this;
  69078. }
  69079. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69080. //-- Begin properties for backward compatibility for inputs
  69081. get: function () {
  69082. var touch = this.inputs.attached["touch"];
  69083. if (touch)
  69084. return touch.touchAngularSensibility;
  69085. return 0;
  69086. },
  69087. set: function (value) {
  69088. var touch = this.inputs.attached["touch"];
  69089. if (touch)
  69090. touch.touchAngularSensibility = value;
  69091. },
  69092. enumerable: true,
  69093. configurable: true
  69094. });
  69095. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69096. get: function () {
  69097. var touch = this.inputs.attached["touch"];
  69098. if (touch)
  69099. return touch.touchMoveSensibility;
  69100. return 0;
  69101. },
  69102. set: function (value) {
  69103. var touch = this.inputs.attached["touch"];
  69104. if (touch)
  69105. touch.touchMoveSensibility = value;
  69106. },
  69107. enumerable: true,
  69108. configurable: true
  69109. });
  69110. TouchCamera.prototype.getClassName = function () {
  69111. return "TouchCamera";
  69112. };
  69113. TouchCamera.prototype._setupInputs = function () {
  69114. var mouse = this.inputs.attached["mouse"];
  69115. if (mouse) {
  69116. mouse.touchEnabled = false;
  69117. }
  69118. };
  69119. return TouchCamera;
  69120. }(BABYLON.FreeCamera));
  69121. BABYLON.TouchCamera = TouchCamera;
  69122. })(BABYLON || (BABYLON = {}));
  69123. //# sourceMappingURL=babylon.touchCamera.js.map
  69124. var BABYLON;
  69125. (function (BABYLON) {
  69126. var ProceduralTexture = /** @class */ (function (_super) {
  69127. __extends(ProceduralTexture, _super);
  69128. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69129. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69130. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69131. if (isCube === void 0) { isCube = false; }
  69132. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69133. _this.isCube = isCube;
  69134. _this.isEnabled = true;
  69135. _this._currentRefreshId = -1;
  69136. _this._refreshRate = 1;
  69137. _this._vertexBuffers = {};
  69138. _this._uniforms = new Array();
  69139. _this._samplers = new Array();
  69140. _this._textures = {};
  69141. _this._floats = {};
  69142. _this._floatsArrays = {};
  69143. _this._colors3 = {};
  69144. _this._colors4 = {};
  69145. _this._vectors2 = {};
  69146. _this._vectors3 = {};
  69147. _this._matrices = {};
  69148. _this._fallbackTextureUsed = false;
  69149. scene.proceduralTextures.push(_this);
  69150. _this._engine = scene.getEngine();
  69151. _this.name = name;
  69152. _this.isRenderTarget = true;
  69153. _this._size = size;
  69154. _this._generateMipMaps = generateMipMaps;
  69155. _this.setFragment(fragment);
  69156. _this._fallbackTexture = fallbackTexture;
  69157. if (isCube) {
  69158. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69159. _this.setFloat("face", 0);
  69160. }
  69161. else {
  69162. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69163. }
  69164. // VBO
  69165. var vertices = [];
  69166. vertices.push(1, 1);
  69167. vertices.push(-1, 1);
  69168. vertices.push(-1, -1);
  69169. vertices.push(1, -1);
  69170. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69171. _this._createIndexBuffer();
  69172. return _this;
  69173. }
  69174. ProceduralTexture.prototype._createIndexBuffer = function () {
  69175. var engine = this._engine;
  69176. // Indices
  69177. var indices = [];
  69178. indices.push(0);
  69179. indices.push(1);
  69180. indices.push(2);
  69181. indices.push(0);
  69182. indices.push(2);
  69183. indices.push(3);
  69184. this._indexBuffer = engine.createIndexBuffer(indices);
  69185. };
  69186. ProceduralTexture.prototype._rebuild = function () {
  69187. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69188. if (vb) {
  69189. vb._rebuild();
  69190. }
  69191. this._createIndexBuffer();
  69192. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69193. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69194. }
  69195. };
  69196. ProceduralTexture.prototype.reset = function () {
  69197. if (this._effect === undefined) {
  69198. return;
  69199. }
  69200. var engine = this._engine;
  69201. engine._releaseEffect(this._effect);
  69202. };
  69203. ProceduralTexture.prototype.isReady = function () {
  69204. var _this = this;
  69205. var engine = this._engine;
  69206. var shaders;
  69207. if (!this._fragment) {
  69208. return false;
  69209. }
  69210. if (this._fallbackTextureUsed) {
  69211. return true;
  69212. }
  69213. if (this._fragment.fragmentElement !== undefined) {
  69214. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69215. }
  69216. else {
  69217. shaders = { vertex: "procedural", fragment: this._fragment };
  69218. }
  69219. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69220. _this.releaseInternalTexture();
  69221. if (_this._fallbackTexture) {
  69222. _this._texture = _this._fallbackTexture._texture;
  69223. if (_this._texture) {
  69224. _this._texture.incrementReferences();
  69225. }
  69226. }
  69227. _this._fallbackTextureUsed = true;
  69228. });
  69229. return this._effect.isReady();
  69230. };
  69231. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69232. this._currentRefreshId = -1;
  69233. };
  69234. ProceduralTexture.prototype.setFragment = function (fragment) {
  69235. this._fragment = fragment;
  69236. };
  69237. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69238. get: function () {
  69239. return this._refreshRate;
  69240. },
  69241. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69242. set: function (value) {
  69243. this._refreshRate = value;
  69244. this.resetRefreshCounter();
  69245. },
  69246. enumerable: true,
  69247. configurable: true
  69248. });
  69249. ProceduralTexture.prototype._shouldRender = function () {
  69250. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69251. return false;
  69252. }
  69253. if (this._fallbackTextureUsed) {
  69254. return false;
  69255. }
  69256. if (this._currentRefreshId === -1) { // At least render once
  69257. this._currentRefreshId = 1;
  69258. return true;
  69259. }
  69260. if (this.refreshRate === this._currentRefreshId) {
  69261. this._currentRefreshId = 1;
  69262. return true;
  69263. }
  69264. this._currentRefreshId++;
  69265. return false;
  69266. };
  69267. ProceduralTexture.prototype.getRenderSize = function () {
  69268. return this._size;
  69269. };
  69270. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69271. if (this._fallbackTextureUsed) {
  69272. return;
  69273. }
  69274. this.releaseInternalTexture();
  69275. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69276. // Update properties
  69277. this._size = size;
  69278. this._generateMipMaps = generateMipMaps;
  69279. };
  69280. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69281. if (this._uniforms.indexOf(uniformName) === -1) {
  69282. this._uniforms.push(uniformName);
  69283. }
  69284. };
  69285. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69286. if (this._samplers.indexOf(name) === -1) {
  69287. this._samplers.push(name);
  69288. }
  69289. this._textures[name] = texture;
  69290. return this;
  69291. };
  69292. ProceduralTexture.prototype.setFloat = function (name, value) {
  69293. this._checkUniform(name);
  69294. this._floats[name] = value;
  69295. return this;
  69296. };
  69297. ProceduralTexture.prototype.setFloats = function (name, value) {
  69298. this._checkUniform(name);
  69299. this._floatsArrays[name] = value;
  69300. return this;
  69301. };
  69302. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69303. this._checkUniform(name);
  69304. this._colors3[name] = value;
  69305. return this;
  69306. };
  69307. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69308. this._checkUniform(name);
  69309. this._colors4[name] = value;
  69310. return this;
  69311. };
  69312. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69313. this._checkUniform(name);
  69314. this._vectors2[name] = value;
  69315. return this;
  69316. };
  69317. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69318. this._checkUniform(name);
  69319. this._vectors3[name] = value;
  69320. return this;
  69321. };
  69322. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69323. this._checkUniform(name);
  69324. this._matrices[name] = value;
  69325. return this;
  69326. };
  69327. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69328. var scene = this.getScene();
  69329. if (!scene) {
  69330. return;
  69331. }
  69332. var engine = this._engine;
  69333. // Render
  69334. engine.enableEffect(this._effect);
  69335. engine.setState(false);
  69336. // Texture
  69337. for (var name in this._textures) {
  69338. this._effect.setTexture(name, this._textures[name]);
  69339. }
  69340. // Float
  69341. for (name in this._floats) {
  69342. this._effect.setFloat(name, this._floats[name]);
  69343. }
  69344. // Floats
  69345. for (name in this._floatsArrays) {
  69346. this._effect.setArray(name, this._floatsArrays[name]);
  69347. }
  69348. // Color3
  69349. for (name in this._colors3) {
  69350. this._effect.setColor3(name, this._colors3[name]);
  69351. }
  69352. // Color4
  69353. for (name in this._colors4) {
  69354. var color = this._colors4[name];
  69355. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69356. }
  69357. // Vector2
  69358. for (name in this._vectors2) {
  69359. this._effect.setVector2(name, this._vectors2[name]);
  69360. }
  69361. // Vector3
  69362. for (name in this._vectors3) {
  69363. this._effect.setVector3(name, this._vectors3[name]);
  69364. }
  69365. // Matrix
  69366. for (name in this._matrices) {
  69367. this._effect.setMatrix(name, this._matrices[name]);
  69368. }
  69369. if (!this._texture) {
  69370. return;
  69371. }
  69372. if (this.isCube) {
  69373. for (var face = 0; face < 6; face++) {
  69374. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69375. // VBOs
  69376. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69377. this._effect.setFloat("face", face);
  69378. // Clear
  69379. engine.clear(scene.clearColor, true, true, true);
  69380. // Draw order
  69381. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69382. // Mipmaps
  69383. if (face === 5) {
  69384. engine.generateMipMapsForCubemap(this._texture);
  69385. }
  69386. }
  69387. }
  69388. else {
  69389. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69390. // VBOs
  69391. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69392. // Clear
  69393. engine.clear(scene.clearColor, true, true, true);
  69394. // Draw order
  69395. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69396. }
  69397. // Unbind
  69398. engine.unBindFramebuffer(this._texture, this.isCube);
  69399. if (this.onGenerated) {
  69400. this.onGenerated();
  69401. }
  69402. };
  69403. ProceduralTexture.prototype.clone = function () {
  69404. var textureSize = this.getSize();
  69405. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69406. // Base texture
  69407. newTexture.hasAlpha = this.hasAlpha;
  69408. newTexture.level = this.level;
  69409. // RenderTarget Texture
  69410. newTexture.coordinatesMode = this.coordinatesMode;
  69411. return newTexture;
  69412. };
  69413. ProceduralTexture.prototype.dispose = function () {
  69414. var scene = this.getScene();
  69415. if (!scene) {
  69416. return;
  69417. }
  69418. var index = scene.proceduralTextures.indexOf(this);
  69419. if (index >= 0) {
  69420. scene.proceduralTextures.splice(index, 1);
  69421. }
  69422. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69423. if (vertexBuffer) {
  69424. vertexBuffer.dispose();
  69425. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69426. }
  69427. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69428. this._indexBuffer = null;
  69429. }
  69430. _super.prototype.dispose.call(this);
  69431. };
  69432. __decorate([
  69433. BABYLON.serialize()
  69434. ], ProceduralTexture.prototype, "_size", void 0);
  69435. __decorate([
  69436. BABYLON.serialize()
  69437. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69438. __decorate([
  69439. BABYLON.serialize()
  69440. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69441. __decorate([
  69442. BABYLON.serialize()
  69443. ], ProceduralTexture.prototype, "refreshRate", null);
  69444. return ProceduralTexture;
  69445. }(BABYLON.Texture));
  69446. BABYLON.ProceduralTexture = ProceduralTexture;
  69447. })(BABYLON || (BABYLON = {}));
  69448. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69449. var BABYLON;
  69450. (function (BABYLON) {
  69451. var CustomProceduralTexture = /** @class */ (function (_super) {
  69452. __extends(CustomProceduralTexture, _super);
  69453. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69454. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69455. _this._animate = true;
  69456. _this._time = 0;
  69457. _this._texturePath = texturePath;
  69458. //Try to load json
  69459. _this.loadJson(texturePath);
  69460. _this.refreshRate = 1;
  69461. return _this;
  69462. }
  69463. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69464. var _this = this;
  69465. var noConfigFile = function () {
  69466. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69467. try {
  69468. _this.setFragment(_this._texturePath);
  69469. }
  69470. catch (ex) {
  69471. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69472. }
  69473. };
  69474. var configFileUrl = jsonUrl + "/config.json";
  69475. var xhr = new XMLHttpRequest();
  69476. xhr.open("GET", configFileUrl, true);
  69477. xhr.addEventListener("load", function () {
  69478. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69479. try {
  69480. _this._config = JSON.parse(xhr.response);
  69481. _this.updateShaderUniforms();
  69482. _this.updateTextures();
  69483. _this.setFragment(_this._texturePath + "/custom");
  69484. _this._animate = _this._config.animate;
  69485. _this.refreshRate = _this._config.refreshrate;
  69486. }
  69487. catch (ex) {
  69488. noConfigFile();
  69489. }
  69490. }
  69491. else {
  69492. noConfigFile();
  69493. }
  69494. }, false);
  69495. xhr.addEventListener("error", function () {
  69496. noConfigFile();
  69497. }, false);
  69498. try {
  69499. xhr.send();
  69500. }
  69501. catch (ex) {
  69502. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69503. }
  69504. };
  69505. CustomProceduralTexture.prototype.isReady = function () {
  69506. if (!_super.prototype.isReady.call(this)) {
  69507. return false;
  69508. }
  69509. for (var name in this._textures) {
  69510. var texture = this._textures[name];
  69511. if (!texture.isReady()) {
  69512. return false;
  69513. }
  69514. }
  69515. return true;
  69516. };
  69517. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69518. var scene = this.getScene();
  69519. if (this._animate && scene) {
  69520. this._time += scene.getAnimationRatio() * 0.03;
  69521. this.updateShaderUniforms();
  69522. }
  69523. _super.prototype.render.call(this, useCameraPostProcess);
  69524. };
  69525. CustomProceduralTexture.prototype.updateTextures = function () {
  69526. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69527. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69528. }
  69529. };
  69530. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69531. if (this._config) {
  69532. for (var j = 0; j < this._config.uniforms.length; j++) {
  69533. var uniform = this._config.uniforms[j];
  69534. switch (uniform.type) {
  69535. case "float":
  69536. this.setFloat(uniform.name, uniform.value);
  69537. break;
  69538. case "color3":
  69539. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69540. break;
  69541. case "color4":
  69542. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69543. break;
  69544. case "vector2":
  69545. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69546. break;
  69547. case "vector3":
  69548. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69549. break;
  69550. }
  69551. }
  69552. }
  69553. this.setFloat("time", this._time);
  69554. };
  69555. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69556. get: function () {
  69557. return this._animate;
  69558. },
  69559. set: function (value) {
  69560. this._animate = value;
  69561. },
  69562. enumerable: true,
  69563. configurable: true
  69564. });
  69565. return CustomProceduralTexture;
  69566. }(BABYLON.ProceduralTexture));
  69567. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69568. })(BABYLON || (BABYLON = {}));
  69569. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69570. var BABYLON;
  69571. (function (BABYLON) {
  69572. var FreeCameraGamepadInput = /** @class */ (function () {
  69573. function FreeCameraGamepadInput() {
  69574. this.gamepadAngularSensibility = 200;
  69575. this.gamepadMoveSensibility = 40;
  69576. // private members
  69577. this._cameraTransform = BABYLON.Matrix.Identity();
  69578. this._deltaTransform = BABYLON.Vector3.Zero();
  69579. this._vector3 = BABYLON.Vector3.Zero();
  69580. this._vector2 = BABYLON.Vector2.Zero();
  69581. }
  69582. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69583. var _this = this;
  69584. var manager = this.camera.getScene().gamepadManager;
  69585. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69586. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69587. // prioritize XBOX gamepads.
  69588. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69589. _this.gamepad = gamepad;
  69590. }
  69591. }
  69592. });
  69593. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69594. if (_this.gamepad === gamepad) {
  69595. _this.gamepad = null;
  69596. }
  69597. });
  69598. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69599. };
  69600. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69601. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69602. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69603. this.gamepad = null;
  69604. };
  69605. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69606. if (this.gamepad && this.gamepad.leftStick) {
  69607. var camera = this.camera;
  69608. var LSValues = this.gamepad.leftStick;
  69609. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69610. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69611. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69612. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69613. var RSValues = this.gamepad.rightStick;
  69614. if (RSValues) {
  69615. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69616. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69617. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69618. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69619. }
  69620. else {
  69621. RSValues = { x: 0, y: 0 };
  69622. }
  69623. if (!camera.rotationQuaternion) {
  69624. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69625. }
  69626. else {
  69627. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69628. }
  69629. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69630. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69631. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69632. camera.cameraDirection.addInPlace(this._deltaTransform);
  69633. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69634. camera.cameraRotation.addInPlace(this._vector2);
  69635. }
  69636. };
  69637. FreeCameraGamepadInput.prototype.getClassName = function () {
  69638. return "FreeCameraGamepadInput";
  69639. };
  69640. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69641. return "gamepad";
  69642. };
  69643. __decorate([
  69644. BABYLON.serialize()
  69645. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69646. __decorate([
  69647. BABYLON.serialize()
  69648. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69649. return FreeCameraGamepadInput;
  69650. }());
  69651. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69652. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69653. })(BABYLON || (BABYLON = {}));
  69654. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69655. var BABYLON;
  69656. (function (BABYLON) {
  69657. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69658. function ArcRotateCameraGamepadInput() {
  69659. this.gamepadRotationSensibility = 80;
  69660. this.gamepadMoveSensibility = 40;
  69661. }
  69662. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69663. var _this = this;
  69664. var manager = this.camera.getScene().gamepadManager;
  69665. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69666. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69667. // prioritize XBOX gamepads.
  69668. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69669. _this.gamepad = gamepad;
  69670. }
  69671. }
  69672. });
  69673. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69674. if (_this.gamepad === gamepad) {
  69675. _this.gamepad = null;
  69676. }
  69677. });
  69678. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69679. };
  69680. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69681. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69682. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69683. this.gamepad = null;
  69684. };
  69685. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69686. if (this.gamepad) {
  69687. var camera = this.camera;
  69688. var RSValues = this.gamepad.rightStick;
  69689. if (RSValues) {
  69690. if (RSValues.x != 0) {
  69691. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69692. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69693. camera.inertialAlphaOffset += normalizedRX;
  69694. }
  69695. }
  69696. if (RSValues.y != 0) {
  69697. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69698. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69699. camera.inertialBetaOffset += normalizedRY;
  69700. }
  69701. }
  69702. }
  69703. var LSValues = this.gamepad.leftStick;
  69704. if (LSValues && LSValues.y != 0) {
  69705. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69706. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69707. this.camera.inertialRadiusOffset -= normalizedLY;
  69708. }
  69709. }
  69710. }
  69711. };
  69712. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69713. return "ArcRotateCameraGamepadInput";
  69714. };
  69715. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69716. return "gamepad";
  69717. };
  69718. __decorate([
  69719. BABYLON.serialize()
  69720. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69721. __decorate([
  69722. BABYLON.serialize()
  69723. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69724. return ArcRotateCameraGamepadInput;
  69725. }());
  69726. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69727. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69728. })(BABYLON || (BABYLON = {}));
  69729. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69730. var BABYLON;
  69731. (function (BABYLON) {
  69732. var GamepadManager = /** @class */ (function () {
  69733. function GamepadManager(_scene) {
  69734. var _this = this;
  69735. this._scene = _scene;
  69736. this._babylonGamepads = [];
  69737. this._oneGamepadConnected = false;
  69738. this._isMonitoring = false;
  69739. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69740. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69741. this._gamepadEventSupported = false;
  69742. }
  69743. else {
  69744. this._gamepadEventSupported = 'GamepadEvent' in window;
  69745. this._gamepadSupport = (navigator.getGamepads ||
  69746. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69747. }
  69748. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69749. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69750. for (var i in _this._babylonGamepads) {
  69751. var gamepad = _this._babylonGamepads[i];
  69752. if (gamepad && gamepad._isConnected) {
  69753. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69754. }
  69755. }
  69756. });
  69757. this._onGamepadConnectedEvent = function (evt) {
  69758. var gamepad = evt.gamepad;
  69759. if (gamepad.index in _this._babylonGamepads) {
  69760. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69761. return;
  69762. }
  69763. }
  69764. var newGamepad;
  69765. if (_this._babylonGamepads[gamepad.index]) {
  69766. newGamepad = _this._babylonGamepads[gamepad.index];
  69767. newGamepad.browserGamepad = gamepad;
  69768. newGamepad._isConnected = true;
  69769. }
  69770. else {
  69771. newGamepad = _this._addNewGamepad(gamepad);
  69772. }
  69773. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69774. _this._startMonitoringGamepads();
  69775. };
  69776. this._onGamepadDisconnectedEvent = function (evt) {
  69777. var gamepad = evt.gamepad;
  69778. // Remove the gamepad from the list of gamepads to monitor.
  69779. for (var i in _this._babylonGamepads) {
  69780. if (_this._babylonGamepads[i].index === gamepad.index) {
  69781. var disconnectedGamepad = _this._babylonGamepads[i];
  69782. disconnectedGamepad._isConnected = false;
  69783. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69784. break;
  69785. }
  69786. }
  69787. };
  69788. if (this._gamepadSupport) {
  69789. //first add already-connected gamepads
  69790. this._updateGamepadObjects();
  69791. if (this._babylonGamepads.length) {
  69792. this._startMonitoringGamepads();
  69793. }
  69794. // Checking if the gamepad connected event is supported (like in Firefox)
  69795. if (this._gamepadEventSupported) {
  69796. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69797. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69798. }
  69799. else {
  69800. this._startMonitoringGamepads();
  69801. }
  69802. }
  69803. }
  69804. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69805. get: function () {
  69806. return this._babylonGamepads;
  69807. },
  69808. enumerable: true,
  69809. configurable: true
  69810. });
  69811. GamepadManager.prototype.getGamepadByType = function (type) {
  69812. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69813. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69814. var gamepad = _a[_i];
  69815. if (gamepad && gamepad.type === type) {
  69816. return gamepad;
  69817. }
  69818. }
  69819. return null;
  69820. };
  69821. GamepadManager.prototype.dispose = function () {
  69822. if (this._gamepadEventSupported) {
  69823. if (this._onGamepadConnectedEvent) {
  69824. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69825. }
  69826. if (this._onGamepadDisconnectedEvent) {
  69827. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69828. }
  69829. this._onGamepadConnectedEvent = null;
  69830. this._onGamepadDisconnectedEvent = null;
  69831. }
  69832. this._babylonGamepads.forEach(function (gamepad) {
  69833. gamepad.dispose();
  69834. });
  69835. this.onGamepadConnectedObservable.clear();
  69836. this.onGamepadDisconnectedObservable.clear();
  69837. this._oneGamepadConnected = false;
  69838. this._stopMonitoringGamepads();
  69839. this._babylonGamepads = [];
  69840. };
  69841. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69842. if (!this._oneGamepadConnected) {
  69843. this._oneGamepadConnected = true;
  69844. }
  69845. var newGamepad;
  69846. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69847. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69848. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69849. }
  69850. // if pose is supported, use the (WebVR) pose enabled controller
  69851. else if (gamepad.pose) {
  69852. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69853. }
  69854. else {
  69855. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69856. }
  69857. this._babylonGamepads[newGamepad.index] = newGamepad;
  69858. return newGamepad;
  69859. };
  69860. GamepadManager.prototype._startMonitoringGamepads = function () {
  69861. if (!this._isMonitoring) {
  69862. this._isMonitoring = true;
  69863. //back-comp
  69864. if (!this._scene) {
  69865. this._checkGamepadsStatus();
  69866. }
  69867. }
  69868. };
  69869. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69870. this._isMonitoring = false;
  69871. };
  69872. GamepadManager.prototype._checkGamepadsStatus = function () {
  69873. var _this = this;
  69874. // Hack to be compatible Chrome
  69875. this._updateGamepadObjects();
  69876. for (var i in this._babylonGamepads) {
  69877. var gamepad = this._babylonGamepads[i];
  69878. if (!gamepad || !gamepad.isConnected) {
  69879. continue;
  69880. }
  69881. gamepad.update();
  69882. }
  69883. if (this._isMonitoring && !this._scene) {
  69884. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69885. }
  69886. };
  69887. // This function is called only on Chrome, which does not properly support
  69888. // connection/disconnection events and forces you to recopy again the gamepad object
  69889. GamepadManager.prototype._updateGamepadObjects = function () {
  69890. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69891. for (var i = 0; i < gamepads.length; i++) {
  69892. var gamepad = gamepads[i];
  69893. if (gamepad) {
  69894. if (!this._babylonGamepads[gamepad.index]) {
  69895. var newGamepad = this._addNewGamepad(gamepad);
  69896. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69897. }
  69898. else {
  69899. // Forced to copy again this object for Chrome for unknown reason
  69900. this._babylonGamepads[i].browserGamepad = gamepad;
  69901. if (!this._babylonGamepads[i].isConnected) {
  69902. this._babylonGamepads[i]._isConnected = true;
  69903. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69904. }
  69905. }
  69906. }
  69907. }
  69908. };
  69909. return GamepadManager;
  69910. }());
  69911. BABYLON.GamepadManager = GamepadManager;
  69912. })(BABYLON || (BABYLON = {}));
  69913. //# sourceMappingURL=babylon.gamepadManager.js.map
  69914. var BABYLON;
  69915. (function (BABYLON) {
  69916. var StickValues = /** @class */ (function () {
  69917. function StickValues(x, y) {
  69918. this.x = x;
  69919. this.y = y;
  69920. }
  69921. return StickValues;
  69922. }());
  69923. BABYLON.StickValues = StickValues;
  69924. var Gamepad = /** @class */ (function () {
  69925. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69926. if (leftStickX === void 0) { leftStickX = 0; }
  69927. if (leftStickY === void 0) { leftStickY = 1; }
  69928. if (rightStickX === void 0) { rightStickX = 2; }
  69929. if (rightStickY === void 0) { rightStickY = 3; }
  69930. this.id = id;
  69931. this.index = index;
  69932. this.browserGamepad = browserGamepad;
  69933. this._isConnected = true;
  69934. this._invertLeftStickY = false;
  69935. this.type = Gamepad.GAMEPAD;
  69936. this._leftStickAxisX = leftStickX;
  69937. this._leftStickAxisY = leftStickY;
  69938. this._rightStickAxisX = rightStickX;
  69939. this._rightStickAxisY = rightStickY;
  69940. if (this.browserGamepad.axes.length >= 2) {
  69941. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69942. }
  69943. if (this.browserGamepad.axes.length >= 4) {
  69944. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69945. }
  69946. }
  69947. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69948. get: function () {
  69949. return this._isConnected;
  69950. },
  69951. enumerable: true,
  69952. configurable: true
  69953. });
  69954. Gamepad.prototype.onleftstickchanged = function (callback) {
  69955. this._onleftstickchanged = callback;
  69956. };
  69957. Gamepad.prototype.onrightstickchanged = function (callback) {
  69958. this._onrightstickchanged = callback;
  69959. };
  69960. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69961. get: function () {
  69962. return this._leftStick;
  69963. },
  69964. set: function (newValues) {
  69965. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69966. this._onleftstickchanged(newValues);
  69967. }
  69968. this._leftStick = newValues;
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69974. get: function () {
  69975. return this._rightStick;
  69976. },
  69977. set: function (newValues) {
  69978. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69979. this._onrightstickchanged(newValues);
  69980. }
  69981. this._rightStick = newValues;
  69982. },
  69983. enumerable: true,
  69984. configurable: true
  69985. });
  69986. Gamepad.prototype.update = function () {
  69987. if (this._leftStick) {
  69988. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69989. if (this._invertLeftStickY) {
  69990. this.leftStick.y *= -1;
  69991. }
  69992. }
  69993. if (this._rightStick) {
  69994. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69995. }
  69996. };
  69997. Gamepad.prototype.dispose = function () {
  69998. };
  69999. Gamepad.GAMEPAD = 0;
  70000. Gamepad.GENERIC = 1;
  70001. Gamepad.XBOX = 2;
  70002. Gamepad.POSE_ENABLED = 3;
  70003. return Gamepad;
  70004. }());
  70005. BABYLON.Gamepad = Gamepad;
  70006. var GenericPad = /** @class */ (function (_super) {
  70007. __extends(GenericPad, _super);
  70008. function GenericPad(id, index, browserGamepad) {
  70009. var _this = _super.call(this, id, index, browserGamepad) || this;
  70010. _this.onButtonDownObservable = new BABYLON.Observable();
  70011. _this.onButtonUpObservable = new BABYLON.Observable();
  70012. _this.type = Gamepad.GENERIC;
  70013. _this._buttons = new Array(browserGamepad.buttons.length);
  70014. return _this;
  70015. }
  70016. GenericPad.prototype.onbuttondown = function (callback) {
  70017. this._onbuttondown = callback;
  70018. };
  70019. GenericPad.prototype.onbuttonup = function (callback) {
  70020. this._onbuttonup = callback;
  70021. };
  70022. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70023. if (newValue !== currentValue) {
  70024. if (newValue === 1) {
  70025. if (this._onbuttondown) {
  70026. this._onbuttondown(buttonIndex);
  70027. }
  70028. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70029. }
  70030. if (newValue === 0) {
  70031. if (this._onbuttonup) {
  70032. this._onbuttonup(buttonIndex);
  70033. }
  70034. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70035. }
  70036. }
  70037. return newValue;
  70038. };
  70039. GenericPad.prototype.update = function () {
  70040. _super.prototype.update.call(this);
  70041. for (var index = 0; index < this._buttons.length; index++) {
  70042. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70043. }
  70044. };
  70045. GenericPad.prototype.dispose = function () {
  70046. _super.prototype.dispose.call(this);
  70047. this.onButtonDownObservable.clear();
  70048. this.onButtonUpObservable.clear();
  70049. };
  70050. return GenericPad;
  70051. }(Gamepad));
  70052. BABYLON.GenericPad = GenericPad;
  70053. })(BABYLON || (BABYLON = {}));
  70054. //# sourceMappingURL=babylon.gamepad.js.map
  70055. var BABYLON;
  70056. (function (BABYLON) {
  70057. /**
  70058. * Defines supported buttons for XBox360 compatible gamepads
  70059. */
  70060. var Xbox360Button;
  70061. (function (Xbox360Button) {
  70062. /** A */
  70063. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70064. /** B */
  70065. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70066. /** X */
  70067. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70068. /** Y */
  70069. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70070. /** Start */
  70071. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70072. /** Back */
  70073. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70074. /** Left button */
  70075. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70076. /** Right button */
  70077. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70078. /** Left stick */
  70079. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70080. /** Right stick */
  70081. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70082. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70083. /** Defines values for XBox360 DPad */
  70084. var Xbox360Dpad;
  70085. (function (Xbox360Dpad) {
  70086. /** Up */
  70087. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70088. /** Down */
  70089. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70090. /** Left */
  70091. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70092. /** Right */
  70093. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70094. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70095. /**
  70096. * Defines a XBox360 gamepad
  70097. */
  70098. var Xbox360Pad = /** @class */ (function (_super) {
  70099. __extends(Xbox360Pad, _super);
  70100. /**
  70101. * Creates a new XBox360 gamepad object
  70102. * @param id defines the id of this gamepad
  70103. * @param index defines its index
  70104. * @param gamepad defines the internal HTML gamepad object
  70105. * @param xboxOne defines if it is a XBox One gamepad
  70106. */
  70107. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70108. if (xboxOne === void 0) { xboxOne = false; }
  70109. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70110. _this._leftTrigger = 0;
  70111. _this._rightTrigger = 0;
  70112. /** Observable raised when a button is pressed */
  70113. _this.onButtonDownObservable = new BABYLON.Observable();
  70114. /** Observable raised when a button is released */
  70115. _this.onButtonUpObservable = new BABYLON.Observable();
  70116. /** Observable raised when a pad is pressed */
  70117. _this.onPadDownObservable = new BABYLON.Observable();
  70118. /** Observable raised when a pad is released */
  70119. _this.onPadUpObservable = new BABYLON.Observable();
  70120. _this._buttonA = 0;
  70121. _this._buttonB = 0;
  70122. _this._buttonX = 0;
  70123. _this._buttonY = 0;
  70124. _this._buttonBack = 0;
  70125. _this._buttonStart = 0;
  70126. _this._buttonLB = 0;
  70127. _this._buttonRB = 0;
  70128. _this._buttonLeftStick = 0;
  70129. _this._buttonRightStick = 0;
  70130. _this._dPadUp = 0;
  70131. _this._dPadDown = 0;
  70132. _this._dPadLeft = 0;
  70133. _this._dPadRight = 0;
  70134. _this._isXboxOnePad = false;
  70135. _this.type = BABYLON.Gamepad.XBOX;
  70136. _this._isXboxOnePad = xboxOne;
  70137. return _this;
  70138. }
  70139. /**
  70140. * Defines the callback to call when left trigger is pressed
  70141. * @param callback defines the callback to use
  70142. */
  70143. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70144. this._onlefttriggerchanged = callback;
  70145. };
  70146. /**
  70147. * Defines the callback to call when right trigger is pressed
  70148. * @param callback defines the callback to use
  70149. */
  70150. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70151. this._onrighttriggerchanged = callback;
  70152. };
  70153. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70154. /**
  70155. * Gets or sets left trigger value
  70156. */
  70157. get: function () {
  70158. return this._leftTrigger;
  70159. },
  70160. set: function (newValue) {
  70161. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70162. this._onlefttriggerchanged(newValue);
  70163. }
  70164. this._leftTrigger = newValue;
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70170. /**
  70171. * Gets or sets right trigger value
  70172. */
  70173. get: function () {
  70174. return this._rightTrigger;
  70175. },
  70176. set: function (newValue) {
  70177. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70178. this._onrighttriggerchanged(newValue);
  70179. }
  70180. this._rightTrigger = newValue;
  70181. },
  70182. enumerable: true,
  70183. configurable: true
  70184. });
  70185. /**
  70186. * Defines the callback to call when a button is pressed
  70187. * @param callback defines the callback to use
  70188. */
  70189. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70190. this._onbuttondown = callback;
  70191. };
  70192. /**
  70193. * Defines the callback to call when a button is released
  70194. * @param callback defines the callback to use
  70195. */
  70196. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70197. this._onbuttonup = callback;
  70198. };
  70199. /**
  70200. * Defines the callback to call when a pad is pressed
  70201. * @param callback defines the callback to use
  70202. */
  70203. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70204. this._ondpaddown = callback;
  70205. };
  70206. /**
  70207. * Defines the callback to call when a pad is released
  70208. * @param callback defines the callback to use
  70209. */
  70210. Xbox360Pad.prototype.ondpadup = function (callback) {
  70211. this._ondpadup = callback;
  70212. };
  70213. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70214. if (newValue !== currentValue) {
  70215. if (newValue === 1) {
  70216. if (this._onbuttondown) {
  70217. this._onbuttondown(buttonType);
  70218. }
  70219. this.onButtonDownObservable.notifyObservers(buttonType);
  70220. }
  70221. if (newValue === 0) {
  70222. if (this._onbuttonup) {
  70223. this._onbuttonup(buttonType);
  70224. }
  70225. this.onButtonUpObservable.notifyObservers(buttonType);
  70226. }
  70227. }
  70228. return newValue;
  70229. };
  70230. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70231. if (newValue !== currentValue) {
  70232. if (newValue === 1) {
  70233. if (this._ondpaddown) {
  70234. this._ondpaddown(buttonType);
  70235. }
  70236. this.onPadDownObservable.notifyObservers(buttonType);
  70237. }
  70238. if (newValue === 0) {
  70239. if (this._ondpadup) {
  70240. this._ondpadup(buttonType);
  70241. }
  70242. this.onPadUpObservable.notifyObservers(buttonType);
  70243. }
  70244. }
  70245. return newValue;
  70246. };
  70247. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70248. /** Gets or sets value of A button */
  70249. get: function () {
  70250. return this._buttonA;
  70251. },
  70252. set: function (value) {
  70253. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70254. },
  70255. enumerable: true,
  70256. configurable: true
  70257. });
  70258. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70259. /** Gets or sets value of B button */
  70260. get: function () {
  70261. return this._buttonB;
  70262. },
  70263. set: function (value) {
  70264. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70265. },
  70266. enumerable: true,
  70267. configurable: true
  70268. });
  70269. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70270. /** Gets or sets value of X button */
  70271. get: function () {
  70272. return this._buttonX;
  70273. },
  70274. set: function (value) {
  70275. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70276. },
  70277. enumerable: true,
  70278. configurable: true
  70279. });
  70280. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70281. /** Gets or sets value of Y button */
  70282. get: function () {
  70283. return this._buttonY;
  70284. },
  70285. set: function (value) {
  70286. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70287. },
  70288. enumerable: true,
  70289. configurable: true
  70290. });
  70291. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70292. /** Gets or sets value of Start button */
  70293. get: function () {
  70294. return this._buttonStart;
  70295. },
  70296. set: function (value) {
  70297. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70303. /** Gets or sets value of Back button */
  70304. get: function () {
  70305. return this._buttonBack;
  70306. },
  70307. set: function (value) {
  70308. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70309. },
  70310. enumerable: true,
  70311. configurable: true
  70312. });
  70313. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70314. /** Gets or sets value of Left button */
  70315. get: function () {
  70316. return this._buttonLB;
  70317. },
  70318. set: function (value) {
  70319. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70320. },
  70321. enumerable: true,
  70322. configurable: true
  70323. });
  70324. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70325. /** Gets or sets value of Right button */
  70326. get: function () {
  70327. return this._buttonRB;
  70328. },
  70329. set: function (value) {
  70330. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70331. },
  70332. enumerable: true,
  70333. configurable: true
  70334. });
  70335. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70336. /** Gets or sets value of left stick */
  70337. get: function () {
  70338. return this._buttonLeftStick;
  70339. },
  70340. set: function (value) {
  70341. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70342. },
  70343. enumerable: true,
  70344. configurable: true
  70345. });
  70346. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70347. /** Gets or sets value of right stick */
  70348. get: function () {
  70349. return this._buttonRightStick;
  70350. },
  70351. set: function (value) {
  70352. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70353. },
  70354. enumerable: true,
  70355. configurable: true
  70356. });
  70357. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70358. /** Gets or sets value of DPad up */
  70359. get: function () {
  70360. return this._dPadUp;
  70361. },
  70362. set: function (value) {
  70363. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70364. },
  70365. enumerable: true,
  70366. configurable: true
  70367. });
  70368. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70369. /** Gets or sets value of DPad down */
  70370. get: function () {
  70371. return this._dPadDown;
  70372. },
  70373. set: function (value) {
  70374. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70375. },
  70376. enumerable: true,
  70377. configurable: true
  70378. });
  70379. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70380. /** Gets or sets value of DPad left */
  70381. get: function () {
  70382. return this._dPadLeft;
  70383. },
  70384. set: function (value) {
  70385. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70386. },
  70387. enumerable: true,
  70388. configurable: true
  70389. });
  70390. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70391. /** Gets or sets value of DPad right */
  70392. get: function () {
  70393. return this._dPadRight;
  70394. },
  70395. set: function (value) {
  70396. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70397. },
  70398. enumerable: true,
  70399. configurable: true
  70400. });
  70401. /**
  70402. * Force the gamepad to synchronize with device values
  70403. */
  70404. Xbox360Pad.prototype.update = function () {
  70405. _super.prototype.update.call(this);
  70406. if (this._isXboxOnePad) {
  70407. this.buttonA = this.browserGamepad.buttons[0].value;
  70408. this.buttonB = this.browserGamepad.buttons[1].value;
  70409. this.buttonX = this.browserGamepad.buttons[2].value;
  70410. this.buttonY = this.browserGamepad.buttons[3].value;
  70411. this.buttonLB = this.browserGamepad.buttons[4].value;
  70412. this.buttonRB = this.browserGamepad.buttons[5].value;
  70413. this.leftTrigger = this.browserGamepad.axes[2];
  70414. this.rightTrigger = this.browserGamepad.axes[5];
  70415. this.buttonBack = this.browserGamepad.buttons[9].value;
  70416. this.buttonStart = this.browserGamepad.buttons[8].value;
  70417. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70418. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70419. this.dPadUp = this.browserGamepad.buttons[11].value;
  70420. this.dPadDown = this.browserGamepad.buttons[12].value;
  70421. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70422. this.dPadRight = this.browserGamepad.buttons[14].value;
  70423. }
  70424. else {
  70425. this.buttonA = this.browserGamepad.buttons[0].value;
  70426. this.buttonB = this.browserGamepad.buttons[1].value;
  70427. this.buttonX = this.browserGamepad.buttons[2].value;
  70428. this.buttonY = this.browserGamepad.buttons[3].value;
  70429. this.buttonLB = this.browserGamepad.buttons[4].value;
  70430. this.buttonRB = this.browserGamepad.buttons[5].value;
  70431. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70432. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70433. this.buttonBack = this.browserGamepad.buttons[8].value;
  70434. this.buttonStart = this.browserGamepad.buttons[9].value;
  70435. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70436. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70437. this.dPadUp = this.browserGamepad.buttons[12].value;
  70438. this.dPadDown = this.browserGamepad.buttons[13].value;
  70439. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70440. this.dPadRight = this.browserGamepad.buttons[15].value;
  70441. }
  70442. };
  70443. Xbox360Pad.prototype.dispose = function () {
  70444. _super.prototype.dispose.call(this);
  70445. this.onButtonDownObservable.clear();
  70446. this.onButtonUpObservable.clear();
  70447. this.onPadDownObservable.clear();
  70448. this.onPadUpObservable.clear();
  70449. };
  70450. return Xbox360Pad;
  70451. }(BABYLON.Gamepad));
  70452. BABYLON.Xbox360Pad = Xbox360Pad;
  70453. })(BABYLON || (BABYLON = {}));
  70454. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70455. var BABYLON;
  70456. (function (BABYLON) {
  70457. /**
  70458. * Defines the types of pose enabled controllers that are supported
  70459. */
  70460. var PoseEnabledControllerType;
  70461. (function (PoseEnabledControllerType) {
  70462. /**
  70463. * HTC Vive
  70464. */
  70465. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70466. /**
  70467. * Oculus Rift
  70468. */
  70469. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70470. /**
  70471. * Windows mixed reality
  70472. */
  70473. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70474. /**
  70475. * Samsung gear VR
  70476. */
  70477. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70478. /**
  70479. * Google Daydream
  70480. */
  70481. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70482. /**
  70483. * Generic
  70484. */
  70485. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70486. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70487. /**
  70488. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70489. */
  70490. var PoseEnabledControllerHelper = /** @class */ (function () {
  70491. function PoseEnabledControllerHelper() {
  70492. }
  70493. /**
  70494. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70495. * @param vrGamepad the gamepad to initialized
  70496. * @returns a vr controller of the type the gamepad identified as
  70497. */
  70498. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70499. // Oculus Touch
  70500. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70501. return new BABYLON.OculusTouchController(vrGamepad);
  70502. }
  70503. // Windows Mixed Reality controllers
  70504. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70505. return new BABYLON.WindowsMotionController(vrGamepad);
  70506. }
  70507. // HTC Vive
  70508. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70509. return new BABYLON.ViveController(vrGamepad);
  70510. }
  70511. // Samsung/Oculus Gear VR or Oculus Go
  70512. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  70513. return new BABYLON.GearVRController(vrGamepad);
  70514. }
  70515. // Google Daydream
  70516. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70517. return new BABYLON.DaydreamController(vrGamepad);
  70518. }
  70519. // Generic
  70520. else {
  70521. return new BABYLON.GenericController(vrGamepad);
  70522. }
  70523. };
  70524. return PoseEnabledControllerHelper;
  70525. }());
  70526. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70527. /**
  70528. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70529. */
  70530. var PoseEnabledController = /** @class */ (function (_super) {
  70531. __extends(PoseEnabledController, _super);
  70532. /**
  70533. * Creates a new PoseEnabledController from a gamepad
  70534. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70535. */
  70536. function PoseEnabledController(browserGamepad) {
  70537. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70538. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70539. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70540. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70541. /**
  70542. * The device position in babylon space
  70543. */
  70544. _this.devicePosition = BABYLON.Vector3.Zero();
  70545. /**
  70546. * The device rotation in babylon space
  70547. */
  70548. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70549. /**
  70550. * The scale factor of the device in babylon space
  70551. */
  70552. _this.deviceScaleFactor = 1;
  70553. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70554. /**
  70555. * Internal, matrix used to convert room space to babylon space
  70556. */
  70557. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70558. /**
  70559. * Node to be used when casting a ray from the controller
  70560. */
  70561. _this._pointingPoseNode = null;
  70562. _this._workingMatrix = BABYLON.Matrix.Identity();
  70563. /**
  70564. * @hidden
  70565. */
  70566. _this._meshAttachedObservable = new BABYLON.Observable();
  70567. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70568. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70569. _this.position = BABYLON.Vector3.Zero();
  70570. _this.rotationQuaternion = new BABYLON.Quaternion();
  70571. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70572. _this._calculatedRotation = new BABYLON.Quaternion();
  70573. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70574. return _this;
  70575. }
  70576. /**
  70577. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70578. */
  70579. PoseEnabledController.prototype.update = function () {
  70580. _super.prototype.update.call(this);
  70581. var pose = this.browserGamepad.pose;
  70582. this.updateFromDevice(pose);
  70583. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70584. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70585. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70586. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70587. if (this._mesh) {
  70588. this._mesh.position.copyFrom(this.devicePosition);
  70589. if (this._mesh.rotationQuaternion) {
  70590. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70591. }
  70592. }
  70593. };
  70594. /**
  70595. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70596. * @param poseData raw pose fromthe device
  70597. */
  70598. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70599. if (poseData) {
  70600. this.rawPose = poseData;
  70601. if (poseData.position) {
  70602. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70603. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70604. this._deviceRoomPosition.z *= -1;
  70605. }
  70606. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70607. this._calculatedPosition.addInPlace(this.position);
  70608. }
  70609. var pose = this.rawPose;
  70610. if (poseData.orientation && pose.orientation) {
  70611. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70612. if (this._mesh) {
  70613. if (this._mesh.getScene().useRightHandedSystem) {
  70614. this._deviceRoomRotationQuaternion.z *= -1;
  70615. this._deviceRoomRotationQuaternion.w *= -1;
  70616. }
  70617. else {
  70618. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70619. }
  70620. }
  70621. // if the camera is set, rotate to the camera's rotation
  70622. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70623. }
  70624. }
  70625. };
  70626. /**
  70627. * Attaches a mesh to the controller
  70628. * @param mesh the mesh to be attached
  70629. */
  70630. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70631. if (this._mesh) {
  70632. this._mesh.parent = null;
  70633. }
  70634. this._mesh = mesh;
  70635. if (this._poseControlledCamera) {
  70636. this._mesh.parent = this._poseControlledCamera;
  70637. }
  70638. if (!this._mesh.rotationQuaternion) {
  70639. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70640. }
  70641. this._meshAttachedObservable.notifyObservers(mesh);
  70642. };
  70643. /**
  70644. * Attaches the controllers mesh to a camera
  70645. * @param camera the camera the mesh should be attached to
  70646. */
  70647. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70648. this._poseControlledCamera = camera;
  70649. if (this._mesh) {
  70650. this._mesh.parent = this._poseControlledCamera;
  70651. }
  70652. };
  70653. /**
  70654. * Disposes of the controller
  70655. */
  70656. PoseEnabledController.prototype.dispose = function () {
  70657. if (this._mesh) {
  70658. this._mesh.dispose();
  70659. }
  70660. this._mesh = null;
  70661. _super.prototype.dispose.call(this);
  70662. };
  70663. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70664. /**
  70665. * The mesh that is attached to the controller
  70666. */
  70667. get: function () {
  70668. return this._mesh;
  70669. },
  70670. enumerable: true,
  70671. configurable: true
  70672. });
  70673. /**
  70674. * Gets the ray of the controller in the direction the controller is pointing
  70675. * @param length the length the resulting ray should be
  70676. * @returns a ray in the direction the controller is pointing
  70677. */
  70678. PoseEnabledController.prototype.getForwardRay = function (length) {
  70679. if (length === void 0) { length = 100; }
  70680. if (!this.mesh) {
  70681. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70682. }
  70683. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70684. var origin = m.getTranslation();
  70685. var forward = new BABYLON.Vector3(0, 0, -1);
  70686. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70687. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70688. return new BABYLON.Ray(origin, direction, length);
  70689. };
  70690. /**
  70691. * Name of the child mesh that can be used to cast a ray from the controller
  70692. */
  70693. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70694. return PoseEnabledController;
  70695. }(BABYLON.Gamepad));
  70696. BABYLON.PoseEnabledController = PoseEnabledController;
  70697. })(BABYLON || (BABYLON = {}));
  70698. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70699. var BABYLON;
  70700. (function (BABYLON) {
  70701. /**
  70702. * Defines the WebVRController object that represents controllers tracked in 3D space
  70703. */
  70704. var WebVRController = /** @class */ (function (_super) {
  70705. __extends(WebVRController, _super);
  70706. /**
  70707. * Creates a new WebVRController from a gamepad
  70708. * @param vrGamepad the gamepad that the WebVRController should be created from
  70709. */
  70710. function WebVRController(vrGamepad) {
  70711. var _this = _super.call(this, vrGamepad) || this;
  70712. // Observables
  70713. /**
  70714. * Fired when the trigger state has changed
  70715. */
  70716. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70717. /**
  70718. * Fired when the main button state has changed
  70719. */
  70720. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70721. /**
  70722. * Fired when the secondary button state has changed
  70723. */
  70724. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70725. /**
  70726. * Fired when the pad state has changed
  70727. */
  70728. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70729. /**
  70730. * Fired when controllers stick values have changed
  70731. */
  70732. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70733. /**
  70734. * X and Y axis corrisponding to the controllers joystick
  70735. */
  70736. _this.pad = { x: 0, y: 0 };
  70737. // avoid GC, store state in a tmp object
  70738. _this._changes = {
  70739. pressChanged: false,
  70740. touchChanged: false,
  70741. valueChanged: false,
  70742. changed: false
  70743. };
  70744. _this._buttons = new Array(vrGamepad.buttons.length);
  70745. _this.hand = vrGamepad.hand;
  70746. return _this;
  70747. }
  70748. /**
  70749. * Fired when a controller button's state has changed
  70750. * @param callback the callback containing the button that was modified
  70751. */
  70752. WebVRController.prototype.onButtonStateChange = function (callback) {
  70753. this._onButtonStateChange = callback;
  70754. };
  70755. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70756. /**
  70757. * The default controller model for the controller
  70758. */
  70759. get: function () {
  70760. return this._defaultModel;
  70761. },
  70762. enumerable: true,
  70763. configurable: true
  70764. });
  70765. /**
  70766. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70767. */
  70768. WebVRController.prototype.update = function () {
  70769. _super.prototype.update.call(this);
  70770. for (var index = 0; index < this._buttons.length; index++) {
  70771. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70772. }
  70773. ;
  70774. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70775. this.pad.x = this.leftStick.x;
  70776. this.pad.y = this.leftStick.y;
  70777. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70778. }
  70779. };
  70780. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70781. if (!newState) {
  70782. newState = {
  70783. pressed: false,
  70784. touched: false,
  70785. value: 0
  70786. };
  70787. }
  70788. if (!currentState) {
  70789. this._buttons[buttonIndex] = {
  70790. pressed: newState.pressed,
  70791. touched: newState.touched,
  70792. value: newState.value
  70793. };
  70794. return;
  70795. }
  70796. this._checkChanges(newState, currentState);
  70797. if (this._changes.changed) {
  70798. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70799. this._handleButtonChange(buttonIndex, newState, this._changes);
  70800. }
  70801. this._buttons[buttonIndex].pressed = newState.pressed;
  70802. this._buttons[buttonIndex].touched = newState.touched;
  70803. // oculus triggers are never 0, thou not touched.
  70804. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70805. };
  70806. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70807. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70808. this._changes.touchChanged = newState.touched !== currentState.touched;
  70809. this._changes.valueChanged = newState.value !== currentState.value;
  70810. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70811. return this._changes;
  70812. };
  70813. /**
  70814. * Disposes of th webVRCOntroller
  70815. */
  70816. WebVRController.prototype.dispose = function () {
  70817. _super.prototype.dispose.call(this);
  70818. this.onTriggerStateChangedObservable.clear();
  70819. this.onMainButtonStateChangedObservable.clear();
  70820. this.onSecondaryButtonStateChangedObservable.clear();
  70821. this.onPadStateChangedObservable.clear();
  70822. this.onPadValuesChangedObservable.clear();
  70823. };
  70824. return WebVRController;
  70825. }(BABYLON.PoseEnabledController));
  70826. BABYLON.WebVRController = WebVRController;
  70827. })(BABYLON || (BABYLON = {}));
  70828. //# sourceMappingURL=babylon.webVRController.js.map
  70829. var BABYLON;
  70830. (function (BABYLON) {
  70831. /**
  70832. * Oculus Touch Controller
  70833. */
  70834. var OculusTouchController = /** @class */ (function (_super) {
  70835. __extends(OculusTouchController, _super);
  70836. /**
  70837. * Creates a new OculusTouchController from a gamepad
  70838. * @param vrGamepad the gamepad that the controller should be created from
  70839. */
  70840. function OculusTouchController(vrGamepad) {
  70841. var _this = _super.call(this, vrGamepad) || this;
  70842. /**
  70843. * Fired when the secondary trigger on this controller is modified
  70844. */
  70845. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70846. /**
  70847. * Fired when the thumb rest on this controller is modified
  70848. */
  70849. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70850. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70851. return _this;
  70852. }
  70853. /**
  70854. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70855. * @param scene scene in which to add meshes
  70856. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70857. */
  70858. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70859. var _this = this;
  70860. var meshName;
  70861. // Hand
  70862. if (this.hand === 'left') {
  70863. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70864. }
  70865. else { // Right is the default if no hand is specified
  70866. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70867. }
  70868. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70869. /*
  70870. Parent Mesh name: oculus_touch_left
  70871. - body
  70872. - trigger
  70873. - thumbstick
  70874. - grip
  70875. - button_y
  70876. - button_x
  70877. - button_enter
  70878. */
  70879. _this._defaultModel = newMeshes[1];
  70880. _this.attachToMesh(_this._defaultModel);
  70881. if (meshLoaded) {
  70882. meshLoaded(_this._defaultModel);
  70883. }
  70884. });
  70885. };
  70886. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70887. /**
  70888. * Fired when the A button on this controller is modified
  70889. */
  70890. get: function () {
  70891. if (this.hand === 'right') {
  70892. return this.onMainButtonStateChangedObservable;
  70893. }
  70894. else {
  70895. throw new Error('No A button on left hand');
  70896. }
  70897. },
  70898. enumerable: true,
  70899. configurable: true
  70900. });
  70901. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70902. /**
  70903. * Fired when the B button on this controller is modified
  70904. */
  70905. get: function () {
  70906. if (this.hand === 'right') {
  70907. return this.onSecondaryButtonStateChangedObservable;
  70908. }
  70909. else {
  70910. throw new Error('No B button on left hand');
  70911. }
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70917. /**
  70918. * Fired when the X button on this controller is modified
  70919. */
  70920. get: function () {
  70921. if (this.hand === 'left') {
  70922. return this.onMainButtonStateChangedObservable;
  70923. }
  70924. else {
  70925. throw new Error('No X button on right hand');
  70926. }
  70927. },
  70928. enumerable: true,
  70929. configurable: true
  70930. });
  70931. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70932. /**
  70933. * Fired when the Y button on this controller is modified
  70934. */
  70935. get: function () {
  70936. if (this.hand === 'left') {
  70937. return this.onSecondaryButtonStateChangedObservable;
  70938. }
  70939. else {
  70940. throw new Error('No Y button on right hand');
  70941. }
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. /**
  70947. * Called once for each button that changed state since the last frame
  70948. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70949. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70950. * 2) secondary trigger (same)
  70951. * 3) A (right) X (left), touch, pressed = value
  70952. * 4) B / Y
  70953. * 5) thumb rest
  70954. * @param buttonIdx Which button index changed
  70955. * @param state New state of the button
  70956. * @param changes Which properties on the state changed since last frame
  70957. */
  70958. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70959. var notifyObject = state; //{ state: state, changes: changes };
  70960. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70961. switch (buttonIdx) {
  70962. case 0:
  70963. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70964. return;
  70965. case 1: // index trigger
  70966. if (this._defaultModel) {
  70967. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70968. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70969. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70970. }
  70971. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70972. return;
  70973. case 2: // secondary trigger
  70974. if (this._defaultModel) {
  70975. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70976. }
  70977. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70978. return;
  70979. case 3:
  70980. if (this._defaultModel) {
  70981. if (notifyObject.pressed) {
  70982. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70983. }
  70984. else {
  70985. (this._defaultModel.getChildren()[1]).position.y = 0;
  70986. }
  70987. }
  70988. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70989. return;
  70990. case 4:
  70991. if (this._defaultModel) {
  70992. if (notifyObject.pressed) {
  70993. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70994. }
  70995. else {
  70996. (this._defaultModel.getChildren()[2]).position.y = 0;
  70997. }
  70998. }
  70999. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71000. return;
  71001. case 5:
  71002. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71003. return;
  71004. }
  71005. };
  71006. /**
  71007. * Base Url for the controller model.
  71008. */
  71009. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71010. /**
  71011. * File name for the left controller model.
  71012. */
  71013. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71014. /**
  71015. * File name for the right controller model.
  71016. */
  71017. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71018. return OculusTouchController;
  71019. }(BABYLON.WebVRController));
  71020. BABYLON.OculusTouchController = OculusTouchController;
  71021. })(BABYLON || (BABYLON = {}));
  71022. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71023. var BABYLON;
  71024. (function (BABYLON) {
  71025. /**
  71026. * Vive Controller
  71027. */
  71028. var ViveController = /** @class */ (function (_super) {
  71029. __extends(ViveController, _super);
  71030. /**
  71031. * Creates a new ViveController from a gamepad
  71032. * @param vrGamepad the gamepad that the controller should be created from
  71033. */
  71034. function ViveController(vrGamepad) {
  71035. var _this = _super.call(this, vrGamepad) || this;
  71036. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71037. _this._invertLeftStickY = true;
  71038. return _this;
  71039. }
  71040. /**
  71041. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71042. * @param scene scene in which to add meshes
  71043. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71044. */
  71045. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71046. var _this = this;
  71047. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71048. /*
  71049. Parent Mesh name: ViveWand
  71050. - body
  71051. - r_gripper
  71052. - l_gripper
  71053. - menu_button
  71054. - system_button
  71055. - trackpad
  71056. - trigger
  71057. - LED
  71058. */
  71059. _this._defaultModel = newMeshes[1];
  71060. _this.attachToMesh(_this._defaultModel);
  71061. if (meshLoaded) {
  71062. meshLoaded(_this._defaultModel);
  71063. }
  71064. });
  71065. };
  71066. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71067. /**
  71068. * Fired when the left button on this controller is modified
  71069. */
  71070. get: function () {
  71071. return this.onMainButtonStateChangedObservable;
  71072. },
  71073. enumerable: true,
  71074. configurable: true
  71075. });
  71076. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71077. /**
  71078. * Fired when the right button on this controller is modified
  71079. */
  71080. get: function () {
  71081. return this.onMainButtonStateChangedObservable;
  71082. },
  71083. enumerable: true,
  71084. configurable: true
  71085. });
  71086. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71087. /**
  71088. * Fired when the menu button on this controller is modified
  71089. */
  71090. get: function () {
  71091. return this.onSecondaryButtonStateChangedObservable;
  71092. },
  71093. enumerable: true,
  71094. configurable: true
  71095. });
  71096. /**
  71097. * Called once for each button that changed state since the last frame
  71098. * Vive mapping:
  71099. * 0: touchpad
  71100. * 1: trigger
  71101. * 2: left AND right buttons
  71102. * 3: menu button
  71103. * @param buttonIdx Which button index changed
  71104. * @param state New state of the button
  71105. * @param changes Which properties on the state changed since last frame
  71106. */
  71107. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71108. var notifyObject = state; //{ state: state, changes: changes };
  71109. switch (buttonIdx) {
  71110. case 0:
  71111. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71112. return;
  71113. case 1: // index trigger
  71114. if (this._defaultModel) {
  71115. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71116. }
  71117. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71118. return;
  71119. case 2: // left AND right button
  71120. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71121. return;
  71122. case 3:
  71123. if (this._defaultModel) {
  71124. if (notifyObject.pressed) {
  71125. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71126. }
  71127. else {
  71128. (this._defaultModel.getChildren()[2]).position.y = 0;
  71129. }
  71130. }
  71131. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71132. return;
  71133. }
  71134. };
  71135. /**
  71136. * Base Url for the controller model.
  71137. */
  71138. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71139. /**
  71140. * File name for the controller model.
  71141. */
  71142. ViveController.MODEL_FILENAME = 'wand.babylon';
  71143. return ViveController;
  71144. }(BABYLON.WebVRController));
  71145. BABYLON.ViveController = ViveController;
  71146. })(BABYLON || (BABYLON = {}));
  71147. //# sourceMappingURL=babylon.viveController.js.map
  71148. var BABYLON;
  71149. (function (BABYLON) {
  71150. /**
  71151. * Generic Controller
  71152. */
  71153. var GenericController = /** @class */ (function (_super) {
  71154. __extends(GenericController, _super);
  71155. /**
  71156. * Creates a new GenericController from a gamepad
  71157. * @param vrGamepad the gamepad that the controller should be created from
  71158. */
  71159. function GenericController(vrGamepad) {
  71160. return _super.call(this, vrGamepad) || this;
  71161. }
  71162. /**
  71163. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71164. * @param scene scene in which to add meshes
  71165. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71166. */
  71167. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71168. var _this = this;
  71169. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71170. _this._defaultModel = newMeshes[1];
  71171. _this.attachToMesh(_this._defaultModel);
  71172. if (meshLoaded) {
  71173. meshLoaded(_this._defaultModel);
  71174. }
  71175. });
  71176. };
  71177. /**
  71178. * Called once for each button that changed state since the last frame
  71179. * @param buttonIdx Which button index changed
  71180. * @param state New state of the button
  71181. * @param changes Which properties on the state changed since last frame
  71182. */
  71183. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71184. console.log("Button id: " + buttonIdx + "state: ");
  71185. console.dir(state);
  71186. };
  71187. /**
  71188. * Base Url for the controller model.
  71189. */
  71190. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71191. /**
  71192. * File name for the controller model.
  71193. */
  71194. GenericController.MODEL_FILENAME = 'generic.babylon';
  71195. return GenericController;
  71196. }(BABYLON.WebVRController));
  71197. BABYLON.GenericController = GenericController;
  71198. })(BABYLON || (BABYLON = {}));
  71199. //# sourceMappingURL=babylon.genericController.js.map
  71200. var BABYLON;
  71201. (function (BABYLON) {
  71202. /**
  71203. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71204. */
  71205. var LoadedMeshInfo = /** @class */ (function () {
  71206. function LoadedMeshInfo() {
  71207. /**
  71208. * Map of the button meshes contained in the controller
  71209. */
  71210. this.buttonMeshes = {};
  71211. /**
  71212. * Map of the axis meshes contained in the controller
  71213. */
  71214. this.axisMeshes = {};
  71215. }
  71216. return LoadedMeshInfo;
  71217. }());
  71218. /**
  71219. * Defines the WindowsMotionController object that the state of the windows motion controller
  71220. */
  71221. var WindowsMotionController = /** @class */ (function (_super) {
  71222. __extends(WindowsMotionController, _super);
  71223. /**
  71224. * Creates a new WindowsMotionController from a gamepad
  71225. * @param vrGamepad the gamepad that the controller should be created from
  71226. */
  71227. function WindowsMotionController(vrGamepad) {
  71228. var _this = _super.call(this, vrGamepad) || this;
  71229. _this._mapping = {
  71230. // Semantic button names
  71231. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71232. // A mapping of the button name to glTF model node name
  71233. // that should be transformed by button value.
  71234. buttonMeshNames: {
  71235. 'trigger': 'SELECT',
  71236. 'menu': 'MENU',
  71237. 'grip': 'GRASP',
  71238. 'thumbstick': 'THUMBSTICK_PRESS',
  71239. 'trackpad': 'TOUCHPAD_PRESS'
  71240. },
  71241. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71242. buttonObservableNames: {
  71243. 'trigger': 'onTriggerStateChangedObservable',
  71244. 'menu': 'onSecondaryButtonStateChangedObservable',
  71245. 'grip': 'onMainButtonStateChangedObservable',
  71246. 'thumbstick': 'onPadStateChangedObservable',
  71247. 'trackpad': 'onTrackpadChangedObservable'
  71248. },
  71249. // A mapping of the axis name to glTF model node name
  71250. // that should be transformed by axis value.
  71251. // This array mirrors the browserGamepad.axes array, such that
  71252. // the mesh corresponding to axis 0 is in this array index 0.
  71253. axisMeshNames: [
  71254. 'THUMBSTICK_X',
  71255. 'THUMBSTICK_Y',
  71256. 'TOUCHPAD_TOUCH_X',
  71257. 'TOUCHPAD_TOUCH_Y'
  71258. ],
  71259. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71260. };
  71261. /**
  71262. * Fired when the trackpad on this controller is clicked
  71263. */
  71264. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71265. /**
  71266. * Fired when the trackpad on this controller is modified
  71267. */
  71268. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71269. /**
  71270. * The current x and y values of this controller's trackpad
  71271. */
  71272. _this.trackpad = { x: 0, y: 0 };
  71273. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71274. _this._loadedMeshInfo = null;
  71275. return _this;
  71276. }
  71277. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71278. /**
  71279. * Fired when the trigger on this controller is modified
  71280. */
  71281. get: function () {
  71282. return this.onTriggerStateChangedObservable;
  71283. },
  71284. enumerable: true,
  71285. configurable: true
  71286. });
  71287. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71288. /**
  71289. * Fired when the menu button on this controller is modified
  71290. */
  71291. get: function () {
  71292. return this.onSecondaryButtonStateChangedObservable;
  71293. },
  71294. enumerable: true,
  71295. configurable: true
  71296. });
  71297. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71298. /**
  71299. * Fired when the grip button on this controller is modified
  71300. */
  71301. get: function () {
  71302. return this.onMainButtonStateChangedObservable;
  71303. },
  71304. enumerable: true,
  71305. configurable: true
  71306. });
  71307. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71308. /**
  71309. * Fired when the thumbstick button on this controller is modified
  71310. */
  71311. get: function () {
  71312. return this.onPadStateChangedObservable;
  71313. },
  71314. enumerable: true,
  71315. configurable: true
  71316. });
  71317. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71318. /**
  71319. * Fired when the touchpad button on this controller is modified
  71320. */
  71321. get: function () {
  71322. return this.onTrackpadChangedObservable;
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71328. /**
  71329. * Fired when the touchpad values on this controller are modified
  71330. */
  71331. get: function () {
  71332. return this.onTrackpadValuesChangedObservable;
  71333. },
  71334. enumerable: true,
  71335. configurable: true
  71336. });
  71337. WindowsMotionController.prototype._updateTrackpad = function () {
  71338. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71339. this.trackpad.x = this.browserGamepad["axes"][2];
  71340. this.trackpad.y = this.browserGamepad["axes"][3];
  71341. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71342. }
  71343. };
  71344. /**
  71345. * Called once per frame by the engine.
  71346. */
  71347. WindowsMotionController.prototype.update = function () {
  71348. _super.prototype.update.call(this);
  71349. if (this.browserGamepad.axes) {
  71350. this._updateTrackpad();
  71351. // Only need to animate axes if there is a loaded mesh
  71352. if (this._loadedMeshInfo) {
  71353. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71354. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71355. }
  71356. }
  71357. }
  71358. };
  71359. /**
  71360. * Called once for each button that changed state since the last frame
  71361. * @param buttonIdx Which button index changed
  71362. * @param state New state of the button
  71363. * @param changes Which properties on the state changed since last frame
  71364. */
  71365. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71366. var buttonName = this._mapping.buttons[buttonIdx];
  71367. if (!buttonName) {
  71368. return;
  71369. }
  71370. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71371. this._updateTrackpad();
  71372. // Only emit events for buttons that we know how to map from index to name
  71373. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71374. if (observable) {
  71375. observable.notifyObservers(state);
  71376. }
  71377. this._lerpButtonTransform(buttonName, state.value);
  71378. };
  71379. /**
  71380. * Moves the buttons on the controller mesh based on their current state
  71381. * @param buttonName the name of the button to move
  71382. * @param buttonValue the value of the button which determines the buttons new position
  71383. */
  71384. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71385. // If there is no loaded mesh, there is nothing to transform.
  71386. if (!this._loadedMeshInfo) {
  71387. return;
  71388. }
  71389. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71390. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71391. return;
  71392. }
  71393. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71394. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71395. };
  71396. /**
  71397. * Moves the axis on the controller mesh based on its current state
  71398. * @param axis the index of the axis
  71399. * @param axisValue the value of the axis which determines the meshes new position
  71400. * @hidden
  71401. */
  71402. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71403. if (!this._loadedMeshInfo) {
  71404. return;
  71405. }
  71406. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71407. if (!meshInfo) {
  71408. return;
  71409. }
  71410. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71411. return;
  71412. }
  71413. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71414. var lerpValue = axisValue * 0.5 + 0.5;
  71415. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71416. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71417. };
  71418. /**
  71419. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71420. * @param scene scene in which to add meshes
  71421. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71422. */
  71423. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71424. var _this = this;
  71425. if (forceDefault === void 0) { forceDefault = false; }
  71426. var path;
  71427. var filename;
  71428. // Checking if GLB loader is present
  71429. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71430. // Determine the device specific folder based on the ID suffix
  71431. var device = 'default';
  71432. if (this.id && !forceDefault) {
  71433. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71434. device = ((match && match[0]) || device);
  71435. }
  71436. // Hand
  71437. if (this.hand === 'left') {
  71438. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71439. }
  71440. else { // Right is the default if no hand is specified
  71441. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71442. }
  71443. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71444. }
  71445. else {
  71446. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71447. path = BABYLON.GenericController.MODEL_BASE_URL;
  71448. filename = BABYLON.GenericController.MODEL_FILENAME;
  71449. }
  71450. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71451. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71452. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71453. if (!_this._loadedMeshInfo) {
  71454. return;
  71455. }
  71456. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71457. _this.attachToMesh(_this._defaultModel);
  71458. if (meshLoaded) {
  71459. meshLoaded(_this._defaultModel);
  71460. }
  71461. }, null, function (scene, message) {
  71462. BABYLON.Tools.Log(message);
  71463. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71464. if (!forceDefault) {
  71465. _this.initControllerMesh(scene, meshLoaded, true);
  71466. }
  71467. });
  71468. };
  71469. /**
  71470. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71471. * can be transformed by button presses and axes values, based on this._mapping.
  71472. *
  71473. * @param scene scene in which the meshes exist
  71474. * @param meshes list of meshes that make up the controller model to process
  71475. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71476. */
  71477. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71478. var loadedMeshInfo = null;
  71479. // Create a new mesh to contain the glTF hierarchy
  71480. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71481. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71482. var childMesh = null;
  71483. for (var i = 0; i < meshes.length; i++) {
  71484. var mesh = meshes[i];
  71485. if (!mesh.parent) {
  71486. // Exclude controller meshes from picking results
  71487. mesh.isPickable = false;
  71488. // Handle root node, attach to the new parentMesh
  71489. childMesh = mesh;
  71490. break;
  71491. }
  71492. }
  71493. if (childMesh) {
  71494. childMesh.setParent(parentMesh);
  71495. // Create our mesh info. Note that this method will always return non-null.
  71496. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71497. }
  71498. else {
  71499. BABYLON.Tools.Warn('Could not find root node in model file.');
  71500. }
  71501. return loadedMeshInfo;
  71502. };
  71503. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71504. var loadedMeshInfo = new LoadedMeshInfo();
  71505. var i;
  71506. loadedMeshInfo.rootNode = rootNode;
  71507. // Reset the caches
  71508. loadedMeshInfo.buttonMeshes = {};
  71509. loadedMeshInfo.axisMeshes = {};
  71510. // Button Meshes
  71511. for (i = 0; i < this._mapping.buttons.length; i++) {
  71512. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71513. if (!buttonMeshName) {
  71514. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71515. continue;
  71516. }
  71517. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71518. if (!buttonMesh) {
  71519. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71520. continue;
  71521. }
  71522. var buttonMeshInfo = {
  71523. index: i,
  71524. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71525. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71526. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71527. };
  71528. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71529. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71530. }
  71531. else {
  71532. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71533. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71534. '(VALUE: ' + !!buttonMeshInfo.value +
  71535. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71536. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71537. ')');
  71538. }
  71539. }
  71540. // Axis Meshes
  71541. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71542. var axisMeshName = this._mapping.axisMeshNames[i];
  71543. if (!axisMeshName) {
  71544. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71545. continue;
  71546. }
  71547. var axisMesh = getChildByName(rootNode, axisMeshName);
  71548. if (!axisMesh) {
  71549. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71550. continue;
  71551. }
  71552. var axisMeshInfo = {
  71553. index: i,
  71554. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71555. min: getImmediateChildByName(axisMesh, 'MIN'),
  71556. max: getImmediateChildByName(axisMesh, 'MAX')
  71557. };
  71558. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71559. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71560. }
  71561. else {
  71562. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71563. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71564. '(VALUE: ' + !!axisMeshInfo.value +
  71565. ', MIN: ' + !!axisMeshInfo.min +
  71566. ', MAX:' + !!axisMeshInfo.max +
  71567. ')');
  71568. }
  71569. }
  71570. // Pointing Ray
  71571. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71572. if (!loadedMeshInfo.pointingPoseNode) {
  71573. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71574. }
  71575. return loadedMeshInfo;
  71576. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71577. function getChildByName(node, name) {
  71578. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71579. }
  71580. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71581. function getImmediateChildByName(node, name) {
  71582. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71583. }
  71584. };
  71585. /**
  71586. * Gets the ray of the controller in the direction the controller is pointing
  71587. * @param length the length the resulting ray should be
  71588. * @returns a ray in the direction the controller is pointing
  71589. */
  71590. WindowsMotionController.prototype.getForwardRay = function (length) {
  71591. if (length === void 0) { length = 100; }
  71592. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71593. return _super.prototype.getForwardRay.call(this, length);
  71594. }
  71595. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71596. var origin = m.getTranslation();
  71597. var forward = new BABYLON.Vector3(0, 0, -1);
  71598. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71599. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71600. return new BABYLON.Ray(origin, direction, length);
  71601. };
  71602. /**
  71603. * Disposes of the controller
  71604. */
  71605. WindowsMotionController.prototype.dispose = function () {
  71606. _super.prototype.dispose.call(this);
  71607. this.onTrackpadChangedObservable.clear();
  71608. };
  71609. /**
  71610. * The base url used to load the left and right controller models
  71611. */
  71612. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71613. /**
  71614. * The name of the left controller model file
  71615. */
  71616. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71617. /**
  71618. * The name of the right controller model file
  71619. */
  71620. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71621. /**
  71622. * The controller name prefix for this controller type
  71623. */
  71624. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71625. /**
  71626. * The controller id pattern for this controller type
  71627. */
  71628. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71629. return WindowsMotionController;
  71630. }(BABYLON.WebVRController));
  71631. BABYLON.WindowsMotionController = WindowsMotionController;
  71632. })(BABYLON || (BABYLON = {}));
  71633. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71634. var BABYLON;
  71635. (function (BABYLON) {
  71636. /**
  71637. * Gear VR Controller
  71638. */
  71639. var GearVRController = /** @class */ (function (_super) {
  71640. __extends(GearVRController, _super);
  71641. /**
  71642. * Creates a new GearVRController from a gamepad
  71643. * @param vrGamepad the gamepad that the controller should be created from
  71644. */
  71645. function GearVRController(vrGamepad) {
  71646. var _this = _super.call(this, vrGamepad) || this;
  71647. _this._buttonIndexToObservableNameMap = [
  71648. 'onTrackpadChangedObservable',
  71649. 'onTriggerStateChangedObservable' // Trigger
  71650. ];
  71651. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71652. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  71653. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  71654. return _this;
  71655. }
  71656. /**
  71657. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71658. * @param scene scene in which to add meshes
  71659. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71660. */
  71661. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71662. var _this = this;
  71663. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71664. _this._defaultModel = newMeshes[1];
  71665. _this.attachToMesh(_this._defaultModel);
  71666. if (meshLoaded) {
  71667. meshLoaded(_this._defaultModel);
  71668. }
  71669. });
  71670. };
  71671. /**
  71672. * Called once for each button that changed state since the last frame
  71673. * @param buttonIdx Which button index changed
  71674. * @param state New state of the button
  71675. * @param changes Which properties on the state changed since last frame
  71676. */
  71677. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71678. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71679. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71680. // Only emit events for buttons that we know how to map from index to observable
  71681. var observable = this[observableName];
  71682. if (observable) {
  71683. observable.notifyObservers(state);
  71684. }
  71685. }
  71686. };
  71687. /**
  71688. * Base Url for the controller model.
  71689. */
  71690. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71691. /**
  71692. * File name for the controller model.
  71693. */
  71694. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71695. /**
  71696. * Gamepad Id prefix used to identify this controller.
  71697. */
  71698. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71699. return GearVRController;
  71700. }(BABYLON.WebVRController));
  71701. BABYLON.GearVRController = GearVRController;
  71702. })(BABYLON || (BABYLON = {}));
  71703. //# sourceMappingURL=babylon.gearVRController.js.map
  71704. var BABYLON;
  71705. (function (BABYLON) {
  71706. /**
  71707. * Google Daydream controller
  71708. */
  71709. var DaydreamController = /** @class */ (function (_super) {
  71710. __extends(DaydreamController, _super);
  71711. /**
  71712. * Creates a new DaydreamController from a gamepad
  71713. * @param vrGamepad the gamepad that the controller should be created from
  71714. */
  71715. function DaydreamController(vrGamepad) {
  71716. var _this = _super.call(this, vrGamepad) || this;
  71717. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71718. return _this;
  71719. }
  71720. /**
  71721. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71722. * @param scene scene in which to add meshes
  71723. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71724. */
  71725. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71726. var _this = this;
  71727. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71728. _this._defaultModel = newMeshes[1];
  71729. _this.attachToMesh(_this._defaultModel);
  71730. if (meshLoaded) {
  71731. meshLoaded(_this._defaultModel);
  71732. }
  71733. });
  71734. };
  71735. /**
  71736. * Called once for each button that changed state since the last frame
  71737. * @param buttonIdx Which button index changed
  71738. * @param state New state of the button
  71739. * @param changes Which properties on the state changed since last frame
  71740. */
  71741. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71742. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71743. if (buttonIdx === 0) {
  71744. var observable = this.onTriggerStateChangedObservable;
  71745. if (observable) {
  71746. observable.notifyObservers(state);
  71747. }
  71748. }
  71749. else {
  71750. // If the app or home buttons are ever made available
  71751. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71752. }
  71753. };
  71754. /**
  71755. * Base Url for the controller model.
  71756. */
  71757. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71758. /**
  71759. * File name for the controller model.
  71760. */
  71761. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71762. /**
  71763. * Gamepad Id prefix used to identify Daydream Controller.
  71764. */
  71765. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71766. return DaydreamController;
  71767. }(BABYLON.WebVRController));
  71768. BABYLON.DaydreamController = DaydreamController;
  71769. })(BABYLON || (BABYLON = {}));
  71770. //# sourceMappingURL=babylon.daydreamController.js.map
  71771. var BABYLON;
  71772. (function (BABYLON) {
  71773. var FollowCamera = /** @class */ (function (_super) {
  71774. __extends(FollowCamera, _super);
  71775. function FollowCamera(name, position, scene, lockedTarget) {
  71776. if (lockedTarget === void 0) { lockedTarget = null; }
  71777. var _this = _super.call(this, name, position, scene) || this;
  71778. _this.radius = 12;
  71779. _this.rotationOffset = 0;
  71780. _this.heightOffset = 4;
  71781. _this.cameraAcceleration = 0.05;
  71782. _this.maxCameraSpeed = 20;
  71783. _this.lockedTarget = lockedTarget;
  71784. return _this;
  71785. }
  71786. FollowCamera.prototype.getRadians = function (degrees) {
  71787. return degrees * Math.PI / 180;
  71788. };
  71789. FollowCamera.prototype.follow = function (cameraTarget) {
  71790. if (!cameraTarget)
  71791. return;
  71792. var yRotation;
  71793. if (cameraTarget.rotationQuaternion) {
  71794. var rotMatrix = new BABYLON.Matrix();
  71795. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71796. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71797. }
  71798. else {
  71799. yRotation = cameraTarget.rotation.y;
  71800. }
  71801. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71802. var targetPosition = cameraTarget.getAbsolutePosition();
  71803. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71804. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71805. var dx = targetX - this.position.x;
  71806. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71807. var dz = (targetZ) - this.position.z;
  71808. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71809. var vy = dy * this.cameraAcceleration;
  71810. var vz = dz * this.cameraAcceleration * 2;
  71811. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71812. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71813. }
  71814. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71815. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71816. }
  71817. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71818. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71819. }
  71820. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71821. this.setTarget(targetPosition);
  71822. };
  71823. FollowCamera.prototype._checkInputs = function () {
  71824. _super.prototype._checkInputs.call(this);
  71825. if (this.lockedTarget) {
  71826. this.follow(this.lockedTarget);
  71827. }
  71828. };
  71829. FollowCamera.prototype.getClassName = function () {
  71830. return "FollowCamera";
  71831. };
  71832. __decorate([
  71833. BABYLON.serialize()
  71834. ], FollowCamera.prototype, "radius", void 0);
  71835. __decorate([
  71836. BABYLON.serialize()
  71837. ], FollowCamera.prototype, "rotationOffset", void 0);
  71838. __decorate([
  71839. BABYLON.serialize()
  71840. ], FollowCamera.prototype, "heightOffset", void 0);
  71841. __decorate([
  71842. BABYLON.serialize()
  71843. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71844. __decorate([
  71845. BABYLON.serialize()
  71846. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71847. __decorate([
  71848. BABYLON.serializeAsMeshReference("lockedTargetId")
  71849. ], FollowCamera.prototype, "lockedTarget", void 0);
  71850. return FollowCamera;
  71851. }(BABYLON.TargetCamera));
  71852. BABYLON.FollowCamera = FollowCamera;
  71853. var ArcFollowCamera = /** @class */ (function (_super) {
  71854. __extends(ArcFollowCamera, _super);
  71855. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71856. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71857. _this.alpha = alpha;
  71858. _this.beta = beta;
  71859. _this.radius = radius;
  71860. _this.target = target;
  71861. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71862. _this.follow();
  71863. return _this;
  71864. }
  71865. ArcFollowCamera.prototype.follow = function () {
  71866. if (!this.target) {
  71867. return;
  71868. }
  71869. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71870. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71871. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71872. var targetPosition = this.target.getAbsolutePosition();
  71873. this.position = targetPosition.add(this._cartesianCoordinates);
  71874. this.setTarget(targetPosition);
  71875. };
  71876. ArcFollowCamera.prototype._checkInputs = function () {
  71877. _super.prototype._checkInputs.call(this);
  71878. this.follow();
  71879. };
  71880. ArcFollowCamera.prototype.getClassName = function () {
  71881. return "ArcFollowCamera";
  71882. };
  71883. return ArcFollowCamera;
  71884. }(BABYLON.TargetCamera));
  71885. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71886. })(BABYLON || (BABYLON = {}));
  71887. //# sourceMappingURL=babylon.followCamera.js.map
  71888. var BABYLON;
  71889. (function (BABYLON) {
  71890. // We're mainly based on the logic defined into the FreeCamera code
  71891. var UniversalCamera = /** @class */ (function (_super) {
  71892. __extends(UniversalCamera, _super);
  71893. //-- end properties for backward compatibility for inputs
  71894. function UniversalCamera(name, position, scene) {
  71895. var _this = _super.call(this, name, position, scene) || this;
  71896. _this.inputs.addGamepad();
  71897. return _this;
  71898. }
  71899. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71900. //-- Begin properties for backward compatibility for inputs
  71901. get: function () {
  71902. var gamepad = this.inputs.attached["gamepad"];
  71903. if (gamepad)
  71904. return gamepad.gamepadAngularSensibility;
  71905. return 0;
  71906. },
  71907. set: function (value) {
  71908. var gamepad = this.inputs.attached["gamepad"];
  71909. if (gamepad)
  71910. gamepad.gamepadAngularSensibility = value;
  71911. },
  71912. enumerable: true,
  71913. configurable: true
  71914. });
  71915. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71916. get: function () {
  71917. var gamepad = this.inputs.attached["gamepad"];
  71918. if (gamepad)
  71919. return gamepad.gamepadMoveSensibility;
  71920. return 0;
  71921. },
  71922. set: function (value) {
  71923. var gamepad = this.inputs.attached["gamepad"];
  71924. if (gamepad)
  71925. gamepad.gamepadMoveSensibility = value;
  71926. },
  71927. enumerable: true,
  71928. configurable: true
  71929. });
  71930. UniversalCamera.prototype.getClassName = function () {
  71931. return "UniversalCamera";
  71932. };
  71933. return UniversalCamera;
  71934. }(BABYLON.TouchCamera));
  71935. BABYLON.UniversalCamera = UniversalCamera;
  71936. })(BABYLON || (BABYLON = {}));
  71937. //# sourceMappingURL=babylon.universalCamera.js.map
  71938. var BABYLON;
  71939. (function (BABYLON) {
  71940. // We're mainly based on the logic defined into the FreeCamera code
  71941. var GamepadCamera = /** @class */ (function (_super) {
  71942. __extends(GamepadCamera, _super);
  71943. //-- end properties for backward compatibility for inputs
  71944. function GamepadCamera(name, position, scene) {
  71945. return _super.call(this, name, position, scene) || this;
  71946. }
  71947. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71948. //-- Begin properties for backward compatibility for inputs
  71949. get: function () {
  71950. var gamepad = this.inputs.attached["gamepad"];
  71951. if (gamepad)
  71952. return gamepad.gamepadAngularSensibility;
  71953. return 0;
  71954. },
  71955. set: function (value) {
  71956. var gamepad = this.inputs.attached["gamepad"];
  71957. if (gamepad)
  71958. gamepad.gamepadAngularSensibility = value;
  71959. },
  71960. enumerable: true,
  71961. configurable: true
  71962. });
  71963. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71964. get: function () {
  71965. var gamepad = this.inputs.attached["gamepad"];
  71966. if (gamepad)
  71967. return gamepad.gamepadMoveSensibility;
  71968. return 0;
  71969. },
  71970. set: function (value) {
  71971. var gamepad = this.inputs.attached["gamepad"];
  71972. if (gamepad)
  71973. gamepad.gamepadMoveSensibility = value;
  71974. },
  71975. enumerable: true,
  71976. configurable: true
  71977. });
  71978. GamepadCamera.prototype.getClassName = function () {
  71979. return "GamepadCamera";
  71980. };
  71981. return GamepadCamera;
  71982. }(BABYLON.UniversalCamera));
  71983. BABYLON.GamepadCamera = GamepadCamera;
  71984. })(BABYLON || (BABYLON = {}));
  71985. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71986. var BABYLON;
  71987. (function (BABYLON) {
  71988. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71989. function PostProcessRenderPipelineManager() {
  71990. this._renderPipelines = {};
  71991. }
  71992. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71993. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71994. };
  71995. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71996. if (unique === void 0) { unique = false; }
  71997. var renderPipeline = this._renderPipelines[renderPipelineName];
  71998. if (!renderPipeline) {
  71999. return;
  72000. }
  72001. renderPipeline._attachCameras(cameras, unique);
  72002. };
  72003. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72004. var renderPipeline = this._renderPipelines[renderPipelineName];
  72005. if (!renderPipeline) {
  72006. return;
  72007. }
  72008. renderPipeline._detachCameras(cameras);
  72009. };
  72010. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72011. var renderPipeline = this._renderPipelines[renderPipelineName];
  72012. if (!renderPipeline) {
  72013. return;
  72014. }
  72015. renderPipeline._enableEffect(renderEffectName, cameras);
  72016. };
  72017. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72018. var renderPipeline = this._renderPipelines[renderPipelineName];
  72019. if (!renderPipeline) {
  72020. return;
  72021. }
  72022. renderPipeline._disableEffect(renderEffectName, cameras);
  72023. };
  72024. PostProcessRenderPipelineManager.prototype.update = function () {
  72025. for (var renderPipelineName in this._renderPipelines) {
  72026. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72027. var pipeline = this._renderPipelines[renderPipelineName];
  72028. if (!pipeline.isSupported) {
  72029. pipeline.dispose();
  72030. delete this._renderPipelines[renderPipelineName];
  72031. }
  72032. else {
  72033. pipeline._update();
  72034. }
  72035. }
  72036. }
  72037. };
  72038. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72039. for (var renderPipelineName in this._renderPipelines) {
  72040. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72041. var pipeline = this._renderPipelines[renderPipelineName];
  72042. pipeline._rebuild();
  72043. }
  72044. }
  72045. };
  72046. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72047. for (var renderPipelineName in this._renderPipelines) {
  72048. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72049. var pipeline = this._renderPipelines[renderPipelineName];
  72050. pipeline.dispose();
  72051. }
  72052. }
  72053. };
  72054. return PostProcessRenderPipelineManager;
  72055. }());
  72056. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72057. })(BABYLON || (BABYLON = {}));
  72058. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72059. var BABYLON;
  72060. (function (BABYLON) {
  72061. /**
  72062. * This represents a set of one or more post processes in Babylon.
  72063. * A post process can be used to apply a shader to a texture after it is rendered.
  72064. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72065. */
  72066. var PostProcessRenderEffect = /** @class */ (function () {
  72067. /**
  72068. * Instantiates a post process render effect.
  72069. * A post process can be used to apply a shader to a texture after it is rendered.
  72070. * @param engine The engine the effect is tied to
  72071. * @param name The name of the effect
  72072. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72073. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72074. */
  72075. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72076. this._name = name;
  72077. this._singleInstance = singleInstance || true;
  72078. this._getPostProcesses = getPostProcesses;
  72079. this._cameras = {};
  72080. this._indicesForCamera = {};
  72081. this._postProcesses = {};
  72082. }
  72083. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72084. /**
  72085. * Checks if all the post processes in the effect are supported.
  72086. */
  72087. get: function () {
  72088. for (var index in this._postProcesses) {
  72089. if (this._postProcesses.hasOwnProperty(index)) {
  72090. var pps = this._postProcesses[index];
  72091. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72092. if (!pps[ppIndex].isSupported) {
  72093. return false;
  72094. }
  72095. }
  72096. }
  72097. }
  72098. return true;
  72099. },
  72100. enumerable: true,
  72101. configurable: true
  72102. });
  72103. /**
  72104. * Updates the current state of the effect
  72105. */
  72106. PostProcessRenderEffect.prototype._update = function () {
  72107. };
  72108. /**
  72109. * Attaches the effect on cameras
  72110. * @param cameras The camera to attach to.
  72111. */
  72112. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72113. var _this = this;
  72114. var cameraKey;
  72115. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72116. if (!cams) {
  72117. return;
  72118. }
  72119. for (var i = 0; i < cams.length; i++) {
  72120. var camera = cams[i];
  72121. var cameraName = camera.name;
  72122. if (this._singleInstance) {
  72123. cameraKey = 0;
  72124. }
  72125. else {
  72126. cameraKey = cameraName;
  72127. }
  72128. if (!this._postProcesses[cameraKey]) {
  72129. var postProcess = this._getPostProcesses();
  72130. if (postProcess) {
  72131. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72132. }
  72133. }
  72134. if (!this._indicesForCamera[cameraName]) {
  72135. this._indicesForCamera[cameraName] = [];
  72136. }
  72137. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72138. var index = camera.attachPostProcess(postProcess);
  72139. _this._indicesForCamera[cameraName].push(index);
  72140. });
  72141. if (!this._cameras[cameraName]) {
  72142. this._cameras[cameraName] = camera;
  72143. }
  72144. }
  72145. };
  72146. /**
  72147. * Detatches the effect on cameras
  72148. * @param cameras The camera to detatch from.
  72149. */
  72150. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72151. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72152. if (!cams) {
  72153. return;
  72154. }
  72155. for (var i = 0; i < cams.length; i++) {
  72156. var camera = cams[i];
  72157. var cameraName = camera.name;
  72158. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72159. camera.detachPostProcess(postProcess);
  72160. });
  72161. if (this._cameras[cameraName]) {
  72162. //this._indicesForCamera.splice(index, 1);
  72163. this._cameras[cameraName] = null;
  72164. }
  72165. }
  72166. };
  72167. /**
  72168. * Enables the effect on given cameras
  72169. * @param cameras The camera to enable.
  72170. */
  72171. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72172. var _this = this;
  72173. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72174. if (!cams) {
  72175. return;
  72176. }
  72177. for (var i = 0; i < cams.length; i++) {
  72178. var camera = cams[i];
  72179. var cameraName = camera.name;
  72180. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72181. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72182. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72183. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72184. });
  72185. }
  72186. }
  72187. }
  72188. };
  72189. /**
  72190. * Disables the effect on the given cameras
  72191. * @param cameras The camera to disable.
  72192. */
  72193. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72194. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72195. if (!cams) {
  72196. return;
  72197. }
  72198. for (var i = 0; i < cams.length; i++) {
  72199. var camera = cams[i];
  72200. var cameraName = camera.name;
  72201. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72202. camera.detachPostProcess(postProcess);
  72203. });
  72204. }
  72205. };
  72206. /**
  72207. * Gets a list of the post processes contained in the effect.
  72208. * @param camera The camera to get the post processes on.
  72209. * @returns The list of the post processes in the effect.
  72210. */
  72211. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72212. if (this._singleInstance) {
  72213. return this._postProcesses[0];
  72214. }
  72215. else {
  72216. if (!camera) {
  72217. return null;
  72218. }
  72219. return this._postProcesses[camera.name];
  72220. }
  72221. };
  72222. return PostProcessRenderEffect;
  72223. }());
  72224. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72225. })(BABYLON || (BABYLON = {}));
  72226. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72227. var BABYLON;
  72228. (function (BABYLON) {
  72229. var PostProcessRenderPipeline = /** @class */ (function () {
  72230. function PostProcessRenderPipeline(engine, name) {
  72231. this.engine = engine;
  72232. this._name = name;
  72233. this._renderEffects = {};
  72234. this._renderEffectsForIsolatedPass = new Array();
  72235. this._cameras = [];
  72236. }
  72237. PostProcessRenderPipeline.prototype.getClassName = function () {
  72238. return "PostProcessRenderPipeline";
  72239. };
  72240. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72241. get: function () {
  72242. for (var renderEffectName in this._renderEffects) {
  72243. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72244. if (!this._renderEffects[renderEffectName].isSupported) {
  72245. return false;
  72246. }
  72247. }
  72248. }
  72249. return true;
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72255. this._renderEffects[renderEffect._name] = renderEffect;
  72256. };
  72257. // private
  72258. PostProcessRenderPipeline.prototype._rebuild = function () {
  72259. };
  72260. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72261. var renderEffects = this._renderEffects[renderEffectName];
  72262. if (!renderEffects) {
  72263. return;
  72264. }
  72265. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72266. };
  72267. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72268. var renderEffects = this._renderEffects[renderEffectName];
  72269. if (!renderEffects) {
  72270. return;
  72271. }
  72272. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72273. };
  72274. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72275. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72276. if (!cams) {
  72277. return;
  72278. }
  72279. var indicesToDelete = [];
  72280. var i;
  72281. for (i = 0; i < cams.length; i++) {
  72282. var camera = cams[i];
  72283. var cameraName = camera.name;
  72284. if (this._cameras.indexOf(camera) === -1) {
  72285. this._cameras[cameraName] = camera;
  72286. }
  72287. else if (unique) {
  72288. indicesToDelete.push(i);
  72289. }
  72290. }
  72291. for (i = 0; i < indicesToDelete.length; i++) {
  72292. cameras.splice(indicesToDelete[i], 1);
  72293. }
  72294. for (var renderEffectName in this._renderEffects) {
  72295. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72296. this._renderEffects[renderEffectName]._attachCameras(cams);
  72297. }
  72298. }
  72299. };
  72300. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72301. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72302. if (!cams) {
  72303. return;
  72304. }
  72305. for (var renderEffectName in this._renderEffects) {
  72306. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72307. this._renderEffects[renderEffectName]._detachCameras(cams);
  72308. }
  72309. }
  72310. for (var i = 0; i < cams.length; i++) {
  72311. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72312. }
  72313. };
  72314. PostProcessRenderPipeline.prototype._update = function () {
  72315. for (var renderEffectName in this._renderEffects) {
  72316. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72317. this._renderEffects[renderEffectName]._update();
  72318. }
  72319. }
  72320. for (var i = 0; i < this._cameras.length; i++) {
  72321. var cameraName = this._cameras[i].name;
  72322. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72323. this._renderEffectsForIsolatedPass[cameraName]._update();
  72324. }
  72325. }
  72326. };
  72327. PostProcessRenderPipeline.prototype._reset = function () {
  72328. this._renderEffects = {};
  72329. this._renderEffectsForIsolatedPass = new Array();
  72330. };
  72331. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72332. // 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)
  72333. var effectKeys = Object.keys(this._renderEffects);
  72334. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72335. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72336. if (postProcesses) {
  72337. postProcesses[0].samples = sampleCount;
  72338. return true;
  72339. }
  72340. }
  72341. return false;
  72342. };
  72343. PostProcessRenderPipeline.prototype.dispose = function () {
  72344. // Must be implemented by children
  72345. };
  72346. __decorate([
  72347. BABYLON.serialize()
  72348. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72349. return PostProcessRenderPipeline;
  72350. }());
  72351. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72352. })(BABYLON || (BABYLON = {}));
  72353. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72354. var BABYLON;
  72355. (function (BABYLON) {
  72356. /**
  72357. * This represents a depth renderer in Babylon.
  72358. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72359. */
  72360. var DepthRenderer = /** @class */ (function () {
  72361. /**
  72362. * Instantiates a depth renderer
  72363. * @param scene The scene the renderer belongs to
  72364. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72365. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72366. */
  72367. function DepthRenderer(scene, type, camera) {
  72368. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72369. if (camera === void 0) { camera = null; }
  72370. var _this = this;
  72371. this._scene = scene;
  72372. this._camera = camera;
  72373. var engine = scene.getEngine();
  72374. // Render target
  72375. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72376. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72377. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72378. this._depthMap.refreshRate = 1;
  72379. this._depthMap.renderParticles = false;
  72380. this._depthMap.renderList = null;
  72381. // Camera to get depth map from to support multiple concurrent cameras
  72382. this._depthMap.activeCamera = this._camera;
  72383. this._depthMap.ignoreCameraViewport = true;
  72384. this._depthMap.useCameraPostProcesses = false;
  72385. // set default depth value to 1.0 (far away)
  72386. this._depthMap.onClearObservable.add(function (engine) {
  72387. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72388. });
  72389. // Custom render function
  72390. var renderSubMesh = function (subMesh) {
  72391. var mesh = subMesh.getRenderingMesh();
  72392. var scene = _this._scene;
  72393. var engine = scene.getEngine();
  72394. var material = subMesh.getMaterial();
  72395. if (!material) {
  72396. return;
  72397. }
  72398. // Culling and reverse (right handed system)
  72399. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72400. // Managing instances
  72401. var batch = mesh._getInstancesRenderList(subMesh._id);
  72402. if (batch.mustReturn) {
  72403. return;
  72404. }
  72405. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72406. var camera = _this._camera || scene.activeCamera;
  72407. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72408. engine.enableEffect(_this._effect);
  72409. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72410. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72411. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72412. // Alpha test
  72413. if (material && material.needAlphaTesting()) {
  72414. var alphaTexture = material.getAlphaTestTexture();
  72415. if (alphaTexture) {
  72416. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72417. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72418. }
  72419. }
  72420. // Bones
  72421. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72422. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72423. }
  72424. // Draw
  72425. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72426. }
  72427. };
  72428. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72429. var index;
  72430. if (depthOnlySubMeshes.length) {
  72431. engine.setColorWrite(false);
  72432. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72433. renderSubMesh(depthOnlySubMeshes.data[index]);
  72434. }
  72435. engine.setColorWrite(true);
  72436. }
  72437. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72438. renderSubMesh(opaqueSubMeshes.data[index]);
  72439. }
  72440. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72441. renderSubMesh(alphaTestSubMeshes.data[index]);
  72442. }
  72443. };
  72444. }
  72445. /**
  72446. * Creates the depth rendering effect and checks if the effect is ready.
  72447. * @param subMesh The submesh to be used to render the depth map of
  72448. * @param useInstances If multiple world instances should be used
  72449. * @returns if the depth renderer is ready to render the depth map
  72450. */
  72451. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72452. var material = subMesh.getMaterial();
  72453. if (material.disableDepthWrite) {
  72454. return false;
  72455. }
  72456. var defines = [];
  72457. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72458. var mesh = subMesh.getMesh();
  72459. // Alpha test
  72460. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72461. defines.push("#define ALPHATEST");
  72462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72463. attribs.push(BABYLON.VertexBuffer.UVKind);
  72464. defines.push("#define UV1");
  72465. }
  72466. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72467. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72468. defines.push("#define UV2");
  72469. }
  72470. }
  72471. // Bones
  72472. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72475. if (mesh.numBoneInfluencers > 4) {
  72476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72478. }
  72479. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72480. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72481. }
  72482. else {
  72483. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72484. }
  72485. // Instances
  72486. if (useInstances) {
  72487. defines.push("#define INSTANCES");
  72488. attribs.push("world0");
  72489. attribs.push("world1");
  72490. attribs.push("world2");
  72491. attribs.push("world3");
  72492. }
  72493. // Get correct effect
  72494. var join = defines.join("\n");
  72495. if (this._cachedDefines !== join) {
  72496. this._cachedDefines = join;
  72497. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72498. }
  72499. return this._effect.isReady();
  72500. };
  72501. /**
  72502. * Gets the texture which the depth map will be written to.
  72503. * @returns The depth map texture
  72504. */
  72505. DepthRenderer.prototype.getDepthMap = function () {
  72506. return this._depthMap;
  72507. };
  72508. /**
  72509. * Disposes of the depth renderer.
  72510. */
  72511. DepthRenderer.prototype.dispose = function () {
  72512. this._depthMap.dispose();
  72513. };
  72514. return DepthRenderer;
  72515. }());
  72516. BABYLON.DepthRenderer = DepthRenderer;
  72517. })(BABYLON || (BABYLON = {}));
  72518. //# sourceMappingURL=babylon.depthRenderer.js.map
  72519. var BABYLON;
  72520. (function (BABYLON) {
  72521. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72522. __extends(SSAORenderingPipeline, _super);
  72523. /**
  72524. * @constructor
  72525. * @param {string} name - The rendering pipeline name
  72526. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72527. * @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 }
  72528. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72529. */
  72530. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72531. var _this = _super.call(this, scene.getEngine(), name) || this;
  72532. // Members
  72533. /**
  72534. * The PassPostProcess id in the pipeline that contains the original scene color
  72535. */
  72536. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72537. /**
  72538. * The SSAO PostProcess id in the pipeline
  72539. */
  72540. _this.SSAORenderEffect = "SSAORenderEffect";
  72541. /**
  72542. * The horizontal blur PostProcess id in the pipeline
  72543. */
  72544. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72545. /**
  72546. * The vertical blur PostProcess id in the pipeline
  72547. */
  72548. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72549. /**
  72550. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72551. */
  72552. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72553. /**
  72554. * The output strength of the SSAO post-process. Default value is 1.0.
  72555. */
  72556. _this.totalStrength = 1.0;
  72557. /**
  72558. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72559. */
  72560. _this.radius = 0.0001;
  72561. /**
  72562. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72563. * Must not be equal to fallOff and superior to fallOff.
  72564. * Default value is 0.975
  72565. */
  72566. _this.area = 0.0075;
  72567. /**
  72568. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72569. * Must not be equal to area and inferior to area.
  72570. * Default value is 0.0
  72571. */
  72572. _this.fallOff = 0.000001;
  72573. /**
  72574. * The base color of the SSAO post-process
  72575. * The final result is "base + ssao" between [0, 1]
  72576. */
  72577. _this.base = 0.5;
  72578. _this._firstUpdate = true;
  72579. _this._scene = scene;
  72580. // Set up assets
  72581. _this._createRandomTexture();
  72582. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72583. var ssaoRatio = ratio.ssaoRatio || ratio;
  72584. var combineRatio = ratio.combineRatio || ratio;
  72585. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72586. _this._createSSAOPostProcess(ssaoRatio);
  72587. _this._createBlurPostProcess(ssaoRatio);
  72588. _this._createSSAOCombinePostProcess(combineRatio);
  72589. // Set up pipeline
  72590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72595. // Finish
  72596. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72597. if (cameras)
  72598. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72599. return _this;
  72600. }
  72601. // Public Methods
  72602. /**
  72603. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72604. */
  72605. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72606. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72607. for (var i = 0; i < this._scene.cameras.length; i++) {
  72608. var camera = this._scene.cameras[i];
  72609. this._originalColorPostProcess.dispose(camera);
  72610. this._ssaoPostProcess.dispose(camera);
  72611. this._blurHPostProcess.dispose(camera);
  72612. this._blurVPostProcess.dispose(camera);
  72613. this._ssaoCombinePostProcess.dispose(camera);
  72614. }
  72615. this._randomTexture.dispose();
  72616. if (disableDepthRender)
  72617. this._scene.disableDepthRenderer();
  72618. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72619. _super.prototype.dispose.call(this);
  72620. };
  72621. // Private Methods
  72622. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72623. var _this = this;
  72624. var size = 16;
  72625. 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);
  72626. 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);
  72627. this._blurHPostProcess.onActivateObservable.add(function () {
  72628. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72629. _this._blurHPostProcess.kernel = size * dw;
  72630. });
  72631. this._blurVPostProcess.onActivateObservable.add(function () {
  72632. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72633. _this._blurVPostProcess.kernel = size * dw;
  72634. });
  72635. };
  72636. SSAORenderingPipeline.prototype._rebuild = function () {
  72637. this._firstUpdate = true;
  72638. _super.prototype._rebuild.call(this);
  72639. };
  72640. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72641. var _this = this;
  72642. var numSamples = 16;
  72643. var sampleSphere = [
  72644. 0.5381, 0.1856, -0.4319,
  72645. 0.1379, 0.2486, 0.4430,
  72646. 0.3371, 0.5679, -0.0057,
  72647. -0.6999, -0.0451, -0.0019,
  72648. 0.0689, -0.1598, -0.8547,
  72649. 0.0560, 0.0069, -0.1843,
  72650. -0.0146, 0.1402, 0.0762,
  72651. 0.0100, -0.1924, -0.0344,
  72652. -0.3577, -0.5301, -0.4358,
  72653. -0.3169, 0.1063, 0.0158,
  72654. 0.0103, -0.5869, 0.0046,
  72655. -0.0897, -0.4940, 0.3287,
  72656. 0.7119, -0.0154, -0.0918,
  72657. -0.0533, 0.0596, -0.5411,
  72658. 0.0352, -0.0631, 0.5460,
  72659. -0.4776, 0.2847, -0.0271
  72660. ];
  72661. var samplesFactor = 1.0 / numSamples;
  72662. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72663. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72664. "area", "fallOff", "base", "range", "viewport"
  72665. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72666. this._ssaoPostProcess.onApply = function (effect) {
  72667. if (_this._firstUpdate) {
  72668. effect.setArray3("sampleSphere", sampleSphere);
  72669. effect.setFloat("samplesFactor", samplesFactor);
  72670. effect.setFloat("randTextureTiles", 4.0);
  72671. }
  72672. effect.setFloat("totalStrength", _this.totalStrength);
  72673. effect.setFloat("radius", _this.radius);
  72674. effect.setFloat("area", _this.area);
  72675. effect.setFloat("fallOff", _this.fallOff);
  72676. effect.setFloat("base", _this.base);
  72677. effect.setTexture("textureSampler", _this._depthTexture);
  72678. effect.setTexture("randomSampler", _this._randomTexture);
  72679. };
  72680. };
  72681. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72682. var _this = this;
  72683. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72684. this._ssaoCombinePostProcess.onApply = function (effect) {
  72685. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  72686. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72687. };
  72688. };
  72689. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72690. var size = 512;
  72691. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72692. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72693. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72694. var context = this._randomTexture.getContext();
  72695. var rand = function (min, max) {
  72696. return Math.random() * (max - min) + min;
  72697. };
  72698. var randVector = BABYLON.Vector3.Zero();
  72699. for (var x = 0; x < size; x++) {
  72700. for (var y = 0; y < size; y++) {
  72701. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72702. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72703. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72704. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72705. context.fillRect(x, y, 1, 1);
  72706. }
  72707. }
  72708. this._randomTexture.update(false);
  72709. };
  72710. __decorate([
  72711. BABYLON.serialize()
  72712. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72713. __decorate([
  72714. BABYLON.serialize()
  72715. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72716. __decorate([
  72717. BABYLON.serialize()
  72718. ], SSAORenderingPipeline.prototype, "area", void 0);
  72719. __decorate([
  72720. BABYLON.serialize()
  72721. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72722. __decorate([
  72723. BABYLON.serialize()
  72724. ], SSAORenderingPipeline.prototype, "base", void 0);
  72725. return SSAORenderingPipeline;
  72726. }(BABYLON.PostProcessRenderPipeline));
  72727. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72728. })(BABYLON || (BABYLON = {}));
  72729. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72730. var BABYLON;
  72731. (function (BABYLON) {
  72732. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72733. __extends(SSAO2RenderingPipeline, _super);
  72734. /**
  72735. * @constructor
  72736. * @param {string} name - The rendering pipeline name
  72737. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72738. * @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 }
  72739. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72740. */
  72741. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72742. var _this = _super.call(this, scene.getEngine(), name) || this;
  72743. // Members
  72744. /**
  72745. * The PassPostProcess id in the pipeline that contains the original scene color
  72746. */
  72747. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72748. /**
  72749. * The SSAO PostProcess id in the pipeline
  72750. */
  72751. _this.SSAORenderEffect = "SSAORenderEffect";
  72752. /**
  72753. * The horizontal blur PostProcess id in the pipeline
  72754. */
  72755. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72756. /**
  72757. * The vertical blur PostProcess id in the pipeline
  72758. */
  72759. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72760. /**
  72761. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72762. */
  72763. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72764. /**
  72765. * The output strength of the SSAO post-process. Default value is 1.0.
  72766. */
  72767. _this.totalStrength = 1.0;
  72768. /**
  72769. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72770. */
  72771. _this.maxZ = 100.0;
  72772. /**
  72773. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72774. */
  72775. _this.minZAspect = 0.2;
  72776. /**
  72777. * Number of samples used for the SSAO calculations. Default value is 8
  72778. */
  72779. _this._samples = 8;
  72780. /**
  72781. * Are we using bilateral blur ?
  72782. */
  72783. _this._expensiveBlur = true;
  72784. /**
  72785. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72786. */
  72787. _this.radius = 2.0;
  72788. /**
  72789. * The base color of the SSAO post-process
  72790. * The final result is "base + ssao" between [0, 1]
  72791. */
  72792. _this.base = 0.1;
  72793. _this._firstUpdate = true;
  72794. _this._scene = scene;
  72795. _this._ratio = ratio;
  72796. if (!_this.isSupported) {
  72797. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72798. return _this;
  72799. }
  72800. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  72801. var blurRatio = _this._ratio.blurRatio || ratio;
  72802. // Set up assets
  72803. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72804. _this._createRandomTexture();
  72805. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72806. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72807. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72808. _this._createSSAOPostProcess(1.0);
  72809. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72810. _this._createSSAOCombinePostProcess(blurRatio);
  72811. // Set up pipeline
  72812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72813. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72814. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72815. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72816. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72817. // Finish
  72818. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72819. if (cameras)
  72820. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72821. return _this;
  72822. }
  72823. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72824. get: function () {
  72825. return this._samples;
  72826. },
  72827. set: function (n) {
  72828. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72829. this._samples = n;
  72830. this._sampleSphere = this._generateHemisphere();
  72831. this._firstUpdate = true;
  72832. },
  72833. enumerable: true,
  72834. configurable: true
  72835. });
  72836. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72837. get: function () {
  72838. return this._expensiveBlur;
  72839. },
  72840. set: function (b) {
  72841. 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"]);
  72842. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72843. this._expensiveBlur = b;
  72844. this._firstUpdate = true;
  72845. },
  72846. enumerable: true,
  72847. configurable: true
  72848. });
  72849. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72850. /**
  72851. * Support test.
  72852. */
  72853. get: function () {
  72854. var engine = BABYLON.Engine.LastCreatedEngine;
  72855. if (!engine) {
  72856. return false;
  72857. }
  72858. return engine.getCaps().drawBuffersExtension;
  72859. },
  72860. enumerable: true,
  72861. configurable: true
  72862. });
  72863. // Public Methods
  72864. /**
  72865. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72866. */
  72867. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72868. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72869. for (var i = 0; i < this._scene.cameras.length; i++) {
  72870. var camera = this._scene.cameras[i];
  72871. this._originalColorPostProcess.dispose(camera);
  72872. this._ssaoPostProcess.dispose(camera);
  72873. this._blurHPostProcess.dispose(camera);
  72874. this._blurVPostProcess.dispose(camera);
  72875. this._ssaoCombinePostProcess.dispose(camera);
  72876. }
  72877. this._randomTexture.dispose();
  72878. if (disableGeometryBufferRenderer)
  72879. this._scene.disableGeometryBufferRenderer();
  72880. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72881. _super.prototype.dispose.call(this);
  72882. };
  72883. // Private Methods
  72884. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72885. var _this = this;
  72886. this._samplerOffsets = [];
  72887. var expensive = this.expensiveBlur;
  72888. for (var i = -8; i < 8; i++) {
  72889. this._samplerOffsets.push(i * 2 + 0.5);
  72890. }
  72891. 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");
  72892. this._blurHPostProcess.onApply = function (effect) {
  72893. if (!_this._scene.activeCamera) {
  72894. return;
  72895. }
  72896. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72897. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72898. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72899. effect.setFloat("radius", _this.radius);
  72900. effect.setTexture("depthSampler", _this._depthTexture);
  72901. if (_this._firstUpdate) {
  72902. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72903. }
  72904. };
  72905. 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");
  72906. this._blurVPostProcess.onApply = function (effect) {
  72907. if (!_this._scene.activeCamera) {
  72908. return;
  72909. }
  72910. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72911. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72912. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72913. effect.setFloat("radius", _this.radius);
  72914. effect.setTexture("depthSampler", _this._depthTexture);
  72915. if (_this._firstUpdate) {
  72916. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72917. _this._firstUpdate = false;
  72918. }
  72919. };
  72920. };
  72921. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72922. this._firstUpdate = true;
  72923. _super.prototype._rebuild.call(this);
  72924. };
  72925. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72926. var numSamples = this.samples;
  72927. var result = [];
  72928. var vector, scale;
  72929. var rand = function (min, max) {
  72930. return Math.random() * (max - min) + min;
  72931. };
  72932. var i = 0;
  72933. while (i < numSamples) {
  72934. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72935. vector.normalize();
  72936. scale = i / numSamples;
  72937. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72938. vector.scaleInPlace(scale);
  72939. result.push(vector.x, vector.y, vector.z);
  72940. i++;
  72941. }
  72942. return result;
  72943. };
  72944. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72945. var _this = this;
  72946. var numSamples = this.samples;
  72947. this._sampleSphere = this._generateHemisphere();
  72948. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72949. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72950. "base", "range", "projection", "near", "far", "texelSize",
  72951. "xViewport", "yViewport", "maxZ", "minZAspect"
  72952. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72953. this._ssaoPostProcess.onApply = function (effect) {
  72954. if (_this._firstUpdate) {
  72955. effect.setArray3("sampleSphere", _this._sampleSphere);
  72956. effect.setFloat("randTextureTiles", 4.0);
  72957. }
  72958. if (!_this._scene.activeCamera) {
  72959. return;
  72960. }
  72961. effect.setFloat("samplesFactor", 1 / _this.samples);
  72962. effect.setFloat("totalStrength", _this.totalStrength);
  72963. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72964. effect.setFloat("radius", _this.radius);
  72965. effect.setFloat("maxZ", _this.maxZ);
  72966. effect.setFloat("minZAspect", _this.minZAspect);
  72967. effect.setFloat("base", _this.base);
  72968. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72969. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72970. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72971. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72972. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72973. effect.setTexture("textureSampler", _this._depthTexture);
  72974. effect.setTexture("normalSampler", _this._normalTexture);
  72975. effect.setTexture("randomSampler", _this._randomTexture);
  72976. };
  72977. };
  72978. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72979. var _this = this;
  72980. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72981. this._ssaoCombinePostProcess.onApply = function (effect) {
  72982. var viewport = _this._scene.activeCamera.viewport;
  72983. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  72984. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72985. };
  72986. };
  72987. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72988. var size = 512;
  72989. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72990. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72991. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72992. var context = this._randomTexture.getContext();
  72993. var rand = function (min, max) {
  72994. return Math.random() * (max - min) + min;
  72995. };
  72996. var randVector = BABYLON.Vector3.Zero();
  72997. for (var x = 0; x < size; x++) {
  72998. for (var y = 0; y < size; y++) {
  72999. randVector.x = rand(0.0, 1.0);
  73000. randVector.y = rand(0.0, 1.0);
  73001. randVector.z = 0.0;
  73002. randVector.normalize();
  73003. randVector.scaleInPlace(255);
  73004. randVector.x = Math.floor(randVector.x);
  73005. randVector.y = Math.floor(randVector.y);
  73006. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73007. context.fillRect(x, y, 1, 1);
  73008. }
  73009. }
  73010. this._randomTexture.update(false);
  73011. };
  73012. /**
  73013. * Serialize the rendering pipeline (Used when exporting)
  73014. * @returns the serialized object
  73015. */
  73016. SSAO2RenderingPipeline.prototype.serialize = function () {
  73017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73018. serializationObject.customType = "SSAO2RenderingPipeline";
  73019. return serializationObject;
  73020. };
  73021. /**
  73022. * Parse the serialized pipeline
  73023. * @param source Source pipeline.
  73024. * @param scene The scene to load the pipeline to.
  73025. * @param rootUrl The URL of the serialized pipeline.
  73026. * @returns An instantiated pipeline from the serialized object.
  73027. */
  73028. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73029. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73030. };
  73031. __decorate([
  73032. BABYLON.serialize()
  73033. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73034. __decorate([
  73035. BABYLON.serialize()
  73036. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73037. __decorate([
  73038. BABYLON.serialize()
  73039. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73040. __decorate([
  73041. BABYLON.serialize("samples")
  73042. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73043. __decorate([
  73044. BABYLON.serialize()
  73045. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73046. __decorate([
  73047. BABYLON.serialize("expensiveBlur")
  73048. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73049. __decorate([
  73050. BABYLON.serialize()
  73051. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73052. __decorate([
  73053. BABYLON.serialize()
  73054. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73055. return SSAO2RenderingPipeline;
  73056. }(BABYLON.PostProcessRenderPipeline));
  73057. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73058. })(BABYLON || (BABYLON = {}));
  73059. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73060. // BABYLON.JS Chromatic Aberration GLSL Shader
  73061. // Author: Olivier Guyot
  73062. // Separates very slightly R, G and B colors on the edges of the screen
  73063. // Inspired by Francois Tarlier & Martins Upitis
  73064. var BABYLON;
  73065. (function (BABYLON) {
  73066. var LensRenderingPipeline = /** @class */ (function (_super) {
  73067. __extends(LensRenderingPipeline, _super);
  73068. /**
  73069. * @constructor
  73070. *
  73071. * Effect parameters are as follow:
  73072. * {
  73073. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73074. * edge_blur: number; // from 0 to x (1 for realism)
  73075. * distortion: number; // from 0 to x (1 for realism)
  73076. * grain_amount: number; // from 0 to 1
  73077. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73078. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73079. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73080. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73081. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73082. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73083. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73084. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73085. * }
  73086. * Note: if an effect parameter is unset, effect is disabled
  73087. *
  73088. * @param {string} name - The rendering pipeline name
  73089. * @param {object} parameters - An object containing all parameters (see above)
  73090. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73091. * @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)
  73092. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73093. */
  73094. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73095. if (ratio === void 0) { ratio = 1.0; }
  73096. var _this = _super.call(this, scene.getEngine(), name) || this;
  73097. // Lens effects can be of the following:
  73098. // - chromatic aberration (slight shift of RGB colors)
  73099. // - blur on the edge of the lens
  73100. // - lens distortion
  73101. // - depth-of-field blur & highlights enhancing
  73102. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73103. // - grain effect (noise or custom texture)
  73104. // Two additional texture samplers are needed:
  73105. // - depth map (for depth-of-field)
  73106. // - grain texture
  73107. /**
  73108. * The chromatic aberration PostProcess id in the pipeline
  73109. */
  73110. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73111. /**
  73112. * The highlights enhancing PostProcess id in the pipeline
  73113. */
  73114. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73115. /**
  73116. * The depth-of-field PostProcess id in the pipeline
  73117. */
  73118. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73119. _this._scene = scene;
  73120. // Fetch texture samplers
  73121. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73122. if (parameters.grain_texture) {
  73123. _this._grainTexture = parameters.grain_texture;
  73124. }
  73125. else {
  73126. _this._createGrainTexture();
  73127. }
  73128. // save parameters
  73129. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73130. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73131. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73132. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73133. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73134. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73135. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73136. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73137. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73138. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73139. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73140. // Create effects
  73141. _this._createChromaticAberrationPostProcess(ratio);
  73142. _this._createHighlightsPostProcess(ratio);
  73143. _this._createDepthOfFieldPostProcess(ratio / 4);
  73144. // Set up pipeline
  73145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73148. if (_this._highlightsGain === -1) {
  73149. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73150. }
  73151. // Finish
  73152. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73153. if (cameras) {
  73154. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73155. }
  73156. return _this;
  73157. }
  73158. // public methods (self explanatory)
  73159. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73160. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73161. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73162. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73163. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73164. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73165. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73166. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73167. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73168. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73169. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73170. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73171. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73172. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73173. };
  73174. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73175. this._highlightsPostProcess.updateEffect();
  73176. };
  73177. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73178. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73179. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73180. this._highlightsGain = amount;
  73181. };
  73182. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73183. if (this._highlightsGain === -1) {
  73184. this._highlightsGain = 1.0;
  73185. }
  73186. this._highlightsThreshold = amount;
  73187. };
  73188. LensRenderingPipeline.prototype.disableHighlights = function () {
  73189. this._highlightsGain = -1;
  73190. };
  73191. /**
  73192. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73193. */
  73194. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73195. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73197. this._chromaticAberrationPostProcess = null;
  73198. this._highlightsPostProcess = null;
  73199. this._depthOfFieldPostProcess = null;
  73200. this._grainTexture.dispose();
  73201. if (disableDepthRender)
  73202. this._scene.disableDepthRenderer();
  73203. };
  73204. // colors shifting and distortion
  73205. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73206. var _this = this;
  73207. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73208. [], // samplers
  73209. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73210. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73211. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73212. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73213. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73214. effect.setFloat('radialIntensity', 1);
  73215. effect.setFloat2('direction', 17, 17);
  73216. effect.setFloat2('centerPosition', 0.5, 0.5);
  73217. };
  73218. };
  73219. // highlights enhancing
  73220. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73221. var _this = this;
  73222. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73223. [], // samplers
  73224. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73225. this._highlightsPostProcess.onApply = function (effect) {
  73226. effect.setFloat('gain', _this._highlightsGain);
  73227. effect.setFloat('threshold', _this._highlightsThreshold);
  73228. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73229. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73230. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73231. };
  73232. };
  73233. // colors shifting and distortion
  73234. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73235. var _this = this;
  73236. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73237. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73238. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73239. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73240. this._depthOfFieldPostProcess.onApply = function (effect) {
  73241. effect.setTexture("depthSampler", _this._depthTexture);
  73242. effect.setTexture("grainSampler", _this._grainTexture);
  73243. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73244. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73245. effect.setFloat('grain_amount', _this._grainAmount);
  73246. effect.setBool('blur_noise', _this._blurNoise);
  73247. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73248. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73249. effect.setFloat('distortion', _this._distortion);
  73250. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73251. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73252. effect.setFloat('aperture', _this._dofAperture);
  73253. effect.setFloat('darken', _this._dofDarken);
  73254. effect.setFloat('edge_blur', _this._edgeBlur);
  73255. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73256. if (_this._scene.activeCamera) {
  73257. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73258. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73259. }
  73260. };
  73261. };
  73262. // creates a black and white random noise texture, 512x512
  73263. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73264. var size = 512;
  73265. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73266. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73267. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73268. var context = this._grainTexture.getContext();
  73269. var rand = function (min, max) {
  73270. return Math.random() * (max - min) + min;
  73271. };
  73272. var value;
  73273. for (var x = 0; x < size; x++) {
  73274. for (var y = 0; y < size; y++) {
  73275. value = Math.floor(rand(0.42, 0.58) * 255);
  73276. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73277. context.fillRect(x, y, 1, 1);
  73278. }
  73279. }
  73280. this._grainTexture.update(false);
  73281. };
  73282. return LensRenderingPipeline;
  73283. }(BABYLON.PostProcessRenderPipeline));
  73284. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73285. })(BABYLON || (BABYLON = {}));
  73286. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73287. var BABYLON;
  73288. (function (BABYLON) {
  73289. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73290. __extends(StandardRenderingPipeline, _super);
  73291. /**
  73292. * @constructor
  73293. * @param {string} name - The rendering pipeline name
  73294. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73295. * @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)
  73296. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73297. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73298. */
  73299. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73300. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73301. var _this = _super.call(this, scene.getEngine(), name) || this;
  73302. _this.downSampleX4PostProcess = null;
  73303. _this.brightPassPostProcess = null;
  73304. _this.blurHPostProcesses = [];
  73305. _this.blurVPostProcesses = [];
  73306. _this.textureAdderPostProcess = null;
  73307. _this.volumetricLightPostProcess = null;
  73308. _this.volumetricLightSmoothXPostProcess = null;
  73309. _this.volumetricLightSmoothYPostProcess = null;
  73310. _this.volumetricLightMergePostProces = null;
  73311. _this.volumetricLightFinalPostProcess = null;
  73312. _this.luminancePostProcess = null;
  73313. _this.luminanceDownSamplePostProcesses = [];
  73314. _this.hdrPostProcess = null;
  73315. _this.textureAdderFinalPostProcess = null;
  73316. _this.lensFlareFinalPostProcess = null;
  73317. _this.hdrFinalPostProcess = null;
  73318. _this.lensFlarePostProcess = null;
  73319. _this.lensFlareComposePostProcess = null;
  73320. _this.motionBlurPostProcess = null;
  73321. _this.depthOfFieldPostProcess = null;
  73322. // Values
  73323. _this.brightThreshold = 1.0;
  73324. _this.blurWidth = 512.0;
  73325. _this.horizontalBlur = false;
  73326. _this.exposure = 1.0;
  73327. _this.lensTexture = null;
  73328. _this.volumetricLightCoefficient = 0.2;
  73329. _this.volumetricLightPower = 4.0;
  73330. _this.volumetricLightBlurScale = 64.0;
  73331. _this.sourceLight = null;
  73332. _this.hdrMinimumLuminance = 1.0;
  73333. _this.hdrDecreaseRate = 0.5;
  73334. _this.hdrIncreaseRate = 0.5;
  73335. _this.lensColorTexture = null;
  73336. _this.lensFlareStrength = 20.0;
  73337. _this.lensFlareGhostDispersal = 1.4;
  73338. _this.lensFlareHaloWidth = 0.7;
  73339. _this.lensFlareDistortionStrength = 16.0;
  73340. _this.lensStarTexture = null;
  73341. _this.lensFlareDirtTexture = null;
  73342. _this.depthOfFieldDistance = 10.0;
  73343. _this.depthOfFieldBlurWidth = 64.0;
  73344. _this.motionStrength = 1.0;
  73345. // IAnimatable
  73346. _this.animations = [];
  73347. _this._currentDepthOfFieldSource = null;
  73348. _this._hdrCurrentLuminance = 1.0;
  73349. // Getters and setters
  73350. _this._bloomEnabled = true;
  73351. _this._depthOfFieldEnabled = false;
  73352. _this._vlsEnabled = false;
  73353. _this._lensFlareEnabled = false;
  73354. _this._hdrEnabled = false;
  73355. _this._motionBlurEnabled = false;
  73356. _this._motionBlurSamples = 64.0;
  73357. _this._volumetricLightStepsCount = 50.0;
  73358. _this._cameras = cameras || [];
  73359. // Initialize
  73360. _this._scene = scene;
  73361. _this._basePostProcess = originalPostProcess;
  73362. _this._ratio = ratio;
  73363. // Misc
  73364. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73365. // Finish
  73366. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73367. _this._buildPipeline();
  73368. return _this;
  73369. }
  73370. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73371. get: function () {
  73372. return this._bloomEnabled;
  73373. },
  73374. set: function (enabled) {
  73375. if (this._bloomEnabled === enabled) {
  73376. return;
  73377. }
  73378. this._bloomEnabled = enabled;
  73379. this._buildPipeline();
  73380. },
  73381. enumerable: true,
  73382. configurable: true
  73383. });
  73384. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73385. get: function () {
  73386. return this._depthOfFieldEnabled;
  73387. },
  73388. set: function (enabled) {
  73389. if (this._depthOfFieldEnabled === enabled) {
  73390. return;
  73391. }
  73392. this._depthOfFieldEnabled = enabled;
  73393. this._buildPipeline();
  73394. },
  73395. enumerable: true,
  73396. configurable: true
  73397. });
  73398. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73399. get: function () {
  73400. return this._lensFlareEnabled;
  73401. },
  73402. set: function (enabled) {
  73403. if (this._lensFlareEnabled === enabled) {
  73404. return;
  73405. }
  73406. this._lensFlareEnabled = enabled;
  73407. this._buildPipeline();
  73408. },
  73409. enumerable: true,
  73410. configurable: true
  73411. });
  73412. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73413. get: function () {
  73414. return this._hdrEnabled;
  73415. },
  73416. set: function (enabled) {
  73417. if (this._hdrEnabled === enabled) {
  73418. return;
  73419. }
  73420. this._hdrEnabled = enabled;
  73421. this._buildPipeline();
  73422. },
  73423. enumerable: true,
  73424. configurable: true
  73425. });
  73426. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73427. get: function () {
  73428. return this._vlsEnabled;
  73429. },
  73430. set: function (enabled) {
  73431. if (this._vlsEnabled === enabled) {
  73432. return;
  73433. }
  73434. if (enabled) {
  73435. var geometry = this._scene.enableGeometryBufferRenderer();
  73436. if (!geometry) {
  73437. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73438. return;
  73439. }
  73440. }
  73441. this._vlsEnabled = enabled;
  73442. this._buildPipeline();
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73448. get: function () {
  73449. return this._motionBlurEnabled;
  73450. },
  73451. set: function (enabled) {
  73452. if (this._motionBlurEnabled === enabled) {
  73453. return;
  73454. }
  73455. this._motionBlurEnabled = enabled;
  73456. this._buildPipeline();
  73457. },
  73458. enumerable: true,
  73459. configurable: true
  73460. });
  73461. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73462. get: function () {
  73463. return this._volumetricLightStepsCount;
  73464. },
  73465. set: function (count) {
  73466. if (this.volumetricLightPostProcess) {
  73467. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73468. }
  73469. this._volumetricLightStepsCount = count;
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73475. get: function () {
  73476. return this._motionBlurSamples;
  73477. },
  73478. set: function (samples) {
  73479. if (this.motionBlurPostProcess) {
  73480. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73481. }
  73482. this._motionBlurSamples = samples;
  73483. },
  73484. enumerable: true,
  73485. configurable: true
  73486. });
  73487. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73488. var _this = this;
  73489. var ratio = this._ratio;
  73490. var scene = this._scene;
  73491. this._disposePostProcesses();
  73492. this._reset();
  73493. // Create pass post-process
  73494. if (!this._basePostProcess) {
  73495. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73496. this.originalPostProcess.onApply = function (effect) {
  73497. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73498. };
  73499. }
  73500. else {
  73501. this.originalPostProcess = this._basePostProcess;
  73502. }
  73503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73504. this._currentDepthOfFieldSource = this.originalPostProcess;
  73505. if (this._bloomEnabled) {
  73506. // Create down sample X4 post-process
  73507. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73508. // Create bright pass post-process
  73509. this._createBrightPassPostProcess(scene, ratio / 2);
  73510. // Create gaussian blur post-processes (down sampling blurs)
  73511. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73512. // Create texture adder post-process
  73513. this._createTextureAdderPostProcess(scene, ratio);
  73514. // Create depth-of-field source post-process
  73515. 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);
  73516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73517. }
  73518. if (this._vlsEnabled) {
  73519. // Create volumetric light
  73520. this._createVolumetricLightPostProcess(scene, ratio);
  73521. // Create volumetric light final post-process
  73522. 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);
  73523. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73524. }
  73525. if (this._lensFlareEnabled) {
  73526. // Create lens flare post-process
  73527. this._createLensFlarePostProcess(scene, ratio);
  73528. // Create depth-of-field source post-process post lens-flare and disable it now
  73529. 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);
  73530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73531. }
  73532. if (this._hdrEnabled) {
  73533. // Create luminance
  73534. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73535. // Create HDR
  73536. this._createHdrPostProcess(scene, ratio);
  73537. // Create depth-of-field source post-process post hdr and disable it now
  73538. 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);
  73539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73540. }
  73541. if (this._depthOfFieldEnabled) {
  73542. // Create gaussian blur used by depth-of-field
  73543. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73544. // Create depth-of-field post-process
  73545. this._createDepthOfFieldPostProcess(scene, ratio);
  73546. }
  73547. if (this._motionBlurEnabled) {
  73548. // Create motion blur post-process
  73549. this._createMotionBlurPostProcess(scene, ratio);
  73550. }
  73551. if (this._cameras !== null) {
  73552. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73553. }
  73554. };
  73555. // Down Sample X4 Post-Processs
  73556. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73557. var _this = this;
  73558. var downSampleX4Offsets = new Array(32);
  73559. 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);
  73560. this.downSampleX4PostProcess.onApply = function (effect) {
  73561. var id = 0;
  73562. var width = _this.downSampleX4PostProcess.width;
  73563. var height = _this.downSampleX4PostProcess.height;
  73564. for (var i = -2; i < 2; i++) {
  73565. for (var j = -2; j < 2; j++) {
  73566. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73567. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73568. id += 2;
  73569. }
  73570. }
  73571. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73572. };
  73573. // Add to pipeline
  73574. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73575. };
  73576. // Brightpass Post-Process
  73577. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73578. var _this = this;
  73579. var brightOffsets = new Array(8);
  73580. 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);
  73581. this.brightPassPostProcess.onApply = function (effect) {
  73582. var sU = (1.0 / _this.brightPassPostProcess.width);
  73583. var sV = (1.0 / _this.brightPassPostProcess.height);
  73584. brightOffsets[0] = -0.5 * sU;
  73585. brightOffsets[1] = 0.5 * sV;
  73586. brightOffsets[2] = 0.5 * sU;
  73587. brightOffsets[3] = 0.5 * sV;
  73588. brightOffsets[4] = -0.5 * sU;
  73589. brightOffsets[5] = -0.5 * sV;
  73590. brightOffsets[6] = 0.5 * sU;
  73591. brightOffsets[7] = -0.5 * sV;
  73592. effect.setArray2("dsOffsets", brightOffsets);
  73593. effect.setFloat("brightThreshold", _this.brightThreshold);
  73594. };
  73595. // Add to pipeline
  73596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73597. };
  73598. // Create blur H&V post-processes
  73599. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73600. var _this = this;
  73601. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73602. var engine = scene.getEngine();
  73603. 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);
  73604. 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);
  73605. blurX.onActivateObservable.add(function () {
  73606. var dw = blurX.width / engine.getRenderWidth();
  73607. blurX.kernel = _this[blurWidthKey] * dw;
  73608. });
  73609. blurY.onActivateObservable.add(function () {
  73610. var dw = blurY.height / engine.getRenderHeight();
  73611. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73612. });
  73613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73615. this.blurHPostProcesses.push(blurX);
  73616. this.blurVPostProcesses.push(blurY);
  73617. };
  73618. // Create texture adder post-process
  73619. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73620. var _this = this;
  73621. 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);
  73622. this.textureAdderPostProcess.onApply = function (effect) {
  73623. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73624. effect.setTexture("lensSampler", _this.lensTexture);
  73625. effect.setFloat("exposure", _this.exposure);
  73626. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73627. };
  73628. // Add to pipeline
  73629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73630. };
  73631. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73632. var _this = this;
  73633. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73634. geometryRenderer.enablePosition = true;
  73635. var geometry = geometryRenderer.getGBuffer();
  73636. // Base post-process
  73637. 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));
  73638. var depthValues = BABYLON.Vector2.Zero();
  73639. this.volumetricLightPostProcess.onApply = function (effect) {
  73640. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73641. var generator = _this.sourceLight.getShadowGenerator();
  73642. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73643. effect.setTexture("positionSampler", geometry.textures[2]);
  73644. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73645. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73646. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73647. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73648. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73649. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73650. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73651. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73652. effect.setVector2("depthValues", depthValues);
  73653. }
  73654. };
  73655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73656. // Smooth
  73657. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73658. // Merge
  73659. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73660. this.volumetricLightMergePostProces.onApply = function (effect) {
  73661. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73662. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73663. };
  73664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73665. };
  73666. // Create luminance
  73667. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73668. var _this = this;
  73669. // Create luminance
  73670. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73671. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73672. var offsets = [];
  73673. this.luminancePostProcess.onApply = function (effect) {
  73674. var sU = (1.0 / _this.luminancePostProcess.width);
  73675. var sV = (1.0 / _this.luminancePostProcess.height);
  73676. offsets[0] = -0.5 * sU;
  73677. offsets[1] = 0.5 * sV;
  73678. offsets[2] = 0.5 * sU;
  73679. offsets[3] = 0.5 * sV;
  73680. offsets[4] = -0.5 * sU;
  73681. offsets[5] = -0.5 * sV;
  73682. offsets[6] = 0.5 * sU;
  73683. offsets[7] = -0.5 * sV;
  73684. effect.setArray2("lumOffsets", offsets);
  73685. };
  73686. // Add to pipeline
  73687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73688. // Create down sample luminance
  73689. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73690. var size = Math.pow(3, i);
  73691. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73692. if (i === 0) {
  73693. defines += "#define FINAL_DOWN_SAMPLER";
  73694. }
  73695. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73696. this.luminanceDownSamplePostProcesses.push(postProcess);
  73697. }
  73698. // Create callbacks and add effects
  73699. var lastLuminance = this.luminancePostProcess;
  73700. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73701. var downSampleOffsets = new Array(18);
  73702. pp.onApply = function (effect) {
  73703. if (!lastLuminance) {
  73704. return;
  73705. }
  73706. var id = 0;
  73707. for (var x = -1; x < 2; x++) {
  73708. for (var y = -1; y < 2; y++) {
  73709. downSampleOffsets[id] = x / lastLuminance.width;
  73710. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73711. id += 2;
  73712. }
  73713. }
  73714. effect.setArray2("dsOffsets", downSampleOffsets);
  73715. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73716. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73717. lastLuminance = _this.luminancePostProcess;
  73718. }
  73719. else {
  73720. lastLuminance = pp;
  73721. }
  73722. };
  73723. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73724. pp.onAfterRender = function (effect) {
  73725. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73726. 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);
  73727. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73728. };
  73729. }
  73730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73731. });
  73732. };
  73733. // Create HDR post-process
  73734. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73735. var _this = this;
  73736. 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);
  73737. var outputLiminance = 1;
  73738. var time = 0;
  73739. var lastTime = 0;
  73740. this.hdrPostProcess.onApply = function (effect) {
  73741. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73742. time += scene.getEngine().getDeltaTime();
  73743. if (outputLiminance < 0) {
  73744. outputLiminance = _this._hdrCurrentLuminance;
  73745. }
  73746. else {
  73747. var dt = (lastTime - time) / 1000.0;
  73748. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73749. outputLiminance += _this.hdrDecreaseRate * dt;
  73750. }
  73751. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73752. outputLiminance -= _this.hdrIncreaseRate * dt;
  73753. }
  73754. else {
  73755. outputLiminance = _this._hdrCurrentLuminance;
  73756. }
  73757. }
  73758. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73759. effect.setFloat("averageLuminance", outputLiminance);
  73760. lastTime = time;
  73761. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73762. };
  73763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73764. };
  73765. // Create lens flare post-process
  73766. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73767. var _this = this;
  73768. 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);
  73769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73770. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73771. 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);
  73772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73773. var resolution = new BABYLON.Vector2(0, 0);
  73774. // Lens flare
  73775. this.lensFlarePostProcess.onApply = function (effect) {
  73776. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73777. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73778. effect.setFloat("strength", _this.lensFlareStrength);
  73779. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73780. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73781. // Shift
  73782. resolution.x = _this.lensFlarePostProcess.width;
  73783. resolution.y = _this.lensFlarePostProcess.height;
  73784. effect.setVector2("resolution", resolution);
  73785. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73786. };
  73787. // Compose
  73788. 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);
  73789. 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);
  73790. this.lensFlareComposePostProcess.onApply = function (effect) {
  73791. if (!_this._scene.activeCamera) {
  73792. return;
  73793. }
  73794. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73795. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73796. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73797. // Lens start rotation matrix
  73798. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73799. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73800. 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));
  73801. camRot *= 4.0;
  73802. 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);
  73803. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73804. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73805. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73806. };
  73807. };
  73808. // Create depth-of-field post-process
  73809. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73810. var _this = this;
  73811. 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);
  73812. this.depthOfFieldPostProcess.onApply = function (effect) {
  73813. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73814. effect.setTexture("depthSampler", _this._getDepthTexture());
  73815. effect.setFloat("distance", _this.depthOfFieldDistance);
  73816. };
  73817. // Add to pipeline
  73818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73819. };
  73820. // Create motion blur post-process
  73821. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73822. var _this = this;
  73823. 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);
  73824. var motionScale = 0;
  73825. var prevViewProjection = BABYLON.Matrix.Identity();
  73826. var invViewProjection = BABYLON.Matrix.Identity();
  73827. var viewProjection = BABYLON.Matrix.Identity();
  73828. var screenSize = BABYLON.Vector2.Zero();
  73829. this.motionBlurPostProcess.onApply = function (effect) {
  73830. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73831. viewProjection.invertToRef(invViewProjection);
  73832. effect.setMatrix("inverseViewProjection", invViewProjection);
  73833. effect.setMatrix("prevViewProjection", prevViewProjection);
  73834. prevViewProjection = viewProjection;
  73835. screenSize.x = _this.motionBlurPostProcess.width;
  73836. screenSize.y = _this.motionBlurPostProcess.height;
  73837. effect.setVector2("screenSize", screenSize);
  73838. motionScale = scene.getEngine().getFps() / 60.0;
  73839. effect.setFloat("motionScale", motionScale);
  73840. effect.setFloat("motionStrength", _this.motionStrength);
  73841. effect.setTexture("depthSampler", _this._getDepthTexture());
  73842. };
  73843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73844. };
  73845. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73846. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73847. var renderer = this._scene.enableGeometryBufferRenderer();
  73848. return renderer.getGBuffer().textures[0];
  73849. }
  73850. return this._scene.enableDepthRenderer().getDepthMap();
  73851. };
  73852. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73853. for (var i = 0; i < this._cameras.length; i++) {
  73854. var camera = this._cameras[i];
  73855. if (this.originalPostProcess) {
  73856. this.originalPostProcess.dispose(camera);
  73857. }
  73858. if (this.downSampleX4PostProcess) {
  73859. this.downSampleX4PostProcess.dispose(camera);
  73860. }
  73861. if (this.brightPassPostProcess) {
  73862. this.brightPassPostProcess.dispose(camera);
  73863. }
  73864. if (this.textureAdderPostProcess) {
  73865. this.textureAdderPostProcess.dispose(camera);
  73866. }
  73867. if (this.textureAdderFinalPostProcess) {
  73868. this.textureAdderFinalPostProcess.dispose(camera);
  73869. }
  73870. if (this.volumetricLightPostProcess) {
  73871. this.volumetricLightPostProcess.dispose(camera);
  73872. }
  73873. if (this.volumetricLightSmoothXPostProcess) {
  73874. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73875. }
  73876. if (this.volumetricLightSmoothYPostProcess) {
  73877. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73878. }
  73879. if (this.volumetricLightMergePostProces) {
  73880. this.volumetricLightMergePostProces.dispose(camera);
  73881. }
  73882. if (this.volumetricLightFinalPostProcess) {
  73883. this.volumetricLightFinalPostProcess.dispose(camera);
  73884. }
  73885. if (this.lensFlarePostProcess) {
  73886. this.lensFlarePostProcess.dispose(camera);
  73887. }
  73888. if (this.lensFlareComposePostProcess) {
  73889. this.lensFlareComposePostProcess.dispose(camera);
  73890. }
  73891. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73892. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73893. }
  73894. if (this.luminancePostProcess) {
  73895. this.luminancePostProcess.dispose(camera);
  73896. }
  73897. if (this.hdrPostProcess) {
  73898. this.hdrPostProcess.dispose(camera);
  73899. }
  73900. if (this.hdrFinalPostProcess) {
  73901. this.hdrFinalPostProcess.dispose(camera);
  73902. }
  73903. if (this.depthOfFieldPostProcess) {
  73904. this.depthOfFieldPostProcess.dispose(camera);
  73905. }
  73906. if (this.motionBlurPostProcess) {
  73907. this.motionBlurPostProcess.dispose(camera);
  73908. }
  73909. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73910. this.blurHPostProcesses[j].dispose(camera);
  73911. }
  73912. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73913. this.blurVPostProcesses[j].dispose(camera);
  73914. }
  73915. }
  73916. this.originalPostProcess = null;
  73917. this.downSampleX4PostProcess = null;
  73918. this.brightPassPostProcess = null;
  73919. this.textureAdderPostProcess = null;
  73920. this.textureAdderFinalPostProcess = null;
  73921. this.volumetricLightPostProcess = null;
  73922. this.volumetricLightSmoothXPostProcess = null;
  73923. this.volumetricLightSmoothYPostProcess = null;
  73924. this.volumetricLightMergePostProces = null;
  73925. this.volumetricLightFinalPostProcess = null;
  73926. this.lensFlarePostProcess = null;
  73927. this.lensFlareComposePostProcess = null;
  73928. this.luminancePostProcess = null;
  73929. this.hdrPostProcess = null;
  73930. this.hdrFinalPostProcess = null;
  73931. this.depthOfFieldPostProcess = null;
  73932. this.motionBlurPostProcess = null;
  73933. this.luminanceDownSamplePostProcesses = [];
  73934. this.blurHPostProcesses = [];
  73935. this.blurVPostProcesses = [];
  73936. };
  73937. /**
  73938. * Dispose of the pipeline and stop all post processes
  73939. */
  73940. StandardRenderingPipeline.prototype.dispose = function () {
  73941. this._disposePostProcesses();
  73942. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73943. _super.prototype.dispose.call(this);
  73944. };
  73945. /**
  73946. * Serialize the rendering pipeline (Used when exporting)
  73947. * @returns the serialized object
  73948. */
  73949. StandardRenderingPipeline.prototype.serialize = function () {
  73950. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73951. if (this.sourceLight) {
  73952. serializationObject.sourceLightId = this.sourceLight.id;
  73953. }
  73954. serializationObject.customType = "StandardRenderingPipeline";
  73955. return serializationObject;
  73956. };
  73957. /**
  73958. * Parse the serialized pipeline
  73959. * @param source Source pipeline.
  73960. * @param scene The scene to load the pipeline to.
  73961. * @param rootUrl The URL of the serialized pipeline.
  73962. * @returns An instantiated pipeline from the serialized object.
  73963. */
  73964. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73965. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73966. if (source.sourceLightId) {
  73967. p.sourceLight = scene.getLightByID(source.sourceLightId);
  73968. }
  73969. return p;
  73970. };
  73971. // Luminance steps
  73972. StandardRenderingPipeline.LuminanceSteps = 6;
  73973. __decorate([
  73974. BABYLON.serialize()
  73975. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73976. __decorate([
  73977. BABYLON.serialize()
  73978. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73979. __decorate([
  73980. BABYLON.serialize()
  73981. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73982. __decorate([
  73983. BABYLON.serialize()
  73984. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73985. __decorate([
  73986. BABYLON.serializeAsTexture("lensTexture")
  73987. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73988. __decorate([
  73989. BABYLON.serialize()
  73990. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73991. __decorate([
  73992. BABYLON.serialize()
  73993. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73994. __decorate([
  73995. BABYLON.serialize()
  73996. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73997. __decorate([
  73998. BABYLON.serialize()
  73999. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74000. __decorate([
  74001. BABYLON.serialize()
  74002. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74003. __decorate([
  74004. BABYLON.serialize()
  74005. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74006. __decorate([
  74007. BABYLON.serializeAsTexture("lensColorTexture")
  74008. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74009. __decorate([
  74010. BABYLON.serialize()
  74011. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74012. __decorate([
  74013. BABYLON.serialize()
  74014. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74015. __decorate([
  74016. BABYLON.serialize()
  74017. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74018. __decorate([
  74019. BABYLON.serialize()
  74020. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74021. __decorate([
  74022. BABYLON.serializeAsTexture("lensStarTexture")
  74023. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74024. __decorate([
  74025. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74026. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74027. __decorate([
  74028. BABYLON.serialize()
  74029. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74030. __decorate([
  74031. BABYLON.serialize()
  74032. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74033. __decorate([
  74034. BABYLON.serialize()
  74035. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74036. __decorate([
  74037. BABYLON.serialize()
  74038. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74039. __decorate([
  74040. BABYLON.serialize()
  74041. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74042. __decorate([
  74043. BABYLON.serialize()
  74044. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74045. __decorate([
  74046. BABYLON.serialize()
  74047. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74048. __decorate([
  74049. BABYLON.serialize()
  74050. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74051. __decorate([
  74052. BABYLON.serialize()
  74053. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74054. __decorate([
  74055. BABYLON.serialize()
  74056. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74057. __decorate([
  74058. BABYLON.serialize()
  74059. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74060. __decorate([
  74061. BABYLON.serialize()
  74062. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74063. return StandardRenderingPipeline;
  74064. }(BABYLON.PostProcessRenderPipeline));
  74065. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74066. })(BABYLON || (BABYLON = {}));
  74067. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74068. var BABYLON;
  74069. (function (BABYLON) {
  74070. var FxaaPostProcess = /** @class */ (function (_super) {
  74071. __extends(FxaaPostProcess, _super);
  74072. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74073. if (camera === void 0) { camera = null; }
  74074. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74075. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74076. var defines = _this._getDefines();
  74077. _this.updateEffect(defines);
  74078. _this.onApplyObservable.add(function (effect) {
  74079. var texelSize = _this.texelSize;
  74080. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74081. });
  74082. return _this;
  74083. }
  74084. FxaaPostProcess.prototype._getDefines = function () {
  74085. var engine = this.getEngine();
  74086. if (!engine) {
  74087. return null;
  74088. }
  74089. var glInfo = engine.getGlInfo();
  74090. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74091. return "#define MALI 1\n";
  74092. }
  74093. return null;
  74094. };
  74095. return FxaaPostProcess;
  74096. }(BABYLON.PostProcess));
  74097. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74098. })(BABYLON || (BABYLON = {}));
  74099. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74100. var BABYLON;
  74101. (function (BABYLON) {
  74102. /**
  74103. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74104. */
  74105. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74106. __extends(ChromaticAberrationPostProcess, _super);
  74107. /**
  74108. * Creates a new instance ChromaticAberrationPostProcess
  74109. * @param name The name of the effect.
  74110. * @param screenWidth The width of the screen to apply the effect on.
  74111. * @param screenHeight The height of the screen to apply the effect on.
  74112. * @param options The required width/height ratio to downsize to before computing the render pass.
  74113. * @param camera The camera to apply the render pass to.
  74114. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74115. * @param engine The engine which the post process will be applied. (default: current engine)
  74116. * @param reusable If the post process can be reused on the same frame. (default: false)
  74117. * @param textureType Type of textures used when performing the post process. (default: 0)
  74118. * @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)
  74119. */
  74120. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74122. if (blockCompilation === void 0) { blockCompilation = false; }
  74123. 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;
  74124. /**
  74125. * The amount of seperation of rgb channels (default: 30)
  74126. */
  74127. _this.aberrationAmount = 30;
  74128. /**
  74129. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74130. */
  74131. _this.radialIntensity = 0;
  74132. /**
  74133. * 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))
  74134. */
  74135. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74136. /**
  74137. * 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))
  74138. */
  74139. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74140. _this.onApplyObservable.add(function (effect) {
  74141. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74142. effect.setFloat('screen_width', screenWidth);
  74143. effect.setFloat('screen_height', screenHeight);
  74144. effect.setFloat('radialIntensity', _this.radialIntensity);
  74145. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74146. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74147. });
  74148. return _this;
  74149. }
  74150. return ChromaticAberrationPostProcess;
  74151. }(BABYLON.PostProcess));
  74152. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74153. })(BABYLON || (BABYLON = {}));
  74154. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74155. var BABYLON;
  74156. (function (BABYLON) {
  74157. /**
  74158. * The GrainPostProcess adds noise to the image at mid luminance levels
  74159. */
  74160. var GrainPostProcess = /** @class */ (function (_super) {
  74161. __extends(GrainPostProcess, _super);
  74162. /**
  74163. * Creates a new instance of @see GrainPostProcess
  74164. * @param name The name of the effect.
  74165. * @param options The required width/height ratio to downsize to before computing the render pass.
  74166. * @param camera The camera to apply the render pass to.
  74167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74168. * @param engine The engine which the post process will be applied. (default: current engine)
  74169. * @param reusable If the post process can be reused on the same frame. (default: false)
  74170. * @param textureType Type of textures used when performing the post process. (default: 0)
  74171. * @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)
  74172. */
  74173. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74174. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74175. if (blockCompilation === void 0) { blockCompilation = false; }
  74176. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74177. /**
  74178. * The intensity of the grain added (default: 30)
  74179. */
  74180. _this.intensity = 30;
  74181. /**
  74182. * If the grain should be randomized on every frame
  74183. */
  74184. _this.animated = false;
  74185. _this.onApplyObservable.add(function (effect) {
  74186. effect.setFloat('intensity', _this.intensity);
  74187. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74188. });
  74189. return _this;
  74190. }
  74191. return GrainPostProcess;
  74192. }(BABYLON.PostProcess));
  74193. BABYLON.GrainPostProcess = GrainPostProcess;
  74194. })(BABYLON || (BABYLON = {}));
  74195. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74196. var BABYLON;
  74197. (function (BABYLON) {
  74198. /**
  74199. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74200. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74201. */
  74202. var SharpenPostProcess = /** @class */ (function (_super) {
  74203. __extends(SharpenPostProcess, _super);
  74204. /**
  74205. * Creates a new instance ConvolutionPostProcess
  74206. * @param name The name of the effect.
  74207. * @param options The required width/height ratio to downsize to before computing the render pass.
  74208. * @param camera The camera to apply the render pass to.
  74209. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74210. * @param engine The engine which the post process will be applied. (default: current engine)
  74211. * @param reusable If the post process can be reused on the same frame. (default: false)
  74212. * @param textureType Type of textures used when performing the post process. (default: 0)
  74213. * @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)
  74214. */
  74215. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74216. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74217. if (blockCompilation === void 0) { blockCompilation = false; }
  74218. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74219. /**
  74220. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74221. */
  74222. _this.colorAmount = 1.0;
  74223. /**
  74224. * How much sharpness should be applied (default: 0.3)
  74225. */
  74226. _this.edgeAmount = 0.3;
  74227. _this.onApply = function (effect) {
  74228. effect.setFloat2("screenSize", _this.width, _this.height);
  74229. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74230. };
  74231. return _this;
  74232. }
  74233. return SharpenPostProcess;
  74234. }(BABYLON.PostProcess));
  74235. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74236. })(BABYLON || (BABYLON = {}));
  74237. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74238. var BABYLON;
  74239. (function (BABYLON) {
  74240. /**
  74241. * The Blur Post Process which blurs an image based on a kernel and direction.
  74242. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74243. */
  74244. var BlurPostProcess = /** @class */ (function (_super) {
  74245. __extends(BlurPostProcess, _super);
  74246. /**
  74247. * Creates a new instance BlurPostProcess
  74248. * @param name The name of the effect.
  74249. * @param direction The direction in which to blur the image.
  74250. * @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.
  74251. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74252. * @param camera The camera to apply the render pass to.
  74253. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74254. * @param engine The engine which the post process will be applied. (default: current engine)
  74255. * @param reusable If the post process can be reused on the same frame. (default: false)
  74256. * @param textureType Type of textures used when performing the post process. (default: 0)
  74257. * @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)
  74258. */
  74259. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74261. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74262. if (defines === void 0) { defines = ""; }
  74263. if (blockCompilation === void 0) { blockCompilation = false; }
  74264. 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;
  74265. _this.direction = direction;
  74266. _this.blockCompilation = blockCompilation;
  74267. _this._packedFloat = false;
  74268. _this._staticDefines = "";
  74269. _this._staticDefines = defines;
  74270. _this.onApplyObservable.add(function (effect) {
  74271. if (_this._outputTexture) {
  74272. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74273. }
  74274. else {
  74275. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74276. }
  74277. });
  74278. _this.kernel = kernel;
  74279. return _this;
  74280. }
  74281. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74282. /**
  74283. * Gets the length in pixels of the blur sample region
  74284. */
  74285. get: function () {
  74286. return this._idealKernel;
  74287. },
  74288. /**
  74289. * Sets the length in pixels of the blur sample region
  74290. */
  74291. set: function (v) {
  74292. if (this._idealKernel === v) {
  74293. return;
  74294. }
  74295. v = Math.max(v, 1);
  74296. this._idealKernel = v;
  74297. this._kernel = this._nearestBestKernel(v);
  74298. if (!this.blockCompilation) {
  74299. this._updateParameters();
  74300. }
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74306. /**
  74307. * Gets wether or not the blur is unpacking/repacking floats
  74308. */
  74309. get: function () {
  74310. return this._packedFloat;
  74311. },
  74312. /**
  74313. * Sets wether or not the blur needs to unpack/repack floats
  74314. */
  74315. set: function (v) {
  74316. if (this._packedFloat === v) {
  74317. return;
  74318. }
  74319. this._packedFloat = v;
  74320. if (!this.blockCompilation) {
  74321. this._updateParameters();
  74322. }
  74323. },
  74324. enumerable: true,
  74325. configurable: true
  74326. });
  74327. /**
  74328. * Updates the effect with the current post process compile time values and recompiles the shader.
  74329. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74330. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74331. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74332. * @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
  74333. * @param onCompiled Called when the shader has been compiled.
  74334. * @param onError Called if there is an error when compiling a shader.
  74335. */
  74336. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74337. if (defines === void 0) { defines = null; }
  74338. if (uniforms === void 0) { uniforms = null; }
  74339. if (samplers === void 0) { samplers = null; }
  74340. this._updateParameters(onCompiled, onError);
  74341. };
  74342. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74343. // Generate sampling offsets and weights
  74344. var N = this._kernel;
  74345. var centerIndex = (N - 1) / 2;
  74346. // Generate Gaussian sampling weights over kernel
  74347. var offsets = [];
  74348. var weights = [];
  74349. var totalWeight = 0;
  74350. for (var i = 0; i < N; i++) {
  74351. var u = i / (N - 1);
  74352. var w = this._gaussianWeight(u * 2.0 - 1);
  74353. offsets[i] = (i - centerIndex);
  74354. weights[i] = w;
  74355. totalWeight += w;
  74356. }
  74357. // Normalize weights
  74358. for (var i = 0; i < weights.length; i++) {
  74359. weights[i] /= totalWeight;
  74360. }
  74361. // Optimize: combine samples to take advantage of hardware linear sampling
  74362. // Walk from left to center, combining pairs (symmetrically)
  74363. var linearSamplingWeights = [];
  74364. var linearSamplingOffsets = [];
  74365. var linearSamplingMap = [];
  74366. for (var i = 0; i <= centerIndex; i += 2) {
  74367. var j = Math.min(i + 1, Math.floor(centerIndex));
  74368. var singleCenterSample = i === j;
  74369. if (singleCenterSample) {
  74370. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74371. }
  74372. else {
  74373. var sharedCell = j === centerIndex;
  74374. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74375. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74376. if (offsetLinear === 0) {
  74377. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74378. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74379. }
  74380. else {
  74381. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74382. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74383. }
  74384. }
  74385. }
  74386. for (var i = 0; i < linearSamplingMap.length; i++) {
  74387. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74388. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74389. }
  74390. // Replace with optimized
  74391. offsets = linearSamplingOffsets;
  74392. weights = linearSamplingWeights;
  74393. // Generate shaders
  74394. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74395. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74396. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74397. var defines = "";
  74398. defines += this._staticDefines;
  74399. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74400. if (this._staticDefines.indexOf("DOF") != -1) {
  74401. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74402. varyingCount--;
  74403. }
  74404. for (var i = 0; i < varyingCount; i++) {
  74405. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74406. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74407. }
  74408. var depCount = 0;
  74409. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74410. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74411. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74412. depCount++;
  74413. }
  74414. if (this.packedFloat) {
  74415. defines += "#define PACKEDFLOAT 1";
  74416. }
  74417. this.blockCompilation = false;
  74418. _super.prototype.updateEffect.call(this, defines, null, null, {
  74419. varyingCount: varyingCount,
  74420. depCount: depCount
  74421. }, onCompiled, onError);
  74422. };
  74423. /**
  74424. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74425. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74426. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74427. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74428. * The gaps between physical kernels are compensated for in the weighting of the samples
  74429. * @param idealKernel Ideal blur kernel.
  74430. * @return Nearest best kernel.
  74431. */
  74432. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74433. var v = Math.round(idealKernel);
  74434. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74435. var k = _a[_i];
  74436. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74437. return Math.max(k, 3);
  74438. }
  74439. }
  74440. return Math.max(v, 3);
  74441. };
  74442. /**
  74443. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74444. * @param x The point on the Gaussian distribution to sample.
  74445. * @return the value of the Gaussian function at x.
  74446. */
  74447. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74448. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74449. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74450. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74451. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74452. // truncated at around 1.3% of peak strength.
  74453. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74454. var sigma = (1 / 3);
  74455. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74456. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74457. var weight = (1.0 / denominator) * Math.exp(exponent);
  74458. return weight;
  74459. };
  74460. /**
  74461. * Generates a string that can be used as a floating point number in GLSL.
  74462. * @param x Value to print.
  74463. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74464. * @return GLSL float string.
  74465. */
  74466. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74467. if (decimalFigures === void 0) { decimalFigures = 8; }
  74468. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74469. };
  74470. return BlurPostProcess;
  74471. }(BABYLON.PostProcess));
  74472. BABYLON.BlurPostProcess = BlurPostProcess;
  74473. })(BABYLON || (BABYLON = {}));
  74474. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74475. var BABYLON;
  74476. (function (BABYLON) {
  74477. /**
  74478. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74479. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74480. * based on samples that have a large difference in distance than the center pixel.
  74481. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74482. */
  74483. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74484. __extends(DepthOfFieldBlurPostProcess, _super);
  74485. /**
  74486. * Creates a new instance CircleOfConfusionPostProcess
  74487. * @param name The name of the effect.
  74488. * @param scene The scene the effect belongs to.
  74489. * @param direction The direction the blur should be applied.
  74490. * @param kernel The size of the kernel used to blur.
  74491. * @param options The required width/height ratio to downsize to before computing the render pass.
  74492. * @param camera The camera to apply the render pass to.
  74493. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74494. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74495. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74496. * @param engine The engine which the post process will be applied. (default: current engine)
  74497. * @param reusable If the post process can be reused on the same frame. (default: false)
  74498. * @param textureType Type of textures used when performing the post process. (default: 0)
  74499. * @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)
  74500. */
  74501. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74502. if (imageToBlur === void 0) { imageToBlur = null; }
  74503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74504. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74505. if (blockCompilation === void 0) { blockCompilation = false; }
  74506. 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;
  74507. _this.direction = direction;
  74508. _this.onApplyObservable.add(function (effect) {
  74509. if (imageToBlur != null) {
  74510. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74511. }
  74512. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74513. if (scene.activeCamera) {
  74514. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74515. }
  74516. });
  74517. return _this;
  74518. }
  74519. return DepthOfFieldBlurPostProcess;
  74520. }(BABYLON.BlurPostProcess));
  74521. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74522. })(BABYLON || (BABYLON = {}));
  74523. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74524. var BABYLON;
  74525. (function (BABYLON) {
  74526. /**
  74527. * Options to be set when merging outputs from the default pipeline.
  74528. */
  74529. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74530. function DepthOfFieldMergePostProcessOptions() {
  74531. }
  74532. return DepthOfFieldMergePostProcessOptions;
  74533. }());
  74534. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74535. /**
  74536. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74537. */
  74538. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74539. __extends(DepthOfFieldMergePostProcess, _super);
  74540. /**
  74541. * Creates a new instance of DepthOfFieldMergePostProcess
  74542. * @param name The name of the effect.
  74543. * @param originalFromInput Post process which's input will be used for the merge.
  74544. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74545. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74546. * @param options The required width/height ratio to downsize to before computing the render pass.
  74547. * @param camera The camera to apply the render pass to.
  74548. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74549. * @param engine The engine which the post process will be applied. (default: current engine)
  74550. * @param reusable If the post process can be reused on the same frame. (default: false)
  74551. * @param textureType Type of textures used when performing the post process. (default: 0)
  74552. * @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)
  74553. */
  74554. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74555. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74556. if (blockCompilation === void 0) { blockCompilation = false; }
  74557. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74558. _this.blurSteps = blurSteps;
  74559. _this.onApplyObservable.add(function (effect) {
  74560. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74561. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74562. blurSteps.forEach(function (step, index) {
  74563. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74564. });
  74565. });
  74566. if (!blockCompilation) {
  74567. _this.updateEffect();
  74568. }
  74569. return _this;
  74570. }
  74571. /**
  74572. * Updates the effect with the current post process compile time values and recompiles the shader.
  74573. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74574. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74575. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74576. * @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
  74577. * @param onCompiled Called when the shader has been compiled.
  74578. * @param onError Called if there is an error when compiling a shader.
  74579. */
  74580. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74581. if (defines === void 0) { defines = null; }
  74582. if (uniforms === void 0) { uniforms = null; }
  74583. if (samplers === void 0) { samplers = null; }
  74584. if (!defines) {
  74585. defines = "";
  74586. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74587. }
  74588. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74589. };
  74590. return DepthOfFieldMergePostProcess;
  74591. }(BABYLON.PostProcess));
  74592. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74593. })(BABYLON || (BABYLON = {}));
  74594. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74595. var BABYLON;
  74596. (function (BABYLON) {
  74597. /**
  74598. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74599. */
  74600. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74601. __extends(CircleOfConfusionPostProcess, _super);
  74602. /**
  74603. * Creates a new instance CircleOfConfusionPostProcess
  74604. * @param name The name of the effect.
  74605. * @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.
  74606. * @param options The required width/height ratio to downsize to before computing the render pass.
  74607. * @param camera The camera to apply the render pass to.
  74608. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74609. * @param engine The engine which the post process will be applied. (default: current engine)
  74610. * @param reusable If the post process can be reused on the same frame. (default: false)
  74611. * @param textureType Type of textures used when performing the post process. (default: 0)
  74612. * @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)
  74613. */
  74614. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74615. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74616. if (blockCompilation === void 0) { blockCompilation = false; }
  74617. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74618. /**
  74619. * 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.
  74620. */
  74621. _this.lensSize = 50;
  74622. /**
  74623. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74624. */
  74625. _this.fStop = 1.4;
  74626. /**
  74627. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74628. */
  74629. _this.focusDistance = 2000;
  74630. /**
  74631. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74632. */
  74633. _this.focalLength = 50;
  74634. _this._depthTexture = null;
  74635. _this._depthTexture = depthTexture;
  74636. _this.onApplyObservable.add(function (effect) {
  74637. if (!_this._depthTexture) {
  74638. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74639. return;
  74640. }
  74641. effect.setTexture("depthSampler", _this._depthTexture);
  74642. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74643. var aperture = _this.lensSize / _this.fStop;
  74644. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74645. effect.setFloat('focusDistance', _this.focusDistance);
  74646. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74647. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74648. });
  74649. return _this;
  74650. }
  74651. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74652. /**
  74653. * 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.
  74654. */
  74655. set: function (value) {
  74656. this._depthTexture = value;
  74657. },
  74658. enumerable: true,
  74659. configurable: true
  74660. });
  74661. return CircleOfConfusionPostProcess;
  74662. }(BABYLON.PostProcess));
  74663. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74664. })(BABYLON || (BABYLON = {}));
  74665. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74666. var BABYLON;
  74667. (function (BABYLON) {
  74668. /**
  74669. * Specifies the level of max blur that should be applied when using the depth of field effect
  74670. */
  74671. var DepthOfFieldEffectBlurLevel;
  74672. (function (DepthOfFieldEffectBlurLevel) {
  74673. /**
  74674. * Subtle blur
  74675. */
  74676. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74677. /**
  74678. * Medium blur
  74679. */
  74680. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74681. /**
  74682. * Large blur
  74683. */
  74684. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74685. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74686. ;
  74687. /**
  74688. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74689. */
  74690. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74691. __extends(DepthOfFieldEffect, _super);
  74692. /**
  74693. * Creates a new instance DepthOfFieldEffect
  74694. * @param scene The scene the effect belongs to.
  74695. * @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.
  74696. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74697. * @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)
  74698. */
  74699. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74700. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74701. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74702. if (blockCompilation === void 0) { blockCompilation = false; }
  74703. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74704. return _this._effects;
  74705. }, true) || this;
  74706. /**
  74707. * Internal post processes in depth of field effect
  74708. */
  74709. _this._effects = [];
  74710. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74711. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74712. // 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)
  74713. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74714. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74715. _this._depthOfFieldBlurY = [];
  74716. _this._depthOfFieldBlurX = [];
  74717. var blurCount = 1;
  74718. var kernelSize = 15;
  74719. switch (blurLevel) {
  74720. case DepthOfFieldEffectBlurLevel.High: {
  74721. blurCount = 3;
  74722. kernelSize = 51;
  74723. break;
  74724. }
  74725. case DepthOfFieldEffectBlurLevel.Medium: {
  74726. blurCount = 2;
  74727. kernelSize = 31;
  74728. break;
  74729. }
  74730. default: {
  74731. kernelSize = 15;
  74732. blurCount = 1;
  74733. break;
  74734. }
  74735. }
  74736. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74737. var ratio = 1.0;
  74738. for (var i = 0; i < blurCount; i++) {
  74739. 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);
  74740. blurY.autoClear = false;
  74741. ratio = 0.75 / Math.pow(2, i);
  74742. 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);
  74743. blurX.autoClear = false;
  74744. _this._depthOfFieldBlurY.push(blurY);
  74745. _this._depthOfFieldBlurX.push(blurX);
  74746. }
  74747. // Set all post processes on the effect.
  74748. _this._effects = [_this._circleOfConfusion];
  74749. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74750. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74751. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74752. }
  74753. // Merge blurred images with original image based on circleOfConfusion
  74754. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74755. _this._dofMerge.autoClear = false;
  74756. _this._effects.push(_this._dofMerge);
  74757. return _this;
  74758. }
  74759. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74760. get: function () {
  74761. return this._circleOfConfusion.focalLength;
  74762. },
  74763. /**
  74764. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74765. */
  74766. set: function (value) {
  74767. this._circleOfConfusion.focalLength = value;
  74768. },
  74769. enumerable: true,
  74770. configurable: true
  74771. });
  74772. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74773. get: function () {
  74774. return this._circleOfConfusion.fStop;
  74775. },
  74776. /**
  74777. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74778. */
  74779. set: function (value) {
  74780. this._circleOfConfusion.fStop = value;
  74781. },
  74782. enumerable: true,
  74783. configurable: true
  74784. });
  74785. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74786. get: function () {
  74787. return this._circleOfConfusion.focusDistance;
  74788. },
  74789. /**
  74790. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74791. */
  74792. set: function (value) {
  74793. this._circleOfConfusion.focusDistance = value;
  74794. },
  74795. enumerable: true,
  74796. configurable: true
  74797. });
  74798. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74799. get: function () {
  74800. return this._circleOfConfusion.lensSize;
  74801. },
  74802. /**
  74803. * 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.
  74804. */
  74805. set: function (value) {
  74806. this._circleOfConfusion.lensSize = value;
  74807. },
  74808. enumerable: true,
  74809. configurable: true
  74810. });
  74811. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74812. /**
  74813. * 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.
  74814. */
  74815. set: function (value) {
  74816. this._circleOfConfusion.depthTexture = value;
  74817. },
  74818. enumerable: true,
  74819. configurable: true
  74820. });
  74821. /**
  74822. * Disposes each of the internal effects for a given camera.
  74823. * @param camera The camera to dispose the effect on.
  74824. */
  74825. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74826. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74827. this._effects[effectIndex].dispose(camera);
  74828. }
  74829. };
  74830. /**
  74831. * Internal
  74832. */
  74833. DepthOfFieldEffect.prototype._updateEffects = function () {
  74834. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74835. this._effects[effectIndex].updateEffect();
  74836. }
  74837. };
  74838. /**
  74839. * Internal
  74840. * @returns if all the contained post processes are ready.
  74841. */
  74842. DepthOfFieldEffect.prototype._isReady = function () {
  74843. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74844. if (!this._effects[effectIndex].isReady()) {
  74845. return false;
  74846. }
  74847. }
  74848. return true;
  74849. };
  74850. return DepthOfFieldEffect;
  74851. }(BABYLON.PostProcessRenderEffect));
  74852. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74853. })(BABYLON || (BABYLON = {}));
  74854. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74855. var BABYLON;
  74856. (function (BABYLON) {
  74857. /**
  74858. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74859. */
  74860. var BloomMergePostProcess = /** @class */ (function (_super) {
  74861. __extends(BloomMergePostProcess, _super);
  74862. /**
  74863. * Creates a new instance of @see BloomMergePostProcess
  74864. * @param name The name of the effect.
  74865. * @param originalFromInput Post process which's input will be used for the merge.
  74866. * @param blurred Blurred highlights post process which's output will be used.
  74867. * @param weight Weight of the bloom to be added to the original input.
  74868. * @param options The required width/height ratio to downsize to before computing the render pass.
  74869. * @param camera The camera to apply the render pass to.
  74870. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74871. * @param engine The engine which the post process will be applied. (default: current engine)
  74872. * @param reusable If the post process can be reused on the same frame. (default: false)
  74873. * @param textureType Type of textures used when performing the post process. (default: 0)
  74874. * @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)
  74875. */
  74876. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74877. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74878. if (blockCompilation === void 0) { blockCompilation = false; }
  74879. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74880. _this.weight = weight;
  74881. _this.onApplyObservable.add(function (effect) {
  74882. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74883. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74884. effect.setFloat("bloomWeight", _this.weight);
  74885. });
  74886. if (!blockCompilation) {
  74887. _this.updateEffect();
  74888. }
  74889. return _this;
  74890. }
  74891. return BloomMergePostProcess;
  74892. }(BABYLON.PostProcess));
  74893. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74894. })(BABYLON || (BABYLON = {}));
  74895. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74896. var BABYLON;
  74897. (function (BABYLON) {
  74898. /**
  74899. * 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.
  74900. */
  74901. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74902. __extends(ExtractHighlightsPostProcess, _super);
  74903. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74904. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74905. if (blockCompilation === void 0) { blockCompilation = false; }
  74906. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74907. /**
  74908. * The luminance threshold, pixels below this value will be set to black.
  74909. */
  74910. _this.threshold = 0.9;
  74911. /**
  74912. * Internal
  74913. */
  74914. _this._exposure = 1;
  74915. /**
  74916. * Post process which has the input texture to be used when performing highlight extraction
  74917. */
  74918. _this._inputPostProcess = null;
  74919. _this.onApplyObservable.add(function (effect) {
  74920. if (_this._inputPostProcess) {
  74921. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74922. }
  74923. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74924. effect.setFloat('exposure', _this._exposure);
  74925. });
  74926. return _this;
  74927. }
  74928. return ExtractHighlightsPostProcess;
  74929. }(BABYLON.PostProcess));
  74930. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74931. })(BABYLON || (BABYLON = {}));
  74932. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74933. var BABYLON;
  74934. (function (BABYLON) {
  74935. /**
  74936. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74937. */
  74938. var BloomEffect = /** @class */ (function (_super) {
  74939. __extends(BloomEffect, _super);
  74940. /**
  74941. * Creates a new instance of @see BloomEffect
  74942. * @param scene The scene the effect belongs to.
  74943. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74944. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74945. * @param bloomWeight The the strength of bloom.
  74946. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74947. * @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)
  74948. */
  74949. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74950. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74951. if (blockCompilation === void 0) { blockCompilation = false; }
  74952. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74953. return _this._effects;
  74954. }, true) || this;
  74955. _this.bloomScale = bloomScale;
  74956. /**
  74957. * Internal
  74958. */
  74959. _this._effects = [];
  74960. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74961. _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);
  74962. _this._blurX.alwaysForcePOT = true;
  74963. _this._blurX.autoClear = false;
  74964. _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);
  74965. _this._blurY.alwaysForcePOT = true;
  74966. _this._blurY.autoClear = false;
  74967. _this.kernel = bloomKernel;
  74968. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74969. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74970. _this._merge.autoClear = false;
  74971. _this._effects.push(_this._merge);
  74972. return _this;
  74973. }
  74974. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74975. /**
  74976. * The luminance threshold to find bright areas of the image to bloom.
  74977. */
  74978. get: function () {
  74979. return this._downscale.threshold;
  74980. },
  74981. set: function (value) {
  74982. this._downscale.threshold = value;
  74983. },
  74984. enumerable: true,
  74985. configurable: true
  74986. });
  74987. Object.defineProperty(BloomEffect.prototype, "weight", {
  74988. /**
  74989. * The strength of the bloom.
  74990. */
  74991. get: function () {
  74992. return this._merge.weight;
  74993. },
  74994. set: function (value) {
  74995. this._merge.weight = value;
  74996. },
  74997. enumerable: true,
  74998. configurable: true
  74999. });
  75000. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75001. /**
  75002. * Specifies the size of the bloom blur kernel, relative to the final output size
  75003. */
  75004. get: function () {
  75005. return this._blurX.kernel / this.bloomScale;
  75006. },
  75007. set: function (value) {
  75008. this._blurX.kernel = value * this.bloomScale;
  75009. this._blurY.kernel = value * this.bloomScale;
  75010. },
  75011. enumerable: true,
  75012. configurable: true
  75013. });
  75014. /**
  75015. * Disposes each of the internal effects for a given camera.
  75016. * @param camera The camera to dispose the effect on.
  75017. */
  75018. BloomEffect.prototype.disposeEffects = function (camera) {
  75019. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75020. this._effects[effectIndex].dispose(camera);
  75021. }
  75022. };
  75023. /**
  75024. * Internal
  75025. */
  75026. BloomEffect.prototype._updateEffects = function () {
  75027. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75028. this._effects[effectIndex].updateEffect();
  75029. }
  75030. };
  75031. /**
  75032. * Internal
  75033. * @returns if all the contained post processes are ready.
  75034. */
  75035. BloomEffect.prototype._isReady = function () {
  75036. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75037. if (!this._effects[effectIndex].isReady()) {
  75038. return false;
  75039. }
  75040. }
  75041. return true;
  75042. };
  75043. return BloomEffect;
  75044. }(BABYLON.PostProcessRenderEffect));
  75045. BABYLON.BloomEffect = BloomEffect;
  75046. })(BABYLON || (BABYLON = {}));
  75047. //# sourceMappingURL=babylon.bloomEffect.js.map
  75048. var BABYLON;
  75049. (function (BABYLON) {
  75050. /**
  75051. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75052. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75053. */
  75054. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75055. __extends(DefaultRenderingPipeline, _super);
  75056. /**
  75057. * @constructor
  75058. * @param {string} name - The rendering pipeline name (default: "")
  75059. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75060. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75061. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75062. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75063. */
  75064. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75065. if (name === void 0) { name = ""; }
  75066. if (hdr === void 0) { hdr = true; }
  75067. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75068. if (automaticBuild === void 0) { automaticBuild = true; }
  75069. var _this = _super.call(this, scene.getEngine(), name) || this;
  75070. _this._originalCameras = [];
  75071. /**
  75072. * ID of the sharpen post process,
  75073. */
  75074. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75075. /**
  75076. * ID of the image processing post process;
  75077. */
  75078. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75079. /**
  75080. * ID of the Fast Approximate Anti-Aliasing post process;
  75081. */
  75082. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75083. /**
  75084. * ID of the chromatic aberration post process,
  75085. */
  75086. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75087. /**
  75088. * ID of the grain post process
  75089. */
  75090. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75091. /**
  75092. * Glow post process which adds a glow to emmisive areas of the image
  75093. */
  75094. _this._glowLayer = null;
  75095. /**
  75096. * Animations which can be used to tweak settings over a period of time
  75097. */
  75098. _this.animations = [];
  75099. _this._imageProcessingConfigurationObserver = null;
  75100. // Values
  75101. _this._sharpenEnabled = false;
  75102. _this._bloomEnabled = false;
  75103. _this._depthOfFieldEnabled = false;
  75104. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75105. _this._fxaaEnabled = false;
  75106. _this._imageProcessingEnabled = true;
  75107. _this._bloomScale = 0.5;
  75108. _this._chromaticAberrationEnabled = false;
  75109. _this._grainEnabled = false;
  75110. _this._buildAllowed = true;
  75111. _this._resizeObserver = null;
  75112. _this._hardwareScaleLevel = 1.0;
  75113. _this._bloomKernel = 64;
  75114. /**
  75115. * Specifies the weight of the bloom in the final rendering
  75116. */
  75117. _this._bloomWeight = 0.15;
  75118. /**
  75119. * Specifies the luma threshold for the area that will be blurred by the bloom
  75120. */
  75121. _this._bloomThreshold = 0.9;
  75122. _this._samples = 1;
  75123. _this._hasCleared = false;
  75124. _this._prevPostProcess = null;
  75125. _this._prevPrevPostProcess = null;
  75126. _this._cameras = cameras || scene.cameras;
  75127. _this._originalCameras = _this._cameras.slice();
  75128. _this._buildAllowed = automaticBuild;
  75129. // Initialize
  75130. _this._scene = scene;
  75131. var caps = _this._scene.getEngine().getCaps();
  75132. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75133. // Misc
  75134. if (_this._hdr) {
  75135. if (caps.textureHalfFloatRender) {
  75136. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75137. }
  75138. else if (caps.textureFloatRender) {
  75139. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75140. }
  75141. }
  75142. else {
  75143. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75144. }
  75145. // Attach
  75146. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75147. var engine = _this._scene.getEngine();
  75148. // Create post processes before hand so they can be modified before enabled.
  75149. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75150. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75151. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75152. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75153. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75154. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75155. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75156. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75157. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75158. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75159. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75160. _this.bloomKernel = _this.bloomKernel;
  75161. });
  75162. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75163. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75164. });
  75165. _this._buildPipeline();
  75166. return _this;
  75167. }
  75168. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75169. get: function () {
  75170. return this._sharpenEnabled;
  75171. },
  75172. /**
  75173. * Enable or disable the sharpen process from the pipeline
  75174. */
  75175. set: function (enabled) {
  75176. if (this._sharpenEnabled === enabled) {
  75177. return;
  75178. }
  75179. this._sharpenEnabled = enabled;
  75180. this._buildPipeline();
  75181. },
  75182. enumerable: true,
  75183. configurable: true
  75184. });
  75185. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75186. /**
  75187. * Specifies the size of the bloom blur kernel, relative to the final output size
  75188. */
  75189. get: function () {
  75190. return this._bloomKernel;
  75191. },
  75192. set: function (value) {
  75193. this._bloomKernel = value;
  75194. this.bloom.kernel = value / this._hardwareScaleLevel;
  75195. },
  75196. enumerable: true,
  75197. configurable: true
  75198. });
  75199. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75200. get: function () {
  75201. return this._bloomWeight;
  75202. },
  75203. /**
  75204. * The strength of the bloom.
  75205. */
  75206. set: function (value) {
  75207. if (this._bloomWeight === value) {
  75208. return;
  75209. }
  75210. this.bloom.weight = value;
  75211. this._bloomWeight = value;
  75212. },
  75213. enumerable: true,
  75214. configurable: true
  75215. });
  75216. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75217. get: function () {
  75218. return this._bloomThreshold;
  75219. },
  75220. /**
  75221. * The strength of the bloom.
  75222. */
  75223. set: function (value) {
  75224. if (this._bloomThreshold === value) {
  75225. return;
  75226. }
  75227. this.bloom.threshold = value;
  75228. this._bloomThreshold = value;
  75229. },
  75230. enumerable: true,
  75231. configurable: true
  75232. });
  75233. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75234. get: function () {
  75235. return this._bloomScale;
  75236. },
  75237. /**
  75238. * The scale of the bloom, lower value will provide better performance.
  75239. */
  75240. set: function (value) {
  75241. if (this._bloomScale === value) {
  75242. return;
  75243. }
  75244. this._bloomScale = value;
  75245. // recreate bloom and dispose old as this setting is not dynamic
  75246. this._rebuildBloom();
  75247. this._buildPipeline();
  75248. },
  75249. enumerable: true,
  75250. configurable: true
  75251. });
  75252. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75253. get: function () {
  75254. return this._bloomEnabled;
  75255. },
  75256. /**
  75257. * Enable or disable the bloom from the pipeline
  75258. */
  75259. set: function (enabled) {
  75260. if (this._bloomEnabled === enabled) {
  75261. return;
  75262. }
  75263. this._bloomEnabled = enabled;
  75264. this._buildPipeline();
  75265. },
  75266. enumerable: true,
  75267. configurable: true
  75268. });
  75269. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75270. // recreate bloom and dispose old as this setting is not dynamic
  75271. var oldBloom = this.bloom;
  75272. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75273. this.bloom.threshold = oldBloom.threshold;
  75274. for (var i = 0; i < this._cameras.length; i++) {
  75275. oldBloom.disposeEffects(this._cameras[i]);
  75276. }
  75277. };
  75278. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75279. /**
  75280. * If the depth of field is enabled.
  75281. */
  75282. get: function () {
  75283. return this._depthOfFieldEnabled;
  75284. },
  75285. set: function (enabled) {
  75286. if (this._depthOfFieldEnabled === enabled) {
  75287. return;
  75288. }
  75289. this._depthOfFieldEnabled = enabled;
  75290. this._buildPipeline();
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75296. /**
  75297. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75298. */
  75299. get: function () {
  75300. return this._depthOfFieldBlurLevel;
  75301. },
  75302. set: function (value) {
  75303. if (this._depthOfFieldBlurLevel === value) {
  75304. return;
  75305. }
  75306. this._depthOfFieldBlurLevel = value;
  75307. // recreate dof and dispose old as this setting is not dynamic
  75308. var oldDof = this.depthOfField;
  75309. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75310. this.depthOfField.focalLength = oldDof.focalLength;
  75311. this.depthOfField.focusDistance = oldDof.focusDistance;
  75312. this.depthOfField.fStop = oldDof.fStop;
  75313. this.depthOfField.lensSize = oldDof.lensSize;
  75314. for (var i = 0; i < this._cameras.length; i++) {
  75315. oldDof.disposeEffects(this._cameras[i]);
  75316. }
  75317. this._buildPipeline();
  75318. },
  75319. enumerable: true,
  75320. configurable: true
  75321. });
  75322. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75323. get: function () {
  75324. return this._fxaaEnabled;
  75325. },
  75326. /**
  75327. * If the anti aliasing is enabled.
  75328. */
  75329. set: function (enabled) {
  75330. if (this._fxaaEnabled === enabled) {
  75331. return;
  75332. }
  75333. this._fxaaEnabled = enabled;
  75334. this._buildPipeline();
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75340. get: function () {
  75341. return this._samples;
  75342. },
  75343. /**
  75344. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75345. */
  75346. set: function (sampleCount) {
  75347. if (this._samples === sampleCount) {
  75348. return;
  75349. }
  75350. this._samples = sampleCount;
  75351. this._buildPipeline();
  75352. },
  75353. enumerable: true,
  75354. configurable: true
  75355. });
  75356. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75357. get: function () {
  75358. return this._imageProcessingEnabled;
  75359. },
  75360. /**
  75361. * If image processing is enabled.
  75362. */
  75363. set: function (enabled) {
  75364. if (this._imageProcessingEnabled === enabled) {
  75365. return;
  75366. }
  75367. this._imageProcessingEnabled = enabled;
  75368. this._buildPipeline();
  75369. },
  75370. enumerable: true,
  75371. configurable: true
  75372. });
  75373. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75374. get: function () {
  75375. return this._glowLayer == null;
  75376. },
  75377. /**
  75378. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75379. */
  75380. set: function (enabled) {
  75381. if (enabled && !this._glowLayer) {
  75382. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75383. }
  75384. else if (!enabled && this._glowLayer) {
  75385. this._glowLayer.dispose();
  75386. this._glowLayer = null;
  75387. }
  75388. },
  75389. enumerable: true,
  75390. configurable: true
  75391. });
  75392. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75393. get: function () {
  75394. return this._chromaticAberrationEnabled;
  75395. },
  75396. /**
  75397. * Enable or disable the chromaticAberration process from the pipeline
  75398. */
  75399. set: function (enabled) {
  75400. if (this._chromaticAberrationEnabled === enabled) {
  75401. return;
  75402. }
  75403. this._chromaticAberrationEnabled = enabled;
  75404. this._buildPipeline();
  75405. },
  75406. enumerable: true,
  75407. configurable: true
  75408. });
  75409. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75410. get: function () {
  75411. return this._grainEnabled;
  75412. },
  75413. /**
  75414. * Enable or disable the grain process from the pipeline
  75415. */
  75416. set: function (enabled) {
  75417. if (this._grainEnabled === enabled) {
  75418. return;
  75419. }
  75420. this._grainEnabled = enabled;
  75421. this._buildPipeline();
  75422. },
  75423. enumerable: true,
  75424. configurable: true
  75425. });
  75426. /**
  75427. * Force the compilation of the entire pipeline.
  75428. */
  75429. DefaultRenderingPipeline.prototype.prepare = function () {
  75430. var previousState = this._buildAllowed;
  75431. this._buildAllowed = true;
  75432. this._buildPipeline();
  75433. this._buildAllowed = previousState;
  75434. };
  75435. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75436. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75437. if (this._hasCleared) {
  75438. postProcess.autoClear = false;
  75439. }
  75440. else {
  75441. postProcess.autoClear = true;
  75442. this._scene.autoClear = false;
  75443. this._hasCleared = true;
  75444. }
  75445. if (!skipTextureSharing) {
  75446. if (this._prevPrevPostProcess) {
  75447. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75448. }
  75449. else {
  75450. postProcess.useOwnOutput();
  75451. }
  75452. if (this._prevPostProcess) {
  75453. this._prevPrevPostProcess = this._prevPostProcess;
  75454. }
  75455. this._prevPostProcess = postProcess;
  75456. }
  75457. };
  75458. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75459. var _this = this;
  75460. if (!this._buildAllowed) {
  75461. return;
  75462. }
  75463. this._scene.autoClear = true;
  75464. var engine = this._scene.getEngine();
  75465. this._disposePostProcesses();
  75466. if (this._cameras !== null) {
  75467. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75468. // get back cameras to be used to reattach pipeline
  75469. this._cameras = this._originalCameras.slice();
  75470. }
  75471. this._reset();
  75472. this._prevPostProcess = null;
  75473. this._prevPrevPostProcess = null;
  75474. this._hasCleared = false;
  75475. if (this.depthOfFieldEnabled) {
  75476. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75477. this.depthOfField.depthTexture = depthTexture;
  75478. if (!this.depthOfField._isReady()) {
  75479. this.depthOfField._updateEffects();
  75480. }
  75481. this.addEffect(this.depthOfField);
  75482. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75483. }
  75484. if (this.bloomEnabled) {
  75485. if (!this.bloom._isReady()) {
  75486. this.bloom._updateEffects();
  75487. }
  75488. this.addEffect(this.bloom);
  75489. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75490. }
  75491. if (this._imageProcessingEnabled) {
  75492. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75493. if (this._hdr) {
  75494. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75495. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75496. }
  75497. else {
  75498. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75499. }
  75500. }
  75501. if (this.sharpenEnabled) {
  75502. if (!this.sharpen.isReady()) {
  75503. this.sharpen.updateEffect();
  75504. }
  75505. this.addEffect(this._sharpenEffect);
  75506. this._setAutoClearAndTextureSharing(this.sharpen);
  75507. }
  75508. if (this.grainEnabled) {
  75509. if (!this.grain.isReady()) {
  75510. this.grain.updateEffect();
  75511. }
  75512. this.addEffect(this._grainEffect);
  75513. this._setAutoClearAndTextureSharing(this.grain);
  75514. }
  75515. if (this.chromaticAberrationEnabled) {
  75516. if (!this.chromaticAberration.isReady()) {
  75517. this.chromaticAberration.updateEffect();
  75518. }
  75519. this.addEffect(this._chromaticAberrationEffect);
  75520. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75521. }
  75522. if (this.fxaaEnabled) {
  75523. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75524. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75525. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75526. }
  75527. if (this._cameras !== null) {
  75528. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75529. }
  75530. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75531. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75532. }
  75533. };
  75534. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75535. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75536. for (var i = 0; i < this._cameras.length; i++) {
  75537. var camera = this._cameras[i];
  75538. if (this.imageProcessing) {
  75539. this.imageProcessing.dispose(camera);
  75540. }
  75541. if (this.fxaa) {
  75542. this.fxaa.dispose(camera);
  75543. }
  75544. // These are created in the constructor and should not be disposed on every pipeline change
  75545. if (disposeNonRecreated) {
  75546. if (this.sharpen) {
  75547. this.sharpen.dispose(camera);
  75548. }
  75549. if (this.depthOfField) {
  75550. this.depthOfField.disposeEffects(camera);
  75551. }
  75552. if (this.bloom) {
  75553. this.bloom.disposeEffects(camera);
  75554. }
  75555. if (this.chromaticAberration) {
  75556. this.chromaticAberration.dispose(camera);
  75557. }
  75558. if (this.grain) {
  75559. this.grain.dispose(camera);
  75560. }
  75561. if (this._glowLayer) {
  75562. this._glowLayer.dispose();
  75563. }
  75564. }
  75565. }
  75566. this.imageProcessing = null;
  75567. this.fxaa = null;
  75568. if (disposeNonRecreated) {
  75569. this.sharpen = null;
  75570. this._sharpenEffect = null;
  75571. this.depthOfField = null;
  75572. this.bloom = null;
  75573. this.chromaticAberration = null;
  75574. this._chromaticAberrationEffect = null;
  75575. this.grain = null;
  75576. this._grainEffect = null;
  75577. this._glowLayer = null;
  75578. }
  75579. };
  75580. /**
  75581. * Dispose of the pipeline and stop all post processes
  75582. */
  75583. DefaultRenderingPipeline.prototype.dispose = function () {
  75584. this._disposePostProcesses(true);
  75585. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75586. this._scene.autoClear = true;
  75587. if (this._resizeObserver) {
  75588. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75589. this._resizeObserver = null;
  75590. }
  75591. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75592. _super.prototype.dispose.call(this);
  75593. };
  75594. /**
  75595. * Serialize the rendering pipeline (Used when exporting)
  75596. * @returns the serialized object
  75597. */
  75598. DefaultRenderingPipeline.prototype.serialize = function () {
  75599. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75600. serializationObject.customType = "DefaultRenderingPipeline";
  75601. return serializationObject;
  75602. };
  75603. /**
  75604. * Parse the serialized pipeline
  75605. * @param source Source pipeline.
  75606. * @param scene The scene to load the pipeline to.
  75607. * @param rootUrl The URL of the serialized pipeline.
  75608. * @returns An instantiated pipeline from the serialized object.
  75609. */
  75610. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75611. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75612. };
  75613. __decorate([
  75614. BABYLON.serialize()
  75615. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75616. __decorate([
  75617. BABYLON.serialize()
  75618. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75619. __decorate([
  75620. BABYLON.serialize()
  75621. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75622. __decorate([
  75623. BABYLON.serialize()
  75624. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75625. __decorate([
  75626. BABYLON.serialize()
  75627. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75628. __decorate([
  75629. BABYLON.serialize()
  75630. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75631. __decorate([
  75632. BABYLON.serialize()
  75633. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75634. __decorate([
  75635. BABYLON.serialize()
  75636. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75637. __decorate([
  75638. BABYLON.serialize()
  75639. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75640. __decorate([
  75641. BABYLON.serialize()
  75642. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75643. __decorate([
  75644. BABYLON.serialize()
  75645. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75646. __decorate([
  75647. BABYLON.serialize()
  75648. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75649. __decorate([
  75650. BABYLON.serialize()
  75651. ], DefaultRenderingPipeline.prototype, "samples", null);
  75652. __decorate([
  75653. BABYLON.serialize()
  75654. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75655. __decorate([
  75656. BABYLON.serialize()
  75657. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  75658. __decorate([
  75659. BABYLON.serialize()
  75660. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75661. __decorate([
  75662. BABYLON.serialize()
  75663. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75664. return DefaultRenderingPipeline;
  75665. }(BABYLON.PostProcessRenderPipeline));
  75666. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75667. })(BABYLON || (BABYLON = {}));
  75668. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75669. var BABYLON;
  75670. (function (BABYLON) {
  75671. /**
  75672. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75673. */
  75674. var GeometryBufferRenderer = /** @class */ (function () {
  75675. /**
  75676. * Creates a new G Buffer for the scene
  75677. * @param scene The scene the buffer belongs to
  75678. * @param ratio How big is the buffer related to the main canvas.
  75679. */
  75680. function GeometryBufferRenderer(scene, ratio) {
  75681. if (ratio === void 0) { ratio = 1; }
  75682. this._enablePosition = false;
  75683. this._scene = scene;
  75684. this._ratio = ratio;
  75685. // Render target
  75686. this._createRenderTargets();
  75687. }
  75688. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75689. /**
  75690. * Set the render list (meshes to be rendered) used in the G buffer.
  75691. */
  75692. set: function (meshes) {
  75693. this._multiRenderTarget.renderList = meshes;
  75694. },
  75695. enumerable: true,
  75696. configurable: true
  75697. });
  75698. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75699. /**
  75700. * Gets wether or not G buffer are supported by the running hardware.
  75701. * This requires draw buffer supports
  75702. */
  75703. get: function () {
  75704. return this._multiRenderTarget.isSupported;
  75705. },
  75706. enumerable: true,
  75707. configurable: true
  75708. });
  75709. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75710. /**
  75711. * Gets wether or not position are enabled for the G buffer.
  75712. */
  75713. get: function () {
  75714. return this._enablePosition;
  75715. },
  75716. /**
  75717. * Sets wether or not position are enabled for the G buffer.
  75718. */
  75719. set: function (enable) {
  75720. this._enablePosition = enable;
  75721. this.dispose();
  75722. this._createRenderTargets();
  75723. },
  75724. enumerable: true,
  75725. configurable: true
  75726. });
  75727. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75728. /**
  75729. * Gets the scene associated with the buffer.
  75730. */
  75731. get: function () {
  75732. return this._scene;
  75733. },
  75734. enumerable: true,
  75735. configurable: true
  75736. });
  75737. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75738. /**
  75739. * Gets the ratio used by the buffer during its creation.
  75740. * How big is the buffer related to the main canvas.
  75741. */
  75742. get: function () {
  75743. return this._ratio;
  75744. },
  75745. enumerable: true,
  75746. configurable: true
  75747. });
  75748. /**
  75749. * Checks wether everything is ready to render a submesh to the G buffer.
  75750. * @param subMesh the submesh to check readiness for
  75751. * @param useInstances is the mesh drawn using instance or not
  75752. * @returns true if ready otherwise false
  75753. */
  75754. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75755. var material = subMesh.getMaterial();
  75756. if (material && material.disableDepthWrite) {
  75757. return false;
  75758. }
  75759. var defines = [];
  75760. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75761. var mesh = subMesh.getMesh();
  75762. // Alpha test
  75763. if (material && material.needAlphaTesting()) {
  75764. defines.push("#define ALPHATEST");
  75765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75766. attribs.push(BABYLON.VertexBuffer.UVKind);
  75767. defines.push("#define UV1");
  75768. }
  75769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75770. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75771. defines.push("#define UV2");
  75772. }
  75773. }
  75774. // Buffers
  75775. if (this._enablePosition) {
  75776. defines.push("#define POSITION");
  75777. }
  75778. // Bones
  75779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75782. if (mesh.numBoneInfluencers > 4) {
  75783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75785. }
  75786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75787. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75788. }
  75789. else {
  75790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75791. }
  75792. // Instances
  75793. if (useInstances) {
  75794. defines.push("#define INSTANCES");
  75795. attribs.push("world0");
  75796. attribs.push("world1");
  75797. attribs.push("world2");
  75798. attribs.push("world3");
  75799. }
  75800. // Get correct effect
  75801. var join = defines.join("\n");
  75802. if (this._cachedDefines !== join) {
  75803. this._cachedDefines = join;
  75804. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75805. }
  75806. return this._effect.isReady();
  75807. };
  75808. /**
  75809. * Gets the current underlying G Buffer.
  75810. * @returns the buffer
  75811. */
  75812. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75813. return this._multiRenderTarget;
  75814. };
  75815. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75816. /**
  75817. * Gets the number of samples used to render the buffer (anti aliasing).
  75818. */
  75819. get: function () {
  75820. return this._multiRenderTarget.samples;
  75821. },
  75822. /**
  75823. * Sets the number of samples used to render the buffer (anti aliasing).
  75824. */
  75825. set: function (value) {
  75826. this._multiRenderTarget.samples = value;
  75827. },
  75828. enumerable: true,
  75829. configurable: true
  75830. });
  75831. /**
  75832. * Disposes the renderer and frees up associated resources.
  75833. */
  75834. GeometryBufferRenderer.prototype.dispose = function () {
  75835. this.getGBuffer().dispose();
  75836. };
  75837. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75838. var _this = this;
  75839. var engine = this._scene.getEngine();
  75840. var count = this._enablePosition ? 3 : 2;
  75841. 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 });
  75842. if (!this.isSupported) {
  75843. return;
  75844. }
  75845. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75846. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75847. this._multiRenderTarget.refreshRate = 1;
  75848. this._multiRenderTarget.renderParticles = false;
  75849. this._multiRenderTarget.renderList = null;
  75850. // set default depth value to 1.0 (far away)
  75851. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75852. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75853. });
  75854. // Custom render function
  75855. var renderSubMesh = function (subMesh) {
  75856. var mesh = subMesh.getRenderingMesh();
  75857. var scene = _this._scene;
  75858. var engine = scene.getEngine();
  75859. var material = subMesh.getMaterial();
  75860. if (!material) {
  75861. return;
  75862. }
  75863. // Culling
  75864. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75865. // Managing instances
  75866. var batch = mesh._getInstancesRenderList(subMesh._id);
  75867. if (batch.mustReturn) {
  75868. return;
  75869. }
  75870. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75871. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75872. engine.enableEffect(_this._effect);
  75873. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75874. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75875. _this._effect.setMatrix("view", scene.getViewMatrix());
  75876. // Alpha test
  75877. if (material && material.needAlphaTesting()) {
  75878. var alphaTexture = material.getAlphaTestTexture();
  75879. if (alphaTexture) {
  75880. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75881. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75882. }
  75883. }
  75884. // Bones
  75885. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75886. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75887. }
  75888. // Draw
  75889. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75890. }
  75891. };
  75892. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75893. var index;
  75894. if (depthOnlySubMeshes.length) {
  75895. engine.setColorWrite(false);
  75896. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75897. renderSubMesh(depthOnlySubMeshes.data[index]);
  75898. }
  75899. engine.setColorWrite(true);
  75900. }
  75901. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75902. renderSubMesh(opaqueSubMeshes.data[index]);
  75903. }
  75904. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75905. renderSubMesh(alphaTestSubMeshes.data[index]);
  75906. }
  75907. };
  75908. };
  75909. return GeometryBufferRenderer;
  75910. }());
  75911. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75912. })(BABYLON || (BABYLON = {}));
  75913. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75914. var BABYLON;
  75915. (function (BABYLON) {
  75916. /**
  75917. * This groups together the common properties used for image processing either in direct forward pass
  75918. * or through post processing effect depending on the use of the image processing pipeline in your scene
  75919. * or not.
  75920. */
  75921. var ImageProcessingConfiguration = /** @class */ (function () {
  75922. function ImageProcessingConfiguration() {
  75923. /**
  75924. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  75925. */
  75926. this.colorCurves = new BABYLON.ColorCurves();
  75927. this._colorCurvesEnabled = false;
  75928. this._colorGradingEnabled = false;
  75929. this._colorGradingWithGreenDepth = true;
  75930. this._colorGradingBGR = true;
  75931. this._exposure = 1.0;
  75932. this._toneMappingEnabled = false;
  75933. this._contrast = 1.0;
  75934. /**
  75935. * Vignette stretch size.
  75936. */
  75937. this.vignetteStretch = 0;
  75938. /**
  75939. * Vignette centre X Offset.
  75940. */
  75941. this.vignetteCentreX = 0;
  75942. /**
  75943. * Vignette centre Y Offset.
  75944. */
  75945. this.vignetteCentreY = 0;
  75946. /**
  75947. * Vignette weight or intensity of the vignette effect.
  75948. */
  75949. this.vignetteWeight = 1.5;
  75950. /**
  75951. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75952. * if vignetteEnabled is set to true.
  75953. */
  75954. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75955. /**
  75956. * Camera field of view used by the Vignette effect.
  75957. */
  75958. this.vignetteCameraFov = 0.5;
  75959. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  75960. this._vignetteEnabled = false;
  75961. this._applyByPostProcess = false;
  75962. this._isEnabled = true;
  75963. /**
  75964. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  75965. */
  75966. this.onUpdateParameters = new BABYLON.Observable();
  75967. }
  75968. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  75969. /**
  75970. * Gets wether the color curves effect is enabled.
  75971. */
  75972. get: function () {
  75973. return this._colorCurvesEnabled;
  75974. },
  75975. /**
  75976. * Sets wether the color curves effect is enabled.
  75977. */
  75978. set: function (value) {
  75979. if (this._colorCurvesEnabled === value) {
  75980. return;
  75981. }
  75982. this._colorCurvesEnabled = value;
  75983. this._updateParameters();
  75984. },
  75985. enumerable: true,
  75986. configurable: true
  75987. });
  75988. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  75989. /**
  75990. * Gets wether the color grading effect is enabled.
  75991. */
  75992. get: function () {
  75993. return this._colorGradingEnabled;
  75994. },
  75995. /**
  75996. * Sets wether the color grading effect is enabled.
  75997. */
  75998. set: function (value) {
  75999. if (this._colorGradingEnabled === value) {
  76000. return;
  76001. }
  76002. this._colorGradingEnabled = value;
  76003. this._updateParameters();
  76004. },
  76005. enumerable: true,
  76006. configurable: true
  76007. });
  76008. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76009. /**
  76010. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76011. */
  76012. get: function () {
  76013. return this._colorGradingWithGreenDepth;
  76014. },
  76015. /**
  76016. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76017. */
  76018. set: function (value) {
  76019. if (this._colorGradingWithGreenDepth === value) {
  76020. return;
  76021. }
  76022. this._colorGradingWithGreenDepth = value;
  76023. this._updateParameters();
  76024. },
  76025. enumerable: true,
  76026. configurable: true
  76027. });
  76028. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76029. /**
  76030. * Gets wether the color grading texture contains BGR values.
  76031. */
  76032. get: function () {
  76033. return this._colorGradingBGR;
  76034. },
  76035. /**
  76036. * Sets wether the color grading texture contains BGR values.
  76037. */
  76038. set: function (value) {
  76039. if (this._colorGradingBGR === value) {
  76040. return;
  76041. }
  76042. this._colorGradingBGR = value;
  76043. this._updateParameters();
  76044. },
  76045. enumerable: true,
  76046. configurable: true
  76047. });
  76048. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76049. /**
  76050. * Gets the Exposure used in the effect.
  76051. */
  76052. get: function () {
  76053. return this._exposure;
  76054. },
  76055. /**
  76056. * Sets the Exposure used in the effect.
  76057. */
  76058. set: function (value) {
  76059. if (this._exposure === value) {
  76060. return;
  76061. }
  76062. this._exposure = value;
  76063. this._updateParameters();
  76064. },
  76065. enumerable: true,
  76066. configurable: true
  76067. });
  76068. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76069. /**
  76070. * Gets wether the tone mapping effect is enabled.
  76071. */
  76072. get: function () {
  76073. return this._toneMappingEnabled;
  76074. },
  76075. /**
  76076. * Sets wether the tone mapping effect is enabled.
  76077. */
  76078. set: function (value) {
  76079. if (this._toneMappingEnabled === value) {
  76080. return;
  76081. }
  76082. this._toneMappingEnabled = value;
  76083. this._updateParameters();
  76084. },
  76085. enumerable: true,
  76086. configurable: true
  76087. });
  76088. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76089. /**
  76090. * Gets the contrast used in the effect.
  76091. */
  76092. get: function () {
  76093. return this._contrast;
  76094. },
  76095. /**
  76096. * Sets the contrast used in the effect.
  76097. */
  76098. set: function (value) {
  76099. if (this._contrast === value) {
  76100. return;
  76101. }
  76102. this._contrast = value;
  76103. this._updateParameters();
  76104. },
  76105. enumerable: true,
  76106. configurable: true
  76107. });
  76108. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76109. /**
  76110. * Gets the vignette blend mode allowing different kind of effect.
  76111. */
  76112. get: function () {
  76113. return this._vignetteBlendMode;
  76114. },
  76115. /**
  76116. * Sets the vignette blend mode allowing different kind of effect.
  76117. */
  76118. set: function (value) {
  76119. if (this._vignetteBlendMode === value) {
  76120. return;
  76121. }
  76122. this._vignetteBlendMode = value;
  76123. this._updateParameters();
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76129. /**
  76130. * Gets wether the vignette effect is enabled.
  76131. */
  76132. get: function () {
  76133. return this._vignetteEnabled;
  76134. },
  76135. /**
  76136. * Sets wether the vignette effect is enabled.
  76137. */
  76138. set: function (value) {
  76139. if (this._vignetteEnabled === value) {
  76140. return;
  76141. }
  76142. this._vignetteEnabled = value;
  76143. this._updateParameters();
  76144. },
  76145. enumerable: true,
  76146. configurable: true
  76147. });
  76148. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76149. /**
  76150. * Gets wether the image processing is applied through a post process or not.
  76151. */
  76152. get: function () {
  76153. return this._applyByPostProcess;
  76154. },
  76155. /**
  76156. * Sets wether the image processing is applied through a post process or not.
  76157. */
  76158. set: function (value) {
  76159. if (this._applyByPostProcess === value) {
  76160. return;
  76161. }
  76162. this._applyByPostProcess = value;
  76163. this._updateParameters();
  76164. },
  76165. enumerable: true,
  76166. configurable: true
  76167. });
  76168. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76169. /**
  76170. * Gets wether the image processing is enabled or not.
  76171. */
  76172. get: function () {
  76173. return this._isEnabled;
  76174. },
  76175. /**
  76176. * Sets wether the image processing is enabled or not.
  76177. */
  76178. set: function (value) {
  76179. if (this._isEnabled === value) {
  76180. return;
  76181. }
  76182. this._isEnabled = value;
  76183. this._updateParameters();
  76184. },
  76185. enumerable: true,
  76186. configurable: true
  76187. });
  76188. /**
  76189. * Method called each time the image processing information changes requires to recompile the effect.
  76190. */
  76191. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76192. this.onUpdateParameters.notifyObservers(this);
  76193. };
  76194. ImageProcessingConfiguration.prototype.getClassName = function () {
  76195. return "ImageProcessingConfiguration";
  76196. };
  76197. /**
  76198. * Prepare the list of uniforms associated with the Image Processing effects.
  76199. * @param uniformsList The list of uniforms used in the effect
  76200. * @param defines the list of defines currently in use
  76201. */
  76202. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76203. if (defines.EXPOSURE) {
  76204. uniforms.push("exposureLinear");
  76205. }
  76206. if (defines.CONTRAST) {
  76207. uniforms.push("contrast");
  76208. }
  76209. if (defines.COLORGRADING) {
  76210. uniforms.push("colorTransformSettings");
  76211. }
  76212. if (defines.VIGNETTE) {
  76213. uniforms.push("vInverseScreenSize");
  76214. uniforms.push("vignetteSettings1");
  76215. uniforms.push("vignetteSettings2");
  76216. }
  76217. if (defines.COLORCURVES) {
  76218. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76219. }
  76220. };
  76221. /**
  76222. * Prepare the list of samplers associated with the Image Processing effects.
  76223. * @param uniformsList The list of uniforms used in the effect
  76224. * @param defines the list of defines currently in use
  76225. */
  76226. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76227. if (defines.COLORGRADING) {
  76228. samplersList.push("txColorTransform");
  76229. }
  76230. };
  76231. /**
  76232. * Prepare the list of defines associated to the shader.
  76233. * @param defines the list of defines to complete
  76234. */
  76235. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76236. if (forPostProcess === void 0) { forPostProcess = false; }
  76237. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76238. defines.VIGNETTE = false;
  76239. defines.TONEMAPPING = false;
  76240. defines.CONTRAST = false;
  76241. defines.EXPOSURE = false;
  76242. defines.COLORCURVES = false;
  76243. defines.COLORGRADING = false;
  76244. defines.COLORGRADING3D = false;
  76245. defines.IMAGEPROCESSING = false;
  76246. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76247. return;
  76248. }
  76249. defines.VIGNETTE = this.vignetteEnabled;
  76250. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76251. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76252. defines.TONEMAPPING = this.toneMappingEnabled;
  76253. defines.CONTRAST = (this.contrast !== 1.0);
  76254. defines.EXPOSURE = (this.exposure !== 1.0);
  76255. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76256. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76257. if (defines.COLORGRADING) {
  76258. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76259. }
  76260. else {
  76261. defines.COLORGRADING3D = false;
  76262. }
  76263. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76264. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76265. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76266. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76267. };
  76268. /**
  76269. * Returns true if all the image processing information are ready.
  76270. */
  76271. ImageProcessingConfiguration.prototype.isReady = function () {
  76272. // Color Grading texure can not be none blocking.
  76273. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76274. };
  76275. /**
  76276. * Binds the image processing to the shader.
  76277. * @param effect The effect to bind to
  76278. */
  76279. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76280. if (aspectRatio === void 0) { aspectRatio = 1; }
  76281. // Color Curves
  76282. if (this._colorCurvesEnabled && this.colorCurves) {
  76283. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76284. }
  76285. // Vignette
  76286. if (this._vignetteEnabled) {
  76287. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76288. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76289. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76290. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76291. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76292. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76293. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76294. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76295. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76296. var vignettePower = -2.0 * this.vignetteWeight;
  76297. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76298. }
  76299. // Exposure
  76300. effect.setFloat("exposureLinear", this.exposure);
  76301. // Contrast
  76302. effect.setFloat("contrast", this.contrast);
  76303. // Color transform settings
  76304. if (this.colorGradingTexture) {
  76305. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76306. var textureSize = this.colorGradingTexture.getSize().height;
  76307. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76308. 0.5 / textureSize, // textureOffset
  76309. textureSize, // textureSize
  76310. this.colorGradingTexture.level // weight
  76311. );
  76312. }
  76313. };
  76314. /**
  76315. * Clones the current image processing instance.
  76316. * @return The cloned image processing
  76317. */
  76318. ImageProcessingConfiguration.prototype.clone = function () {
  76319. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76320. };
  76321. /**
  76322. * Serializes the current image processing instance to a json representation.
  76323. * @return a JSON representation
  76324. */
  76325. ImageProcessingConfiguration.prototype.serialize = function () {
  76326. return BABYLON.SerializationHelper.Serialize(this);
  76327. };
  76328. /**
  76329. * Parses the image processing from a json representation.
  76330. * @param source the JSON source to parse
  76331. * @return The parsed image processing
  76332. */
  76333. ImageProcessingConfiguration.Parse = function (source) {
  76334. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76335. };
  76336. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76337. /**
  76338. * Used to apply the vignette as a mix with the pixel color.
  76339. */
  76340. get: function () {
  76341. return this._VIGNETTEMODE_MULTIPLY;
  76342. },
  76343. enumerable: true,
  76344. configurable: true
  76345. });
  76346. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76347. /**
  76348. * Used to apply the vignette as a replacement of the pixel color.
  76349. */
  76350. get: function () {
  76351. return this._VIGNETTEMODE_OPAQUE;
  76352. },
  76353. enumerable: true,
  76354. configurable: true
  76355. });
  76356. // Static constants associated to the image processing.
  76357. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76358. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76359. __decorate([
  76360. BABYLON.serializeAsColorCurves()
  76361. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76362. __decorate([
  76363. BABYLON.serialize()
  76364. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76365. __decorate([
  76366. BABYLON.serializeAsTexture()
  76367. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76368. __decorate([
  76369. BABYLON.serialize()
  76370. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76371. __decorate([
  76372. BABYLON.serialize()
  76373. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76374. __decorate([
  76375. BABYLON.serialize()
  76376. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76377. __decorate([
  76378. BABYLON.serialize()
  76379. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76380. __decorate([
  76381. BABYLON.serialize()
  76382. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76383. __decorate([
  76384. BABYLON.serialize()
  76385. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76386. __decorate([
  76387. BABYLON.serialize()
  76388. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76389. __decorate([
  76390. BABYLON.serialize()
  76391. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76392. __decorate([
  76393. BABYLON.serialize()
  76394. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76395. __decorate([
  76396. BABYLON.serialize()
  76397. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76398. __decorate([
  76399. BABYLON.serializeAsColor4()
  76400. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76401. __decorate([
  76402. BABYLON.serialize()
  76403. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76404. __decorate([
  76405. BABYLON.serialize()
  76406. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76407. __decorate([
  76408. BABYLON.serialize()
  76409. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76410. __decorate([
  76411. BABYLON.serialize()
  76412. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76413. __decorate([
  76414. BABYLON.serialize()
  76415. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76416. return ImageProcessingConfiguration;
  76417. }());
  76418. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76419. })(BABYLON || (BABYLON = {}));
  76420. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76421. var BABYLON;
  76422. (function (BABYLON) {
  76423. /**
  76424. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76425. * It can help converting any input color in a desired output one. This can then be used to create effects
  76426. * from sepia, black and white to sixties or futuristic rendering...
  76427. *
  76428. * The only supported format is currently 3dl.
  76429. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76430. */
  76431. var ColorGradingTexture = /** @class */ (function (_super) {
  76432. __extends(ColorGradingTexture, _super);
  76433. /**
  76434. * Instantiates a ColorGradingTexture from the following parameters.
  76435. *
  76436. * @param url The location of the color gradind data (currently only supporting 3dl)
  76437. * @param scene The scene the texture will be used in
  76438. */
  76439. function ColorGradingTexture(url, scene) {
  76440. var _this = _super.call(this, scene) || this;
  76441. if (!url) {
  76442. return _this;
  76443. }
  76444. _this._engine = scene.getEngine();
  76445. _this._textureMatrix = BABYLON.Matrix.Identity();
  76446. _this.name = url;
  76447. _this.url = url;
  76448. _this.hasAlpha = false;
  76449. _this.isCube = false;
  76450. _this.is3D = _this._engine.webGLVersion > 1;
  76451. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76452. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76453. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76454. _this.anisotropicFilteringLevel = 1;
  76455. _this._texture = _this._getFromCache(url, true);
  76456. if (!_this._texture) {
  76457. if (!scene.useDelayedTextureLoading) {
  76458. _this.loadTexture();
  76459. }
  76460. else {
  76461. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76462. }
  76463. }
  76464. return _this;
  76465. }
  76466. /**
  76467. * Returns the texture matrix used in most of the material.
  76468. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  76469. */
  76470. ColorGradingTexture.prototype.getTextureMatrix = function () {
  76471. return this._textureMatrix;
  76472. };
  76473. /**
  76474. * Occurs when the file being loaded is a .3dl LUT file.
  76475. */
  76476. ColorGradingTexture.prototype.load3dlTexture = function () {
  76477. var engine = this._engine;
  76478. var texture;
  76479. if (engine.webGLVersion === 1) {
  76480. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76481. }
  76482. else {
  76483. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76484. }
  76485. this._texture = texture;
  76486. var callback = function (text) {
  76487. if (typeof text !== "string") {
  76488. return;
  76489. }
  76490. var data = null;
  76491. var tempData = null;
  76492. var line;
  76493. var lines = text.split('\n');
  76494. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  76495. var maxColor = 0;
  76496. for (var i = 0; i < lines.length; i++) {
  76497. line = lines[i];
  76498. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  76499. continue;
  76500. if (line.indexOf('#') === 0)
  76501. continue;
  76502. var words = line.split(" ");
  76503. if (size === 0) {
  76504. // Number of space + one
  76505. size = words.length;
  76506. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  76507. tempData = new Float32Array(size * size * size * 4);
  76508. continue;
  76509. }
  76510. if (size != 0) {
  76511. var r = Math.max(parseInt(words[0]), 0);
  76512. var g = Math.max(parseInt(words[1]), 0);
  76513. var b = Math.max(parseInt(words[2]), 0);
  76514. maxColor = Math.max(r, maxColor);
  76515. maxColor = Math.max(g, maxColor);
  76516. maxColor = Math.max(b, maxColor);
  76517. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  76518. if (tempData) {
  76519. tempData[pixelStorageIndex + 0] = r;
  76520. tempData[pixelStorageIndex + 1] = g;
  76521. tempData[pixelStorageIndex + 2] = b;
  76522. }
  76523. pixelIndexSlice++;
  76524. if (pixelIndexSlice % size == 0) {
  76525. pixelIndexH++;
  76526. pixelIndexSlice = 0;
  76527. if (pixelIndexH % size == 0) {
  76528. pixelIndexW++;
  76529. pixelIndexH = 0;
  76530. }
  76531. }
  76532. }
  76533. }
  76534. if (tempData && data) {
  76535. for (var i = 0; i < tempData.length; i++) {
  76536. if (i > 0 && (i + 1) % 4 === 0) {
  76537. data[i] = 255;
  76538. }
  76539. else {
  76540. var value = tempData[i];
  76541. data[i] = (value / maxColor * 255);
  76542. }
  76543. }
  76544. }
  76545. if (texture.is3D) {
  76546. texture.updateSize(size, size, size);
  76547. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76548. }
  76549. else {
  76550. texture.updateSize(size * size, size);
  76551. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76552. }
  76553. };
  76554. var scene = this.getScene();
  76555. if (scene) {
  76556. scene._loadFile(this.url, callback);
  76557. }
  76558. else {
  76559. this._engine._loadFile(this.url, callback);
  76560. }
  76561. return this._texture;
  76562. };
  76563. /**
  76564. * Starts the loading process of the texture.
  76565. */
  76566. ColorGradingTexture.prototype.loadTexture = function () {
  76567. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  76568. this.load3dlTexture();
  76569. }
  76570. };
  76571. /**
  76572. * Clones the color gradind texture.
  76573. */
  76574. ColorGradingTexture.prototype.clone = function () {
  76575. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  76576. // Base texture
  76577. newTexture.level = this.level;
  76578. return newTexture;
  76579. };
  76580. /**
  76581. * Called during delayed load for textures.
  76582. */
  76583. ColorGradingTexture.prototype.delayLoad = function () {
  76584. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76585. return;
  76586. }
  76587. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76588. this._texture = this._getFromCache(this.url, true);
  76589. if (!this._texture) {
  76590. this.loadTexture();
  76591. }
  76592. };
  76593. /**
  76594. * Parses a color grading texture serialized by Babylon.
  76595. * @param parsedTexture The texture information being parsedTexture
  76596. * @param scene The scene to load the texture in
  76597. * @param rootUrl The root url of the data assets to load
  76598. * @return A color gradind texture
  76599. */
  76600. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76601. var texture = null;
  76602. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76603. texture = new ColorGradingTexture(parsedTexture.name, scene);
  76604. texture.name = parsedTexture.name;
  76605. texture.level = parsedTexture.level;
  76606. }
  76607. return texture;
  76608. };
  76609. /**
  76610. * Serializes the LUT texture to json format.
  76611. */
  76612. ColorGradingTexture.prototype.serialize = function () {
  76613. if (!this.name) {
  76614. return null;
  76615. }
  76616. var serializationObject = {};
  76617. serializationObject.name = this.name;
  76618. serializationObject.level = this.level;
  76619. serializationObject.customType = "BABYLON.ColorGradingTexture";
  76620. return serializationObject;
  76621. };
  76622. /**
  76623. * Empty line regex stored for GC.
  76624. */
  76625. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  76626. return ColorGradingTexture;
  76627. }(BABYLON.BaseTexture));
  76628. BABYLON.ColorGradingTexture = ColorGradingTexture;
  76629. })(BABYLON || (BABYLON = {}));
  76630. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  76631. var BABYLON;
  76632. (function (BABYLON) {
  76633. /**
  76634. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76635. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76636. * 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;
  76637. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76638. */
  76639. var ColorCurves = /** @class */ (function () {
  76640. function ColorCurves() {
  76641. this._dirty = true;
  76642. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  76643. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  76644. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76645. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  76646. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76647. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  76648. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  76649. this._globalHue = 30;
  76650. this._globalDensity = 0;
  76651. this._globalSaturation = 0;
  76652. this._globalExposure = 0;
  76653. this._highlightsHue = 30;
  76654. this._highlightsDensity = 0;
  76655. this._highlightsSaturation = 0;
  76656. this._highlightsExposure = 0;
  76657. this._midtonesHue = 30;
  76658. this._midtonesDensity = 0;
  76659. this._midtonesSaturation = 0;
  76660. this._midtonesExposure = 0;
  76661. this._shadowsHue = 30;
  76662. this._shadowsDensity = 0;
  76663. this._shadowsSaturation = 0;
  76664. this._shadowsExposure = 0;
  76665. }
  76666. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  76667. /**
  76668. * Gets the global Hue value.
  76669. * 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).
  76670. */
  76671. get: function () {
  76672. return this._globalHue;
  76673. },
  76674. /**
  76675. * Sets the global Hue value.
  76676. * 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).
  76677. */
  76678. set: function (value) {
  76679. this._globalHue = value;
  76680. this._dirty = true;
  76681. },
  76682. enumerable: true,
  76683. configurable: true
  76684. });
  76685. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  76686. /**
  76687. * Gets the global Density value.
  76688. * 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.
  76689. * Values less than zero provide a filter of opposite hue.
  76690. */
  76691. get: function () {
  76692. return this._globalDensity;
  76693. },
  76694. /**
  76695. * Sets the global Density value.
  76696. * 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.
  76697. * Values less than zero provide a filter of opposite hue.
  76698. */
  76699. set: function (value) {
  76700. this._globalDensity = value;
  76701. this._dirty = true;
  76702. },
  76703. enumerable: true,
  76704. configurable: true
  76705. });
  76706. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  76707. /**
  76708. * Gets the global Saturation value.
  76709. * 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.
  76710. */
  76711. get: function () {
  76712. return this._globalSaturation;
  76713. },
  76714. /**
  76715. * Sets the global Saturation value.
  76716. * 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.
  76717. */
  76718. set: function (value) {
  76719. this._globalSaturation = value;
  76720. this._dirty = true;
  76721. },
  76722. enumerable: true,
  76723. configurable: true
  76724. });
  76725. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  76726. /**
  76727. * Gets the global Exposure value.
  76728. * 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.
  76729. */
  76730. get: function () {
  76731. return this._globalExposure;
  76732. },
  76733. /**
  76734. * Sets the global Exposure value.
  76735. * 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.
  76736. */
  76737. set: function (value) {
  76738. this._globalExposure = value;
  76739. this._dirty = true;
  76740. },
  76741. enumerable: true,
  76742. configurable: true
  76743. });
  76744. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  76745. /**
  76746. * Gets the highlights Hue value.
  76747. * 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).
  76748. */
  76749. get: function () {
  76750. return this._highlightsHue;
  76751. },
  76752. /**
  76753. * Sets the highlights Hue value.
  76754. * 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).
  76755. */
  76756. set: function (value) {
  76757. this._highlightsHue = value;
  76758. this._dirty = true;
  76759. },
  76760. enumerable: true,
  76761. configurable: true
  76762. });
  76763. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  76764. /**
  76765. * Gets the highlights Density value.
  76766. * 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.
  76767. * Values less than zero provide a filter of opposite hue.
  76768. */
  76769. get: function () {
  76770. return this._highlightsDensity;
  76771. },
  76772. /**
  76773. * Sets the highlights Density value.
  76774. * 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.
  76775. * Values less than zero provide a filter of opposite hue.
  76776. */
  76777. set: function (value) {
  76778. this._highlightsDensity = value;
  76779. this._dirty = true;
  76780. },
  76781. enumerable: true,
  76782. configurable: true
  76783. });
  76784. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  76785. /**
  76786. * Gets the highlights Saturation value.
  76787. * 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.
  76788. */
  76789. get: function () {
  76790. return this._highlightsSaturation;
  76791. },
  76792. /**
  76793. * Sets the highlights Saturation value.
  76794. * 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.
  76795. */
  76796. set: function (value) {
  76797. this._highlightsSaturation = value;
  76798. this._dirty = true;
  76799. },
  76800. enumerable: true,
  76801. configurable: true
  76802. });
  76803. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  76804. /**
  76805. * Gets the highlights Exposure value.
  76806. * 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.
  76807. */
  76808. get: function () {
  76809. return this._highlightsExposure;
  76810. },
  76811. /**
  76812. * Sets the highlights Exposure value.
  76813. * 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.
  76814. */
  76815. set: function (value) {
  76816. this._highlightsExposure = value;
  76817. this._dirty = true;
  76818. },
  76819. enumerable: true,
  76820. configurable: true
  76821. });
  76822. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  76823. /**
  76824. * Gets the midtones Hue value.
  76825. * 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).
  76826. */
  76827. get: function () {
  76828. return this._midtonesHue;
  76829. },
  76830. /**
  76831. * Sets the midtones Hue value.
  76832. * 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).
  76833. */
  76834. set: function (value) {
  76835. this._midtonesHue = value;
  76836. this._dirty = true;
  76837. },
  76838. enumerable: true,
  76839. configurable: true
  76840. });
  76841. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  76842. /**
  76843. * Gets the midtones Density value.
  76844. * 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.
  76845. * Values less than zero provide a filter of opposite hue.
  76846. */
  76847. get: function () {
  76848. return this._midtonesDensity;
  76849. },
  76850. /**
  76851. * Sets the midtones Density value.
  76852. * 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.
  76853. * Values less than zero provide a filter of opposite hue.
  76854. */
  76855. set: function (value) {
  76856. this._midtonesDensity = value;
  76857. this._dirty = true;
  76858. },
  76859. enumerable: true,
  76860. configurable: true
  76861. });
  76862. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  76863. /**
  76864. * Gets the midtones Saturation value.
  76865. * 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.
  76866. */
  76867. get: function () {
  76868. return this._midtonesSaturation;
  76869. },
  76870. /**
  76871. * Sets the midtones Saturation value.
  76872. * 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.
  76873. */
  76874. set: function (value) {
  76875. this._midtonesSaturation = value;
  76876. this._dirty = true;
  76877. },
  76878. enumerable: true,
  76879. configurable: true
  76880. });
  76881. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  76882. /**
  76883. * Gets the midtones Exposure value.
  76884. * 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.
  76885. */
  76886. get: function () {
  76887. return this._midtonesExposure;
  76888. },
  76889. /**
  76890. * Sets the midtones Exposure value.
  76891. * 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.
  76892. */
  76893. set: function (value) {
  76894. this._midtonesExposure = value;
  76895. this._dirty = true;
  76896. },
  76897. enumerable: true,
  76898. configurable: true
  76899. });
  76900. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  76901. /**
  76902. * Gets the shadows Hue value.
  76903. * 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).
  76904. */
  76905. get: function () {
  76906. return this._shadowsHue;
  76907. },
  76908. /**
  76909. * Sets the shadows Hue value.
  76910. * 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).
  76911. */
  76912. set: function (value) {
  76913. this._shadowsHue = value;
  76914. this._dirty = true;
  76915. },
  76916. enumerable: true,
  76917. configurable: true
  76918. });
  76919. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  76920. /**
  76921. * Gets the shadows Density value.
  76922. * 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.
  76923. * Values less than zero provide a filter of opposite hue.
  76924. */
  76925. get: function () {
  76926. return this._shadowsDensity;
  76927. },
  76928. /**
  76929. * Sets the shadows Density value.
  76930. * 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.
  76931. * Values less than zero provide a filter of opposite hue.
  76932. */
  76933. set: function (value) {
  76934. this._shadowsDensity = value;
  76935. this._dirty = true;
  76936. },
  76937. enumerable: true,
  76938. configurable: true
  76939. });
  76940. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  76941. /**
  76942. * Gets the shadows Saturation value.
  76943. * 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.
  76944. */
  76945. get: function () {
  76946. return this._shadowsSaturation;
  76947. },
  76948. /**
  76949. * Sets the shadows Saturation value.
  76950. * 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.
  76951. */
  76952. set: function (value) {
  76953. this._shadowsSaturation = value;
  76954. this._dirty = true;
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  76960. /**
  76961. * Gets the shadows Exposure value.
  76962. * 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.
  76963. */
  76964. get: function () {
  76965. return this._shadowsExposure;
  76966. },
  76967. /**
  76968. * Sets the shadows Exposure value.
  76969. * 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.
  76970. */
  76971. set: function (value) {
  76972. this._shadowsExposure = value;
  76973. this._dirty = true;
  76974. },
  76975. enumerable: true,
  76976. configurable: true
  76977. });
  76978. ColorCurves.prototype.getClassName = function () {
  76979. return "ColorCurves";
  76980. };
  76981. /**
  76982. * Binds the color curves to the shader.
  76983. * @param colorCurves The color curve to bind
  76984. * @param effect The effect to bind to
  76985. */
  76986. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  76987. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  76988. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  76989. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  76990. if (colorCurves._dirty) {
  76991. colorCurves._dirty = false;
  76992. // Fill in global info.
  76993. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  76994. // Compute highlights info.
  76995. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  76996. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  76997. // Compute midtones info.
  76998. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  76999. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77000. // Compute shadows info.
  77001. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77002. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77003. // Compute deltas (neutral is midtones).
  77004. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77005. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77006. }
  77007. if (effect) {
  77008. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77009. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77010. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77011. }
  77012. };
  77013. /**
  77014. * Prepare the list of uniforms associated with the ColorCurves effects.
  77015. * @param uniformsList The list of uniforms used in the effect
  77016. */
  77017. ColorCurves.PrepareUniforms = function (uniformsList) {
  77018. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77019. };
  77020. /**
  77021. * Returns color grading data based on a hue, density, saturation and exposure value.
  77022. * @param filterHue The hue of the color filter.
  77023. * @param filterDensity The density of the color filter.
  77024. * @param saturation The saturation.
  77025. * @param exposure The exposure.
  77026. * @param result The result data container.
  77027. */
  77028. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77029. if (hue == null) {
  77030. return;
  77031. }
  77032. hue = ColorCurves.clamp(hue, 0, 360);
  77033. density = ColorCurves.clamp(density, -100, 100);
  77034. saturation = ColorCurves.clamp(saturation, -100, 100);
  77035. exposure = ColorCurves.clamp(exposure, -100, 100);
  77036. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77037. // so that the maximum filter density is only 50% control. This provides fine control
  77038. // for small values and reasonable range.
  77039. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77040. density *= 0.5;
  77041. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77042. if (density < 0) {
  77043. density *= -1;
  77044. hue = (hue + 180) % 360;
  77045. }
  77046. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77047. result.scaleToRef(2, result);
  77048. result.a = 1 + 0.01 * saturation;
  77049. };
  77050. /**
  77051. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77052. * @param value The input slider value in range [-100,100].
  77053. * @returns Adjusted value.
  77054. */
  77055. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77056. value /= 100;
  77057. var x = Math.abs(value);
  77058. x = Math.pow(x, 2);
  77059. if (value < 0) {
  77060. x *= -1;
  77061. }
  77062. x *= 100;
  77063. return x;
  77064. };
  77065. /**
  77066. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77067. * @param hue The hue (H) input.
  77068. * @param saturation The saturation (S) input.
  77069. * @param brightness The brightness (B) input.
  77070. * @result An RGBA color represented as Vector4.
  77071. */
  77072. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77073. var h = ColorCurves.clamp(hue, 0, 360);
  77074. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77075. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77076. if (s === 0) {
  77077. result.r = v;
  77078. result.g = v;
  77079. result.b = v;
  77080. }
  77081. else {
  77082. // sector 0 to 5
  77083. h /= 60;
  77084. var i = Math.floor(h);
  77085. // fractional part of h
  77086. var f = h - i;
  77087. var p = v * (1 - s);
  77088. var q = v * (1 - s * f);
  77089. var t = v * (1 - s * (1 - f));
  77090. switch (i) {
  77091. case 0:
  77092. result.r = v;
  77093. result.g = t;
  77094. result.b = p;
  77095. break;
  77096. case 1:
  77097. result.r = q;
  77098. result.g = v;
  77099. result.b = p;
  77100. break;
  77101. case 2:
  77102. result.r = p;
  77103. result.g = v;
  77104. result.b = t;
  77105. break;
  77106. case 3:
  77107. result.r = p;
  77108. result.g = q;
  77109. result.b = v;
  77110. break;
  77111. case 4:
  77112. result.r = t;
  77113. result.g = p;
  77114. result.b = v;
  77115. break;
  77116. default: // case 5:
  77117. result.r = v;
  77118. result.g = p;
  77119. result.b = q;
  77120. break;
  77121. }
  77122. }
  77123. result.a = 1;
  77124. };
  77125. /**
  77126. * Returns a value clamped between min and max
  77127. * @param value The value to clamp
  77128. * @param min The minimum of value
  77129. * @param max The maximum of value
  77130. * @returns The clamped value.
  77131. */
  77132. ColorCurves.clamp = function (value, min, max) {
  77133. return Math.min(Math.max(value, min), max);
  77134. };
  77135. /**
  77136. * Clones the current color curve instance.
  77137. * @return The cloned curves
  77138. */
  77139. ColorCurves.prototype.clone = function () {
  77140. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77141. };
  77142. /**
  77143. * Serializes the current color curve instance to a json representation.
  77144. * @return a JSON representation
  77145. */
  77146. ColorCurves.prototype.serialize = function () {
  77147. return BABYLON.SerializationHelper.Serialize(this);
  77148. };
  77149. /**
  77150. * Parses the color curve from a json representation.
  77151. * @param source the JSON source to parse
  77152. * @return The parsed curves
  77153. */
  77154. ColorCurves.Parse = function (source) {
  77155. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77156. };
  77157. __decorate([
  77158. BABYLON.serialize()
  77159. ], ColorCurves.prototype, "_globalHue", void 0);
  77160. __decorate([
  77161. BABYLON.serialize()
  77162. ], ColorCurves.prototype, "_globalDensity", void 0);
  77163. __decorate([
  77164. BABYLON.serialize()
  77165. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77166. __decorate([
  77167. BABYLON.serialize()
  77168. ], ColorCurves.prototype, "_globalExposure", void 0);
  77169. __decorate([
  77170. BABYLON.serialize()
  77171. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77172. __decorate([
  77173. BABYLON.serialize()
  77174. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77175. __decorate([
  77176. BABYLON.serialize()
  77177. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77178. __decorate([
  77179. BABYLON.serialize()
  77180. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77181. __decorate([
  77182. BABYLON.serialize()
  77183. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77184. __decorate([
  77185. BABYLON.serialize()
  77186. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77187. __decorate([
  77188. BABYLON.serialize()
  77189. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77190. __decorate([
  77191. BABYLON.serialize()
  77192. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77193. return ColorCurves;
  77194. }());
  77195. BABYLON.ColorCurves = ColorCurves;
  77196. })(BABYLON || (BABYLON = {}));
  77197. //# sourceMappingURL=babylon.colorCurves.js.map
  77198. var BABYLON;
  77199. (function (BABYLON) {
  77200. var RefractionPostProcess = /** @class */ (function (_super) {
  77201. __extends(RefractionPostProcess, _super);
  77202. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77203. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77204. _this.color = color;
  77205. _this.depth = depth;
  77206. _this.colorLevel = colorLevel;
  77207. _this._ownRefractionTexture = true;
  77208. _this.onActivateObservable.add(function (cam) {
  77209. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77210. });
  77211. _this.onApplyObservable.add(function (effect) {
  77212. effect.setColor3("baseColor", _this.color);
  77213. effect.setFloat("depth", _this.depth);
  77214. effect.setFloat("colorLevel", _this.colorLevel);
  77215. effect.setTexture("refractionSampler", _this._refTexture);
  77216. });
  77217. return _this;
  77218. }
  77219. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77220. /**
  77221. * Gets or sets the refraction texture
  77222. * Please note that you are responsible for disposing the texture if you set it manually
  77223. */
  77224. get: function () {
  77225. return this._refTexture;
  77226. },
  77227. set: function (value) {
  77228. if (this._refTexture && this._ownRefractionTexture) {
  77229. this._refTexture.dispose();
  77230. }
  77231. this._refTexture = value;
  77232. this._ownRefractionTexture = false;
  77233. },
  77234. enumerable: true,
  77235. configurable: true
  77236. });
  77237. // Methods
  77238. RefractionPostProcess.prototype.dispose = function (camera) {
  77239. if (this._refTexture && this._ownRefractionTexture) {
  77240. this._refTexture.dispose();
  77241. this._refTexture = null;
  77242. }
  77243. _super.prototype.dispose.call(this, camera);
  77244. };
  77245. return RefractionPostProcess;
  77246. }(BABYLON.PostProcess));
  77247. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77248. })(BABYLON || (BABYLON = {}));
  77249. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77250. var BABYLON;
  77251. (function (BABYLON) {
  77252. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77253. __extends(BlackAndWhitePostProcess, _super);
  77254. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77255. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77256. _this.degree = 1;
  77257. _this.onApplyObservable.add(function (effect) {
  77258. effect.setFloat("degree", _this.degree);
  77259. });
  77260. return _this;
  77261. }
  77262. return BlackAndWhitePostProcess;
  77263. }(BABYLON.PostProcess));
  77264. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77265. })(BABYLON || (BABYLON = {}));
  77266. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77267. var BABYLON;
  77268. (function (BABYLON) {
  77269. /**
  77270. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77271. * input texture to perform effects such as edge detection or sharpening
  77272. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77273. */
  77274. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77275. __extends(ConvolutionPostProcess, _super);
  77276. /**
  77277. * Creates a new instance ConvolutionPostProcess
  77278. * @param name The name of the effect.
  77279. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77280. * @param options The required width/height ratio to downsize to before computing the render pass.
  77281. * @param camera The camera to apply the render pass to.
  77282. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77283. * @param engine The engine which the post process will be applied. (default: current engine)
  77284. * @param reusable If the post process can be reused on the same frame. (default: false)
  77285. * @param textureType Type of textures used when performing the post process. (default: 0)
  77286. */
  77287. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77289. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77290. _this.kernel = kernel;
  77291. _this.onApply = function (effect) {
  77292. effect.setFloat2("screenSize", _this.width, _this.height);
  77293. effect.setArray("kernel", _this.kernel);
  77294. };
  77295. return _this;
  77296. }
  77297. // Statics
  77298. /**
  77299. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77300. */
  77301. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77302. /**
  77303. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77304. */
  77305. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77306. /**
  77307. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77308. */
  77309. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77310. /**
  77311. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77312. */
  77313. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77314. /**
  77315. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77316. */
  77317. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77318. /**
  77319. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77320. */
  77321. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77322. return ConvolutionPostProcess;
  77323. }(BABYLON.PostProcess));
  77324. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77325. })(BABYLON || (BABYLON = {}));
  77326. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77327. var BABYLON;
  77328. (function (BABYLON) {
  77329. var FilterPostProcess = /** @class */ (function (_super) {
  77330. __extends(FilterPostProcess, _super);
  77331. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77332. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77333. _this.kernelMatrix = kernelMatrix;
  77334. _this.onApply = function (effect) {
  77335. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77336. };
  77337. return _this;
  77338. }
  77339. return FilterPostProcess;
  77340. }(BABYLON.PostProcess));
  77341. BABYLON.FilterPostProcess = FilterPostProcess;
  77342. })(BABYLON || (BABYLON = {}));
  77343. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77344. var BABYLON;
  77345. (function (BABYLON) {
  77346. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77347. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77348. __extends(VolumetricLightScatteringPostProcess, _super);
  77349. /**
  77350. * @constructor
  77351. * @param {string} name - The post-process name
  77352. * @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)
  77353. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77354. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77355. * @param {number} samples - The post-process quality, default 100
  77356. * @param {number} samplingMode - The post-process filtering mode
  77357. * @param {BABYLON.Engine} engine - The babylon engine
  77358. * @param {boolean} reusable - If the post-process is reusable
  77359. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77360. */
  77361. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77362. if (samples === void 0) { samples = 100; }
  77363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77364. 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;
  77365. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77366. /**
  77367. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77368. */
  77369. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77370. /**
  77371. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77372. */
  77373. _this.useCustomMeshPosition = false;
  77374. /**
  77375. * If the post-process should inverse the light scattering direction
  77376. */
  77377. _this.invert = true;
  77378. /**
  77379. * Array containing the excluded meshes not rendered in the internal pass
  77380. */
  77381. _this.excludedMeshes = new Array();
  77382. /**
  77383. * Controls the overall intensity of the post-process
  77384. */
  77385. _this.exposure = 0.3;
  77386. /**
  77387. * Dissipates each sample's contribution in range [0, 1]
  77388. */
  77389. _this.decay = 0.96815;
  77390. /**
  77391. * Controls the overall intensity of each sample
  77392. */
  77393. _this.weight = 0.58767;
  77394. /**
  77395. * Controls the density of each sample
  77396. */
  77397. _this.density = 0.926;
  77398. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77399. engine = scene.getEngine();
  77400. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77401. // Configure mesh
  77402. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77403. // Configure
  77404. _this._createPass(scene, ratio.passRatio || ratio);
  77405. _this.onActivate = function (camera) {
  77406. if (!_this.isSupported) {
  77407. _this.dispose(camera);
  77408. }
  77409. _this.onActivate = null;
  77410. };
  77411. _this.onApplyObservable.add(function (effect) {
  77412. _this._updateMeshScreenCoordinates(scene);
  77413. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77414. effect.setFloat("exposure", _this.exposure);
  77415. effect.setFloat("decay", _this.decay);
  77416. effect.setFloat("weight", _this.weight);
  77417. effect.setFloat("density", _this.density);
  77418. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77419. });
  77420. return _this;
  77421. }
  77422. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77423. get: function () {
  77424. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77425. return false;
  77426. },
  77427. set: function (useDiffuseColor) {
  77428. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77429. },
  77430. enumerable: true,
  77431. configurable: true
  77432. });
  77433. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77434. return "VolumetricLightScatteringPostProcess";
  77435. };
  77436. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77437. var mesh = subMesh.getMesh();
  77438. // Render this.mesh as default
  77439. if (mesh === this.mesh && mesh.material) {
  77440. return mesh.material.isReady(mesh);
  77441. }
  77442. var defines = [];
  77443. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77444. var material = subMesh.getMaterial();
  77445. // Alpha test
  77446. if (material) {
  77447. if (material.needAlphaTesting()) {
  77448. defines.push("#define ALPHATEST");
  77449. }
  77450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77451. attribs.push(BABYLON.VertexBuffer.UVKind);
  77452. defines.push("#define UV1");
  77453. }
  77454. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77455. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77456. defines.push("#define UV2");
  77457. }
  77458. }
  77459. // Bones
  77460. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77463. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77464. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77465. }
  77466. else {
  77467. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77468. }
  77469. // Instances
  77470. if (useInstances) {
  77471. defines.push("#define INSTANCES");
  77472. attribs.push("world0");
  77473. attribs.push("world1");
  77474. attribs.push("world2");
  77475. attribs.push("world3");
  77476. }
  77477. // Get correct effect
  77478. var join = defines.join("\n");
  77479. if (this._cachedDefines !== join) {
  77480. this._cachedDefines = join;
  77481. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77482. }
  77483. return this._volumetricLightScatteringPass.isReady();
  77484. };
  77485. /**
  77486. * Sets the new light position for light scattering effect
  77487. * @param {BABYLON.Vector3} The new custom light position
  77488. */
  77489. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77490. this.customMeshPosition = position;
  77491. };
  77492. /**
  77493. * Returns the light position for light scattering effect
  77494. * @return {BABYLON.Vector3} The custom light position
  77495. */
  77496. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77497. return this.customMeshPosition;
  77498. };
  77499. /**
  77500. * Disposes the internal assets and detaches the post-process from the camera
  77501. */
  77502. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77503. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77504. if (rttIndex !== -1) {
  77505. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77506. }
  77507. this._volumetricLightScatteringRTT.dispose();
  77508. _super.prototype.dispose.call(this, camera);
  77509. };
  77510. /**
  77511. * Returns the render target texture used by the post-process
  77512. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77513. */
  77514. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77515. return this._volumetricLightScatteringRTT;
  77516. };
  77517. // Private methods
  77518. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77519. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77520. return true;
  77521. }
  77522. return false;
  77523. };
  77524. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77525. var _this = this;
  77526. var engine = scene.getEngine();
  77527. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77528. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77529. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77530. this._volumetricLightScatteringRTT.renderList = null;
  77531. this._volumetricLightScatteringRTT.renderParticles = false;
  77532. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77533. var camera = this.getCamera();
  77534. if (camera) {
  77535. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77536. }
  77537. else {
  77538. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77539. }
  77540. // Custom render function for submeshes
  77541. var renderSubMesh = function (subMesh) {
  77542. var mesh = subMesh.getRenderingMesh();
  77543. if (_this._meshExcluded(mesh)) {
  77544. return;
  77545. }
  77546. var material = subMesh.getMaterial();
  77547. if (!material) {
  77548. return;
  77549. }
  77550. var scene = mesh.getScene();
  77551. var engine = scene.getEngine();
  77552. // Culling
  77553. engine.setState(material.backFaceCulling);
  77554. // Managing instances
  77555. var batch = mesh._getInstancesRenderList(subMesh._id);
  77556. if (batch.mustReturn) {
  77557. return;
  77558. }
  77559. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77560. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77561. var effect = _this._volumetricLightScatteringPass;
  77562. if (mesh === _this.mesh) {
  77563. if (subMesh.effect) {
  77564. effect = subMesh.effect;
  77565. }
  77566. else {
  77567. effect = material.getEffect();
  77568. }
  77569. }
  77570. engine.enableEffect(effect);
  77571. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77572. if (mesh === _this.mesh) {
  77573. material.bind(mesh.getWorldMatrix(), mesh);
  77574. }
  77575. else {
  77576. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77577. // Alpha test
  77578. if (material && material.needAlphaTesting()) {
  77579. var alphaTexture = material.getAlphaTestTexture();
  77580. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77581. if (alphaTexture) {
  77582. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77583. }
  77584. }
  77585. // Bones
  77586. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77587. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77588. }
  77589. }
  77590. // Draw
  77591. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77592. }
  77593. };
  77594. // Render target texture callbacks
  77595. var savedSceneClearColor;
  77596. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77597. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77598. savedSceneClearColor = scene.clearColor;
  77599. scene.clearColor = sceneClearColor;
  77600. });
  77601. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77602. scene.clearColor = savedSceneClearColor;
  77603. });
  77604. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77605. var engine = scene.getEngine();
  77606. var index;
  77607. if (depthOnlySubMeshes.length) {
  77608. engine.setColorWrite(false);
  77609. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77610. renderSubMesh(depthOnlySubMeshes.data[index]);
  77611. }
  77612. engine.setColorWrite(true);
  77613. }
  77614. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77615. renderSubMesh(opaqueSubMeshes.data[index]);
  77616. }
  77617. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77618. renderSubMesh(alphaTestSubMeshes.data[index]);
  77619. }
  77620. if (transparentSubMeshes.length) {
  77621. // Sort sub meshes
  77622. for (index = 0; index < transparentSubMeshes.length; index++) {
  77623. var submesh = transparentSubMeshes.data[index];
  77624. var boundingInfo = submesh.getBoundingInfo();
  77625. if (boundingInfo && scene.activeCamera) {
  77626. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77627. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77628. }
  77629. }
  77630. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77631. sortedArray.sort(function (a, b) {
  77632. // Alpha index first
  77633. if (a._alphaIndex > b._alphaIndex) {
  77634. return 1;
  77635. }
  77636. if (a._alphaIndex < b._alphaIndex) {
  77637. return -1;
  77638. }
  77639. // Then distance to camera
  77640. if (a._distanceToCamera < b._distanceToCamera) {
  77641. return 1;
  77642. }
  77643. if (a._distanceToCamera > b._distanceToCamera) {
  77644. return -1;
  77645. }
  77646. return 0;
  77647. });
  77648. // Render sub meshes
  77649. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77650. for (index = 0; index < sortedArray.length; index++) {
  77651. renderSubMesh(sortedArray[index]);
  77652. }
  77653. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77654. }
  77655. };
  77656. };
  77657. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77658. var transform = scene.getTransformMatrix();
  77659. var meshPosition;
  77660. if (this.useCustomMeshPosition) {
  77661. meshPosition = this.customMeshPosition;
  77662. }
  77663. else if (this.attachedNode) {
  77664. meshPosition = this.attachedNode.position;
  77665. }
  77666. else {
  77667. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77668. }
  77669. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77670. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77671. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77672. if (this.invert)
  77673. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77674. };
  77675. // Static methods
  77676. /**
  77677. * Creates a default mesh for the Volumeric Light Scattering post-process
  77678. * @param {string} The mesh name
  77679. * @param {BABYLON.Scene} The scene where to create the mesh
  77680. * @return {BABYLON.Mesh} the default mesh
  77681. */
  77682. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77683. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77684. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77685. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77686. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77687. mesh.material = material;
  77688. return mesh;
  77689. };
  77690. __decorate([
  77691. BABYLON.serializeAsVector3()
  77692. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77693. __decorate([
  77694. BABYLON.serialize()
  77695. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77696. __decorate([
  77697. BABYLON.serialize()
  77698. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77699. __decorate([
  77700. BABYLON.serializeAsMeshReference()
  77701. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77702. __decorate([
  77703. BABYLON.serialize()
  77704. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77705. __decorate([
  77706. BABYLON.serialize()
  77707. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77708. __decorate([
  77709. BABYLON.serialize()
  77710. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77711. __decorate([
  77712. BABYLON.serialize()
  77713. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77714. __decorate([
  77715. BABYLON.serialize()
  77716. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77717. return VolumetricLightScatteringPostProcess;
  77718. }(BABYLON.PostProcess));
  77719. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77720. })(BABYLON || (BABYLON = {}));
  77721. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77722. //
  77723. // This post-process allows the modification of rendered colors by using
  77724. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77725. //
  77726. // The object needs to be provided an url to a texture containing the color
  77727. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77728. // Use an image editing software to tweak the LUT to match your needs.
  77729. //
  77730. // For an example of a color LUT, see here:
  77731. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77732. // For explanations on color grading, see here:
  77733. // http://udn.epicgames.com/Three/ColorGrading.html
  77734. //
  77735. var BABYLON;
  77736. (function (BABYLON) {
  77737. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77738. __extends(ColorCorrectionPostProcess, _super);
  77739. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77740. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77741. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77742. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77743. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77744. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77745. _this.onApply = function (effect) {
  77746. effect.setTexture("colorTable", _this._colorTableTexture);
  77747. };
  77748. return _this;
  77749. }
  77750. return ColorCorrectionPostProcess;
  77751. }(BABYLON.PostProcess));
  77752. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77753. })(BABYLON || (BABYLON = {}));
  77754. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77755. var BABYLON;
  77756. (function (BABYLON) {
  77757. /** Defines operator used for tonemapping */
  77758. var TonemappingOperator;
  77759. (function (TonemappingOperator) {
  77760. /** Hable */
  77761. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77762. /** Reinhard */
  77763. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77764. /** HejiDawson */
  77765. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77766. /** Photographic */
  77767. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77768. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77769. ;
  77770. /**
  77771. * Defines a post process to apply tone mapping
  77772. */
  77773. var TonemapPostProcess = /** @class */ (function (_super) {
  77774. __extends(TonemapPostProcess, _super);
  77775. /**
  77776. * Creates a new TonemapPostProcess
  77777. * @param name defines the name of the postprocess
  77778. * @param _operator defines the operator to use
  77779. * @param exposureAdjustment defines the required exposure adjustement
  77780. * @param camera defines the camera to use (can be null)
  77781. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77782. * @param engine defines the hosting engine (can be ignore if camera is set)
  77783. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77784. */
  77785. function TonemapPostProcess(name, _operator,
  77786. /** Defines the required exposure adjustement */
  77787. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77789. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77790. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77791. _this._operator = _operator;
  77792. _this.exposureAdjustment = exposureAdjustment;
  77793. var defines = "#define ";
  77794. if (_this._operator === TonemappingOperator.Hable)
  77795. defines += "HABLE_TONEMAPPING";
  77796. else if (_this._operator === TonemappingOperator.Reinhard)
  77797. defines += "REINHARD_TONEMAPPING";
  77798. else if (_this._operator === TonemappingOperator.HejiDawson)
  77799. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77800. else if (_this._operator === TonemappingOperator.Photographic)
  77801. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77802. //sadly a second call to create the effect.
  77803. _this.updateEffect(defines);
  77804. _this.onApply = function (effect) {
  77805. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77806. };
  77807. return _this;
  77808. }
  77809. return TonemapPostProcess;
  77810. }(BABYLON.PostProcess));
  77811. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77812. })(BABYLON || (BABYLON = {}));
  77813. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77814. var BABYLON;
  77815. (function (BABYLON) {
  77816. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77817. __extends(DisplayPassPostProcess, _super);
  77818. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77819. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77820. }
  77821. return DisplayPassPostProcess;
  77822. }(BABYLON.PostProcess));
  77823. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77824. })(BABYLON || (BABYLON = {}));
  77825. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77826. var BABYLON;
  77827. (function (BABYLON) {
  77828. var HighlightsPostProcess = /** @class */ (function (_super) {
  77829. __extends(HighlightsPostProcess, _super);
  77830. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77831. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77832. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77833. }
  77834. return HighlightsPostProcess;
  77835. }(BABYLON.PostProcess));
  77836. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77837. })(BABYLON || (BABYLON = {}));
  77838. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77839. var BABYLON;
  77840. (function (BABYLON) {
  77841. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77842. __extends(ImageProcessingPostProcess, _super);
  77843. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77844. if (camera === void 0) { camera = null; }
  77845. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77846. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77847. _this._fromLinearSpace = true;
  77848. /**
  77849. * Defines cache preventing GC.
  77850. */
  77851. _this._defines = {
  77852. IMAGEPROCESSING: false,
  77853. VIGNETTE: false,
  77854. VIGNETTEBLENDMODEMULTIPLY: false,
  77855. VIGNETTEBLENDMODEOPAQUE: false,
  77856. TONEMAPPING: false,
  77857. CONTRAST: false,
  77858. COLORCURVES: false,
  77859. COLORGRADING: false,
  77860. COLORGRADING3D: false,
  77861. FROMLINEARSPACE: false,
  77862. SAMPLER3DGREENDEPTH: false,
  77863. SAMPLER3DBGRMAP: false,
  77864. IMAGEPROCESSINGPOSTPROCESS: false,
  77865. EXPOSURE: false,
  77866. };
  77867. // Setup the configuration as forced by the constructor. This would then not force the
  77868. // scene materials output in linear space and let untouched the default forward pass.
  77869. if (imageProcessingConfiguration) {
  77870. imageProcessingConfiguration.applyByPostProcess = true;
  77871. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77872. // This will cause the shader to be compiled
  77873. _this.fromLinearSpace = false;
  77874. }
  77875. // Setup the default processing configuration to the scene.
  77876. else {
  77877. _this._attachImageProcessingConfiguration(null, true);
  77878. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77879. }
  77880. _this.onApply = function (effect) {
  77881. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77882. };
  77883. return _this;
  77884. }
  77885. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77886. /**
  77887. * Gets the image processing configuration used either in this material.
  77888. */
  77889. get: function () {
  77890. return this._imageProcessingConfiguration;
  77891. },
  77892. /**
  77893. * Sets the Default image processing configuration used either in the this material.
  77894. *
  77895. * If sets to null, the scene one is in use.
  77896. */
  77897. set: function (value) {
  77898. this._attachImageProcessingConfiguration(value);
  77899. },
  77900. enumerable: true,
  77901. configurable: true
  77902. });
  77903. /**
  77904. * Attaches a new image processing configuration to the PBR Material.
  77905. * @param configuration
  77906. */
  77907. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77908. var _this = this;
  77909. if (doNotBuild === void 0) { doNotBuild = false; }
  77910. if (configuration === this._imageProcessingConfiguration) {
  77911. return;
  77912. }
  77913. // Detaches observer.
  77914. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77915. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77916. }
  77917. // Pick the scene configuration if needed.
  77918. if (!configuration) {
  77919. var scene = null;
  77920. var engine = this.getEngine();
  77921. var camera = this.getCamera();
  77922. if (camera) {
  77923. scene = camera.getScene();
  77924. }
  77925. else if (engine && engine.scenes) {
  77926. var scenes = engine.scenes;
  77927. scene = scenes[scenes.length - 1];
  77928. }
  77929. else {
  77930. scene = BABYLON.Engine.LastCreatedScene;
  77931. }
  77932. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77933. }
  77934. else {
  77935. this._imageProcessingConfiguration = configuration;
  77936. }
  77937. // Attaches observer.
  77938. if (this._imageProcessingConfiguration) {
  77939. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77940. _this._updateParameters();
  77941. });
  77942. }
  77943. // Ensure the effect will be rebuilt.
  77944. if (!doNotBuild) {
  77945. this._updateParameters();
  77946. }
  77947. };
  77948. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77949. /**
  77950. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77951. */
  77952. get: function () {
  77953. return this.imageProcessingConfiguration.colorCurves;
  77954. },
  77955. /**
  77956. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77957. */
  77958. set: function (value) {
  77959. this.imageProcessingConfiguration.colorCurves = value;
  77960. },
  77961. enumerable: true,
  77962. configurable: true
  77963. });
  77964. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77965. /**
  77966. * Gets wether the color curves effect is enabled.
  77967. */
  77968. get: function () {
  77969. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77970. },
  77971. /**
  77972. * Sets wether the color curves effect is enabled.
  77973. */
  77974. set: function (value) {
  77975. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77976. },
  77977. enumerable: true,
  77978. configurable: true
  77979. });
  77980. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77981. /**
  77982. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77983. */
  77984. get: function () {
  77985. return this.imageProcessingConfiguration.colorGradingTexture;
  77986. },
  77987. /**
  77988. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77989. */
  77990. set: function (value) {
  77991. this.imageProcessingConfiguration.colorGradingTexture = value;
  77992. },
  77993. enumerable: true,
  77994. configurable: true
  77995. });
  77996. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77997. /**
  77998. * Gets wether the color grading effect is enabled.
  77999. */
  78000. get: function () {
  78001. return this.imageProcessingConfiguration.colorGradingEnabled;
  78002. },
  78003. /**
  78004. * Gets wether the color grading effect is enabled.
  78005. */
  78006. set: function (value) {
  78007. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78008. },
  78009. enumerable: true,
  78010. configurable: true
  78011. });
  78012. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78013. /**
  78014. * Gets exposure used in the effect.
  78015. */
  78016. get: function () {
  78017. return this.imageProcessingConfiguration.exposure;
  78018. },
  78019. /**
  78020. * Sets exposure used in the effect.
  78021. */
  78022. set: function (value) {
  78023. this.imageProcessingConfiguration.exposure = value;
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78029. /**
  78030. * Gets wether tonemapping is enabled or not.
  78031. */
  78032. get: function () {
  78033. return this._imageProcessingConfiguration.toneMappingEnabled;
  78034. },
  78035. /**
  78036. * Sets wether tonemapping is enabled or not
  78037. */
  78038. set: function (value) {
  78039. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78040. },
  78041. enumerable: true,
  78042. configurable: true
  78043. });
  78044. ;
  78045. ;
  78046. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78047. /**
  78048. * Gets contrast used in the effect.
  78049. */
  78050. get: function () {
  78051. return this.imageProcessingConfiguration.contrast;
  78052. },
  78053. /**
  78054. * Sets contrast used in the effect.
  78055. */
  78056. set: function (value) {
  78057. this.imageProcessingConfiguration.contrast = value;
  78058. },
  78059. enumerable: true,
  78060. configurable: true
  78061. });
  78062. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78063. /**
  78064. * Gets Vignette stretch size.
  78065. */
  78066. get: function () {
  78067. return this.imageProcessingConfiguration.vignetteStretch;
  78068. },
  78069. /**
  78070. * Sets Vignette stretch size.
  78071. */
  78072. set: function (value) {
  78073. this.imageProcessingConfiguration.vignetteStretch = value;
  78074. },
  78075. enumerable: true,
  78076. configurable: true
  78077. });
  78078. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78079. /**
  78080. * Gets Vignette centre X Offset.
  78081. */
  78082. get: function () {
  78083. return this.imageProcessingConfiguration.vignetteCentreX;
  78084. },
  78085. /**
  78086. * Sets Vignette centre X Offset.
  78087. */
  78088. set: function (value) {
  78089. this.imageProcessingConfiguration.vignetteCentreX = value;
  78090. },
  78091. enumerable: true,
  78092. configurable: true
  78093. });
  78094. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78095. /**
  78096. * Gets Vignette centre Y Offset.
  78097. */
  78098. get: function () {
  78099. return this.imageProcessingConfiguration.vignetteCentreY;
  78100. },
  78101. /**
  78102. * Sets Vignette centre Y Offset.
  78103. */
  78104. set: function (value) {
  78105. this.imageProcessingConfiguration.vignetteCentreY = value;
  78106. },
  78107. enumerable: true,
  78108. configurable: true
  78109. });
  78110. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78111. /**
  78112. * Gets Vignette weight or intensity of the vignette effect.
  78113. */
  78114. get: function () {
  78115. return this.imageProcessingConfiguration.vignetteWeight;
  78116. },
  78117. /**
  78118. * Sets Vignette weight or intensity of the vignette effect.
  78119. */
  78120. set: function (value) {
  78121. this.imageProcessingConfiguration.vignetteWeight = value;
  78122. },
  78123. enumerable: true,
  78124. configurable: true
  78125. });
  78126. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78127. /**
  78128. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78129. * if vignetteEnabled is set to true.
  78130. */
  78131. get: function () {
  78132. return this.imageProcessingConfiguration.vignetteColor;
  78133. },
  78134. /**
  78135. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78136. * if vignetteEnabled is set to true.
  78137. */
  78138. set: function (value) {
  78139. this.imageProcessingConfiguration.vignetteColor = value;
  78140. },
  78141. enumerable: true,
  78142. configurable: true
  78143. });
  78144. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78145. /**
  78146. * Gets Camera field of view used by the Vignette effect.
  78147. */
  78148. get: function () {
  78149. return this.imageProcessingConfiguration.vignetteCameraFov;
  78150. },
  78151. /**
  78152. * Sets Camera field of view used by the Vignette effect.
  78153. */
  78154. set: function (value) {
  78155. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78156. },
  78157. enumerable: true,
  78158. configurable: true
  78159. });
  78160. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78161. /**
  78162. * Gets the vignette blend mode allowing different kind of effect.
  78163. */
  78164. get: function () {
  78165. return this.imageProcessingConfiguration.vignetteBlendMode;
  78166. },
  78167. /**
  78168. * Sets the vignette blend mode allowing different kind of effect.
  78169. */
  78170. set: function (value) {
  78171. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78172. },
  78173. enumerable: true,
  78174. configurable: true
  78175. });
  78176. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78177. /**
  78178. * Gets wether the vignette effect is enabled.
  78179. */
  78180. get: function () {
  78181. return this.imageProcessingConfiguration.vignetteEnabled;
  78182. },
  78183. /**
  78184. * Sets wether the vignette effect is enabled.
  78185. */
  78186. set: function (value) {
  78187. this.imageProcessingConfiguration.vignetteEnabled = value;
  78188. },
  78189. enumerable: true,
  78190. configurable: true
  78191. });
  78192. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78193. /**
  78194. * Gets wether the input of the processing is in Gamma or Linear Space.
  78195. */
  78196. get: function () {
  78197. return this._fromLinearSpace;
  78198. },
  78199. /**
  78200. * Sets wether the input of the processing is in Gamma or Linear Space.
  78201. */
  78202. set: function (value) {
  78203. if (this._fromLinearSpace === value) {
  78204. return;
  78205. }
  78206. this._fromLinearSpace = value;
  78207. this._updateParameters();
  78208. },
  78209. enumerable: true,
  78210. configurable: true
  78211. });
  78212. ImageProcessingPostProcess.prototype.getClassName = function () {
  78213. return "ImageProcessingPostProcess";
  78214. };
  78215. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78216. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78217. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78218. var defines = "";
  78219. for (var define in this._defines) {
  78220. if (this._defines[define]) {
  78221. defines += "#define " + define + ";\r\n";
  78222. }
  78223. }
  78224. var samplers = ["textureSampler"];
  78225. var uniforms = ["scale"];
  78226. if (BABYLON.ImageProcessingConfiguration) {
  78227. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78228. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78229. }
  78230. this.updateEffect(defines, uniforms, samplers);
  78231. };
  78232. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78233. _super.prototype.dispose.call(this, camera);
  78234. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78235. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78236. }
  78237. if (this._imageProcessingConfiguration) {
  78238. this.imageProcessingConfiguration.applyByPostProcess = false;
  78239. }
  78240. };
  78241. __decorate([
  78242. BABYLON.serialize()
  78243. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78244. return ImageProcessingPostProcess;
  78245. }(BABYLON.PostProcess));
  78246. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78247. })(BABYLON || (BABYLON = {}));
  78248. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78249. var BABYLON;
  78250. (function (BABYLON) {
  78251. /**
  78252. * Class used to store bone information
  78253. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78254. */
  78255. var Bone = /** @class */ (function (_super) {
  78256. __extends(Bone, _super);
  78257. /**
  78258. * Create a new bone
  78259. * @param name defines the bone name
  78260. * @param skeleton defines the parent skeleton
  78261. * @param parentBone defines the parent (can be null if the bone is the root)
  78262. * @param localMatrix defines the local matrix
  78263. * @param restPose defines the rest pose matrix
  78264. * @param baseMatrix defines the base matrix
  78265. * @param index defines index of the bone in the hiearchy
  78266. */
  78267. function Bone(
  78268. /**
  78269. * defines the bone name
  78270. */
  78271. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78272. if (parentBone === void 0) { parentBone = null; }
  78273. if (localMatrix === void 0) { localMatrix = null; }
  78274. if (restPose === void 0) { restPose = null; }
  78275. if (baseMatrix === void 0) { baseMatrix = null; }
  78276. if (index === void 0) { index = null; }
  78277. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78278. _this.name = name;
  78279. /**
  78280. * Gets the list of child bones
  78281. */
  78282. _this.children = new Array();
  78283. /** Gets the animations associated with this bone */
  78284. _this.animations = new Array();
  78285. /**
  78286. * @hidden Internal only
  78287. * Set this value to map this bone to a different index in the transform matrices
  78288. * Set this value to -1 to exclude the bone from the transform matrices
  78289. */
  78290. _this._index = null;
  78291. _this._absoluteTransform = new BABYLON.Matrix();
  78292. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78293. _this._scalingDeterminant = 1;
  78294. _this._worldTransform = new BABYLON.Matrix();
  78295. _this._needToDecompose = true;
  78296. _this._needToCompose = false;
  78297. _this._skeleton = skeleton;
  78298. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78299. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78300. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78301. _this._index = index;
  78302. skeleton.bones.push(_this);
  78303. _this.setParent(parentBone, false);
  78304. if (baseMatrix || localMatrix) {
  78305. _this._updateDifferenceMatrix();
  78306. }
  78307. return _this;
  78308. }
  78309. Object.defineProperty(Bone.prototype, "_matrix", {
  78310. /** @hidden */
  78311. get: function () {
  78312. this._compose();
  78313. return this._localMatrix;
  78314. },
  78315. /** @hidden */
  78316. set: function (value) {
  78317. this._localMatrix.copyFrom(value);
  78318. this._needToDecompose = true;
  78319. },
  78320. enumerable: true,
  78321. configurable: true
  78322. });
  78323. // Members
  78324. /**
  78325. * Gets the parent skeleton
  78326. * @returns a skeleton
  78327. */
  78328. Bone.prototype.getSkeleton = function () {
  78329. return this._skeleton;
  78330. };
  78331. /**
  78332. * Gets parent bone
  78333. * @returns a bone or null if the bone is the root of the bone hierarchy
  78334. */
  78335. Bone.prototype.getParent = function () {
  78336. return this._parent;
  78337. };
  78338. /**
  78339. * Sets the parent bone
  78340. * @param parent defines the parent (can be null if the bone is the root)
  78341. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78342. */
  78343. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78344. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78345. if (this._parent === parent) {
  78346. return;
  78347. }
  78348. if (this._parent) {
  78349. var index = this._parent.children.indexOf(this);
  78350. if (index !== -1) {
  78351. this._parent.children.splice(index, 1);
  78352. }
  78353. }
  78354. this._parent = parent;
  78355. if (this._parent) {
  78356. this._parent.children.push(this);
  78357. }
  78358. if (updateDifferenceMatrix) {
  78359. this._updateDifferenceMatrix();
  78360. }
  78361. this.markAsDirty();
  78362. };
  78363. /**
  78364. * Gets the local matrix
  78365. * @returns a matrix
  78366. */
  78367. Bone.prototype.getLocalMatrix = function () {
  78368. this._compose();
  78369. return this._localMatrix;
  78370. };
  78371. /**
  78372. * Gets the base matrix (initial matrix which remains unchanged)
  78373. * @returns a matrix
  78374. */
  78375. Bone.prototype.getBaseMatrix = function () {
  78376. return this._baseMatrix;
  78377. };
  78378. /**
  78379. * Gets the rest pose matrix
  78380. * @returns a matrix
  78381. */
  78382. Bone.prototype.getRestPose = function () {
  78383. return this._restPose;
  78384. };
  78385. /**
  78386. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78387. */
  78388. Bone.prototype.getWorldMatrix = function () {
  78389. return this._worldTransform;
  78390. };
  78391. /**
  78392. * Sets the local matrix to rest pose matrix
  78393. */
  78394. Bone.prototype.returnToRest = function () {
  78395. this.updateMatrix(this._restPose.clone());
  78396. };
  78397. /**
  78398. * Gets the inverse of the absolute transform matrix.
  78399. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78400. * @returns a matrix
  78401. */
  78402. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78403. return this._invertedAbsoluteTransform;
  78404. };
  78405. /**
  78406. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78407. * @returns a matrix
  78408. */
  78409. Bone.prototype.getAbsoluteTransform = function () {
  78410. return this._absoluteTransform;
  78411. };
  78412. Object.defineProperty(Bone.prototype, "position", {
  78413. // Properties (matches AbstractMesh properties)
  78414. /** Gets or sets current position (in local space) */
  78415. get: function () {
  78416. this._decompose();
  78417. return this._localPosition;
  78418. },
  78419. set: function (newPosition) {
  78420. this._decompose();
  78421. this._localPosition.copyFrom(newPosition);
  78422. this._markAsDirtyAndCompose();
  78423. },
  78424. enumerable: true,
  78425. configurable: true
  78426. });
  78427. Object.defineProperty(Bone.prototype, "rotation", {
  78428. /** Gets or sets current rotation (in local space) */
  78429. get: function () {
  78430. return this.getRotation();
  78431. },
  78432. set: function (newRotation) {
  78433. this.setRotation(newRotation);
  78434. },
  78435. enumerable: true,
  78436. configurable: true
  78437. });
  78438. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78439. /** Gets or sets current rotation quaternion (in local space) */
  78440. get: function () {
  78441. this._decompose();
  78442. return this._localRotation;
  78443. },
  78444. set: function (newRotation) {
  78445. this.setRotationQuaternion(newRotation);
  78446. },
  78447. enumerable: true,
  78448. configurable: true
  78449. });
  78450. Object.defineProperty(Bone.prototype, "scaling", {
  78451. /** Gets or sets current scaling (in local space) */
  78452. get: function () {
  78453. return this.getScale();
  78454. },
  78455. set: function (newScaling) {
  78456. this.setScale(newScaling);
  78457. },
  78458. enumerable: true,
  78459. configurable: true
  78460. });
  78461. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78462. /**
  78463. * Gets the animation properties override
  78464. */
  78465. get: function () {
  78466. return this._skeleton.animationPropertiesOverride;
  78467. },
  78468. enumerable: true,
  78469. configurable: true
  78470. });
  78471. // Methods
  78472. Bone.prototype._decompose = function () {
  78473. if (!this._needToDecompose) {
  78474. return;
  78475. }
  78476. this._needToDecompose = false;
  78477. if (!this._localScaling) {
  78478. this._localScaling = BABYLON.Vector3.Zero();
  78479. this._localRotation = BABYLON.Quaternion.Zero();
  78480. this._localPosition = BABYLON.Vector3.Zero();
  78481. }
  78482. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78483. };
  78484. Bone.prototype._compose = function () {
  78485. if (!this._needToCompose) {
  78486. return;
  78487. }
  78488. this._needToCompose = false;
  78489. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78490. };
  78491. /**
  78492. * Update the base and local matrices
  78493. * @param matrix defines the new base or local matrix
  78494. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78495. * @param updateLocalMatrix defines if the local matrix should be updated
  78496. */
  78497. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78498. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78499. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78500. this._baseMatrix.copyFrom(matrix);
  78501. if (updateDifferenceMatrix) {
  78502. this._updateDifferenceMatrix();
  78503. }
  78504. if (updateLocalMatrix) {
  78505. this._localMatrix.copyFrom(matrix);
  78506. this._markAsDirtyAndDecompose();
  78507. }
  78508. else {
  78509. this.markAsDirty();
  78510. }
  78511. };
  78512. /** @hidden */
  78513. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78514. if (updateChildren === void 0) { updateChildren = true; }
  78515. if (!rootMatrix) {
  78516. rootMatrix = this._baseMatrix;
  78517. }
  78518. if (this._parent) {
  78519. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78520. }
  78521. else {
  78522. this._absoluteTransform.copyFrom(rootMatrix);
  78523. }
  78524. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78525. if (updateChildren) {
  78526. for (var index = 0; index < this.children.length; index++) {
  78527. this.children[index]._updateDifferenceMatrix();
  78528. }
  78529. }
  78530. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78531. };
  78532. /**
  78533. * Flag the bone as dirty (Forcing it to update everything)
  78534. */
  78535. Bone.prototype.markAsDirty = function () {
  78536. this._currentRenderId++;
  78537. this._childRenderId++;
  78538. this._skeleton._markAsDirty();
  78539. };
  78540. Bone.prototype._markAsDirtyAndCompose = function () {
  78541. this.markAsDirty();
  78542. this._needToCompose = true;
  78543. };
  78544. Bone.prototype._markAsDirtyAndDecompose = function () {
  78545. this.markAsDirty();
  78546. this._needToDecompose = true;
  78547. };
  78548. /**
  78549. * Copy an animation range from another bone
  78550. * @param source defines the source bone
  78551. * @param rangeName defines the range name to copy
  78552. * @param frameOffset defines the frame offset
  78553. * @param rescaleAsRequired defines if rescaling must be applied if required
  78554. * @param skelDimensionsRatio defines the scaling ratio
  78555. * @returns true if operation was successful
  78556. */
  78557. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78558. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78559. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78560. // all animation may be coming from a library skeleton, so may need to create animation
  78561. if (this.animations.length === 0) {
  78562. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78563. this.animations[0].setKeys([]);
  78564. }
  78565. // get animation info / verify there is such a range from the source bone
  78566. var sourceRange = source.animations[0].getRange(rangeName);
  78567. if (!sourceRange) {
  78568. return false;
  78569. }
  78570. var from = sourceRange.from;
  78571. var to = sourceRange.to;
  78572. var sourceKeys = source.animations[0].getKeys();
  78573. // rescaling prep
  78574. var sourceBoneLength = source.length;
  78575. var sourceParent = source.getParent();
  78576. var parent = this.getParent();
  78577. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78578. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78579. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78580. var destKeys = this.animations[0].getKeys();
  78581. // loop vars declaration
  78582. var orig;
  78583. var origTranslation;
  78584. var mat;
  78585. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78586. orig = sourceKeys[key];
  78587. if (orig.frame >= from && orig.frame <= to) {
  78588. if (rescaleAsRequired) {
  78589. mat = orig.value.clone();
  78590. // scale based on parent ratio, when bone has parent
  78591. if (parentScalingReqd) {
  78592. origTranslation = mat.getTranslation();
  78593. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78594. // scale based on skeleton dimension ratio when root bone, and value is passed
  78595. }
  78596. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78597. origTranslation = mat.getTranslation();
  78598. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78599. // use original when root bone, and no data for skelDimensionsRatio
  78600. }
  78601. else {
  78602. mat = orig.value;
  78603. }
  78604. }
  78605. else {
  78606. mat = orig.value;
  78607. }
  78608. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78609. }
  78610. }
  78611. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78612. return true;
  78613. };
  78614. /**
  78615. * Translate the bone in local or world space
  78616. * @param vec The amount to translate the bone
  78617. * @param space The space that the translation is in
  78618. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78619. */
  78620. Bone.prototype.translate = function (vec, space, mesh) {
  78621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78622. var lm = this.getLocalMatrix();
  78623. if (space == BABYLON.Space.LOCAL) {
  78624. lm.m[12] += vec.x;
  78625. lm.m[13] += vec.y;
  78626. lm.m[14] += vec.z;
  78627. }
  78628. else {
  78629. var wm = null;
  78630. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78631. if (mesh) {
  78632. wm = mesh.getWorldMatrix();
  78633. }
  78634. this._skeleton.computeAbsoluteTransforms();
  78635. var tmat = Bone._tmpMats[0];
  78636. var tvec = Bone._tmpVecs[0];
  78637. if (this._parent) {
  78638. if (mesh && wm) {
  78639. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78640. tmat.multiplyToRef(wm, tmat);
  78641. }
  78642. else {
  78643. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78644. }
  78645. }
  78646. tmat.m[12] = 0;
  78647. tmat.m[13] = 0;
  78648. tmat.m[14] = 0;
  78649. tmat.invert();
  78650. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78651. lm.m[12] += tvec.x;
  78652. lm.m[13] += tvec.y;
  78653. lm.m[14] += tvec.z;
  78654. }
  78655. this._markAsDirtyAndDecompose();
  78656. };
  78657. /**
  78658. * Set the postion of the bone in local or world space
  78659. * @param position The position to set the bone
  78660. * @param space The space that the position is in
  78661. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78662. */
  78663. Bone.prototype.setPosition = function (position, space, mesh) {
  78664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78665. var lm = this.getLocalMatrix();
  78666. if (space == BABYLON.Space.LOCAL) {
  78667. lm.m[12] = position.x;
  78668. lm.m[13] = position.y;
  78669. lm.m[14] = position.z;
  78670. }
  78671. else {
  78672. var wm = null;
  78673. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78674. if (mesh) {
  78675. wm = mesh.getWorldMatrix();
  78676. }
  78677. this._skeleton.computeAbsoluteTransforms();
  78678. var tmat = Bone._tmpMats[0];
  78679. var vec = Bone._tmpVecs[0];
  78680. if (this._parent) {
  78681. if (mesh && wm) {
  78682. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78683. tmat.multiplyToRef(wm, tmat);
  78684. }
  78685. else {
  78686. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78687. }
  78688. }
  78689. tmat.invert();
  78690. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78691. lm.m[12] = vec.x;
  78692. lm.m[13] = vec.y;
  78693. lm.m[14] = vec.z;
  78694. }
  78695. this._markAsDirtyAndDecompose();
  78696. };
  78697. /**
  78698. * Set the absolute position of the bone (world space)
  78699. * @param position The position to set the bone
  78700. * @param mesh The mesh that this bone is attached to
  78701. */
  78702. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78703. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78704. };
  78705. /**
  78706. * Scale the bone on the x, y and z axes (in local space)
  78707. * @param x The amount to scale the bone on the x axis
  78708. * @param y The amount to scale the bone on the y axis
  78709. * @param z The amount to scale the bone on the z axis
  78710. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78711. */
  78712. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78713. if (scaleChildren === void 0) { scaleChildren = false; }
  78714. var locMat = this.getLocalMatrix();
  78715. // Apply new scaling on top of current local matrix
  78716. var scaleMat = Bone._tmpMats[0];
  78717. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78718. scaleMat.multiplyToRef(locMat, locMat);
  78719. // Invert scaling matrix and apply the inverse to all children
  78720. scaleMat.invert();
  78721. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78722. var child = _a[_i];
  78723. var cm = child.getLocalMatrix();
  78724. cm.multiplyToRef(scaleMat, cm);
  78725. cm.m[12] *= x;
  78726. cm.m[13] *= y;
  78727. cm.m[14] *= z;
  78728. child._markAsDirtyAndDecompose();
  78729. }
  78730. this._markAsDirtyAndDecompose();
  78731. if (scaleChildren) {
  78732. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78733. var child = _c[_b];
  78734. child.scale(x, y, z, scaleChildren);
  78735. }
  78736. }
  78737. };
  78738. /**
  78739. * Set the bone scaling in local space
  78740. * @param scale defines the scaling vector
  78741. */
  78742. Bone.prototype.setScale = function (scale) {
  78743. this._decompose();
  78744. this._localScaling.copyFrom(scale);
  78745. this._markAsDirtyAndCompose();
  78746. };
  78747. /**
  78748. * Gets the current scaling in local space
  78749. * @returns the current scaling vector
  78750. */
  78751. Bone.prototype.getScale = function () {
  78752. this._decompose();
  78753. return this._localScaling;
  78754. };
  78755. /**
  78756. * Gets the current scaling in local space and stores it in a target vector
  78757. * @param result defines the target vector
  78758. */
  78759. Bone.prototype.getScaleToRef = function (result) {
  78760. this._decompose();
  78761. result.copyFrom(this._localScaling);
  78762. };
  78763. /**
  78764. * Set the yaw, pitch, and roll of the bone in local or world space
  78765. * @param yaw The rotation of the bone on the y axis
  78766. * @param pitch The rotation of the bone on the x axis
  78767. * @param roll The rotation of the bone on the z axis
  78768. * @param space The space that the axes of rotation are in
  78769. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78770. */
  78771. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78772. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78773. if (space === BABYLON.Space.LOCAL) {
  78774. var quat = Bone._tmpQuat;
  78775. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78776. this.setRotationQuaternion(quat, space, mesh);
  78777. return;
  78778. }
  78779. var rotMatInv = Bone._tmpMats[0];
  78780. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78781. return;
  78782. }
  78783. var rotMat = Bone._tmpMats[1];
  78784. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78785. rotMatInv.multiplyToRef(rotMat, rotMat);
  78786. this._rotateWithMatrix(rotMat, space, mesh);
  78787. };
  78788. /**
  78789. * Add a rotation to the bone on an axis in local or world space
  78790. * @param axis The axis to rotate the bone on
  78791. * @param amount The amount to rotate the bone
  78792. * @param space The space that the axis is in
  78793. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78794. */
  78795. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78796. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78797. var rmat = Bone._tmpMats[0];
  78798. rmat.m[12] = 0;
  78799. rmat.m[13] = 0;
  78800. rmat.m[14] = 0;
  78801. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78802. this._rotateWithMatrix(rmat, space, mesh);
  78803. };
  78804. /**
  78805. * Set the rotation of the bone to a particular axis angle in local or world space
  78806. * @param axis The axis to rotate the bone on
  78807. * @param angle The angle that the bone should be rotated to
  78808. * @param space The space that the axis is in
  78809. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78810. */
  78811. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78812. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78813. if (space === BABYLON.Space.LOCAL) {
  78814. var quat = Bone._tmpQuat;
  78815. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78816. this.setRotationQuaternion(quat, space, mesh);
  78817. return;
  78818. }
  78819. var rotMatInv = Bone._tmpMats[0];
  78820. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78821. return;
  78822. }
  78823. var rotMat = Bone._tmpMats[1];
  78824. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78825. rotMatInv.multiplyToRef(rotMat, rotMat);
  78826. this._rotateWithMatrix(rotMat, space, mesh);
  78827. };
  78828. /**
  78829. * Set the euler rotation of the bone in local of world space
  78830. * @param rotation The euler rotation that the bone should be set to
  78831. * @param space The space that the rotation is in
  78832. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78833. */
  78834. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78836. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78837. };
  78838. /**
  78839. * Set the quaternion rotation of the bone in local of world space
  78840. * @param quat The quaternion rotation that the bone should be set to
  78841. * @param space The space that the rotation is in
  78842. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78843. */
  78844. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78846. if (space === BABYLON.Space.LOCAL) {
  78847. this._decompose();
  78848. this._localRotation.copyFrom(quat);
  78849. this._markAsDirtyAndCompose();
  78850. return;
  78851. }
  78852. var rotMatInv = Bone._tmpMats[0];
  78853. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78854. return;
  78855. }
  78856. var rotMat = Bone._tmpMats[1];
  78857. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78858. rotMatInv.multiplyToRef(rotMat, rotMat);
  78859. this._rotateWithMatrix(rotMat, space, mesh);
  78860. };
  78861. /**
  78862. * Set the rotation matrix of the bone in local of world space
  78863. * @param rotMat The rotation matrix that the bone should be set to
  78864. * @param space The space that the rotation is in
  78865. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78866. */
  78867. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78869. if (space === BABYLON.Space.LOCAL) {
  78870. var quat = Bone._tmpQuat;
  78871. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78872. this.setRotationQuaternion(quat, space, mesh);
  78873. return;
  78874. }
  78875. var rotMatInv = Bone._tmpMats[0];
  78876. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78877. return;
  78878. }
  78879. var rotMat2 = Bone._tmpMats[1];
  78880. rotMat2.copyFrom(rotMat);
  78881. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78882. this._rotateWithMatrix(rotMat2, space, mesh);
  78883. };
  78884. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78886. var lmat = this.getLocalMatrix();
  78887. var lx = lmat.m[12];
  78888. var ly = lmat.m[13];
  78889. var lz = lmat.m[14];
  78890. var parent = this.getParent();
  78891. var parentScale = Bone._tmpMats[3];
  78892. var parentScaleInv = Bone._tmpMats[4];
  78893. if (parent && space == BABYLON.Space.WORLD) {
  78894. if (mesh) {
  78895. parentScale.copyFrom(mesh.getWorldMatrix());
  78896. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78897. }
  78898. else {
  78899. parentScale.copyFrom(parent.getAbsoluteTransform());
  78900. }
  78901. parentScaleInv.copyFrom(parentScale);
  78902. parentScaleInv.invert();
  78903. lmat.multiplyToRef(parentScale, lmat);
  78904. lmat.multiplyToRef(rmat, lmat);
  78905. lmat.multiplyToRef(parentScaleInv, lmat);
  78906. }
  78907. else {
  78908. if (space == BABYLON.Space.WORLD && mesh) {
  78909. parentScale.copyFrom(mesh.getWorldMatrix());
  78910. parentScaleInv.copyFrom(parentScale);
  78911. parentScaleInv.invert();
  78912. lmat.multiplyToRef(parentScale, lmat);
  78913. lmat.multiplyToRef(rmat, lmat);
  78914. lmat.multiplyToRef(parentScaleInv, lmat);
  78915. }
  78916. else {
  78917. lmat.multiplyToRef(rmat, lmat);
  78918. }
  78919. }
  78920. lmat.m[12] = lx;
  78921. lmat.m[13] = ly;
  78922. lmat.m[14] = lz;
  78923. this.computeAbsoluteTransforms();
  78924. this._markAsDirtyAndDecompose();
  78925. };
  78926. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78927. var scaleMatrix = Bone._tmpMats[2];
  78928. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78929. if (mesh) {
  78930. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78931. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78932. }
  78933. rotMatInv.invert();
  78934. if (isNaN(rotMatInv.m[0])) {
  78935. // Matrix failed to invert.
  78936. // This can happen if scale is zero for example.
  78937. return false;
  78938. }
  78939. scaleMatrix.m[0] *= this._scalingDeterminant;
  78940. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78941. return true;
  78942. };
  78943. /**
  78944. * Get the position of the bone in local or world space
  78945. * @param space The space that the returned position is in
  78946. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78947. * @returns The position of the bone
  78948. */
  78949. Bone.prototype.getPosition = function (space, mesh) {
  78950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78951. if (mesh === void 0) { mesh = null; }
  78952. var pos = BABYLON.Vector3.Zero();
  78953. this.getPositionToRef(space, mesh, pos);
  78954. return pos;
  78955. };
  78956. /**
  78957. * Copy the position of the bone to a vector3 in local or world space
  78958. * @param space The space that the returned position is in
  78959. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78960. * @param result The vector3 to copy the position to
  78961. */
  78962. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78964. if (space == BABYLON.Space.LOCAL) {
  78965. var lm = this.getLocalMatrix();
  78966. result.x = lm.m[12];
  78967. result.y = lm.m[13];
  78968. result.z = lm.m[14];
  78969. }
  78970. else {
  78971. var wm = null;
  78972. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78973. if (mesh) {
  78974. wm = mesh.getWorldMatrix();
  78975. }
  78976. this._skeleton.computeAbsoluteTransforms();
  78977. var tmat = Bone._tmpMats[0];
  78978. if (mesh && wm) {
  78979. tmat.copyFrom(this.getAbsoluteTransform());
  78980. tmat.multiplyToRef(wm, tmat);
  78981. }
  78982. else {
  78983. tmat = this.getAbsoluteTransform();
  78984. }
  78985. result.x = tmat.m[12];
  78986. result.y = tmat.m[13];
  78987. result.z = tmat.m[14];
  78988. }
  78989. };
  78990. /**
  78991. * Get the absolute position of the bone (world space)
  78992. * @param mesh The mesh that this bone is attached to
  78993. * @returns The absolute position of the bone
  78994. */
  78995. Bone.prototype.getAbsolutePosition = function (mesh) {
  78996. if (mesh === void 0) { mesh = null; }
  78997. var pos = BABYLON.Vector3.Zero();
  78998. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78999. return pos;
  79000. };
  79001. /**
  79002. * Copy the absolute position of the bone (world space) to the result param
  79003. * @param mesh The mesh that this bone is attached to
  79004. * @param result The vector3 to copy the absolute position to
  79005. */
  79006. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79007. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79008. };
  79009. /**
  79010. * Compute the absolute transforms of this bone and its children
  79011. */
  79012. Bone.prototype.computeAbsoluteTransforms = function () {
  79013. this._compose();
  79014. if (this._parent) {
  79015. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79016. }
  79017. else {
  79018. this._absoluteTransform.copyFrom(this._localMatrix);
  79019. var poseMatrix = this._skeleton.getPoseMatrix();
  79020. if (poseMatrix) {
  79021. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79022. }
  79023. }
  79024. var children = this.children;
  79025. var len = children.length;
  79026. for (var i = 0; i < len; i++) {
  79027. children[i].computeAbsoluteTransforms();
  79028. }
  79029. };
  79030. /**
  79031. * Get the world direction from an axis that is in the local space of the bone
  79032. * @param localAxis The local direction that is used to compute the world direction
  79033. * @param mesh The mesh that this bone is attached to
  79034. * @returns The world direction
  79035. */
  79036. Bone.prototype.getDirection = function (localAxis, mesh) {
  79037. if (mesh === void 0) { mesh = null; }
  79038. var result = BABYLON.Vector3.Zero();
  79039. this.getDirectionToRef(localAxis, mesh, result);
  79040. return result;
  79041. };
  79042. /**
  79043. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79044. * @param localAxis The local direction that is used to compute the world direction
  79045. * @param mesh The mesh that this bone is attached to
  79046. * @param result The vector3 that the world direction will be copied to
  79047. */
  79048. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79049. if (mesh === void 0) { mesh = null; }
  79050. var wm = null;
  79051. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79052. if (mesh) {
  79053. wm = mesh.getWorldMatrix();
  79054. }
  79055. this._skeleton.computeAbsoluteTransforms();
  79056. var mat = Bone._tmpMats[0];
  79057. mat.copyFrom(this.getAbsoluteTransform());
  79058. if (mesh && wm) {
  79059. mat.multiplyToRef(wm, mat);
  79060. }
  79061. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79062. result.normalize();
  79063. };
  79064. /**
  79065. * Get the euler rotation of the bone in local or world space
  79066. * @param space The space that the rotation should be in
  79067. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79068. * @returns The euler rotation
  79069. */
  79070. Bone.prototype.getRotation = function (space, mesh) {
  79071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79072. if (mesh === void 0) { mesh = null; }
  79073. var result = BABYLON.Vector3.Zero();
  79074. this.getRotationToRef(space, mesh, result);
  79075. return result;
  79076. };
  79077. /**
  79078. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79079. * @param space The space that the rotation should be in
  79080. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79081. * @param result The vector3 that the rotation should be copied to
  79082. */
  79083. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79085. if (mesh === void 0) { mesh = null; }
  79086. var quat = Bone._tmpQuat;
  79087. this.getRotationQuaternionToRef(space, mesh, quat);
  79088. quat.toEulerAnglesToRef(result);
  79089. };
  79090. /**
  79091. * Get the quaternion rotation of the bone in either local or world space
  79092. * @param space The space that the rotation should be in
  79093. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79094. * @returns The quaternion rotation
  79095. */
  79096. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79098. if (mesh === void 0) { mesh = null; }
  79099. var result = BABYLON.Quaternion.Identity();
  79100. this.getRotationQuaternionToRef(space, mesh, result);
  79101. return result;
  79102. };
  79103. /**
  79104. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79105. * @param space The space that the rotation should be in
  79106. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79107. * @param result The quaternion that the rotation should be copied to
  79108. */
  79109. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79111. if (mesh === void 0) { mesh = null; }
  79112. if (space == BABYLON.Space.LOCAL) {
  79113. this._decompose();
  79114. result.copyFrom(this._localRotation);
  79115. }
  79116. else {
  79117. var mat = Bone._tmpMats[0];
  79118. var amat = this.getAbsoluteTransform();
  79119. if (mesh) {
  79120. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79121. }
  79122. else {
  79123. mat.copyFrom(amat);
  79124. }
  79125. mat.m[0] *= this._scalingDeterminant;
  79126. mat.m[1] *= this._scalingDeterminant;
  79127. mat.m[2] *= this._scalingDeterminant;
  79128. mat.decompose(undefined, result, undefined);
  79129. }
  79130. };
  79131. /**
  79132. * Get the rotation matrix of the bone in local or world space
  79133. * @param space The space that the rotation should be in
  79134. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79135. * @returns The rotation matrix
  79136. */
  79137. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79139. var result = BABYLON.Matrix.Identity();
  79140. this.getRotationMatrixToRef(space, mesh, result);
  79141. return result;
  79142. };
  79143. /**
  79144. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79145. * @param space The space that the rotation should be in
  79146. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79147. * @param result The quaternion that the rotation should be copied to
  79148. */
  79149. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79151. if (space == BABYLON.Space.LOCAL) {
  79152. this.getLocalMatrix().getRotationMatrixToRef(result);
  79153. }
  79154. else {
  79155. var mat = Bone._tmpMats[0];
  79156. var amat = this.getAbsoluteTransform();
  79157. if (mesh) {
  79158. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79159. }
  79160. else {
  79161. mat.copyFrom(amat);
  79162. }
  79163. mat.m[0] *= this._scalingDeterminant;
  79164. mat.m[1] *= this._scalingDeterminant;
  79165. mat.m[2] *= this._scalingDeterminant;
  79166. mat.getRotationMatrixToRef(result);
  79167. }
  79168. };
  79169. /**
  79170. * Get the world position of a point that is in the local space of the bone
  79171. * @param position The local position
  79172. * @param mesh The mesh that this bone is attached to
  79173. * @returns The world position
  79174. */
  79175. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79176. if (mesh === void 0) { mesh = null; }
  79177. var result = BABYLON.Vector3.Zero();
  79178. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79179. return result;
  79180. };
  79181. /**
  79182. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79183. * @param position The local position
  79184. * @param mesh The mesh that this bone is attached to
  79185. * @param result The vector3 that the world position should be copied to
  79186. */
  79187. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79188. if (mesh === void 0) { mesh = null; }
  79189. var wm = null;
  79190. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79191. if (mesh) {
  79192. wm = mesh.getWorldMatrix();
  79193. }
  79194. this._skeleton.computeAbsoluteTransforms();
  79195. var tmat = Bone._tmpMats[0];
  79196. if (mesh && wm) {
  79197. tmat.copyFrom(this.getAbsoluteTransform());
  79198. tmat.multiplyToRef(wm, tmat);
  79199. }
  79200. else {
  79201. tmat = this.getAbsoluteTransform();
  79202. }
  79203. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79204. };
  79205. /**
  79206. * Get the local position of a point that is in world space
  79207. * @param position The world position
  79208. * @param mesh The mesh that this bone is attached to
  79209. * @returns The local position
  79210. */
  79211. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79212. if (mesh === void 0) { mesh = null; }
  79213. var result = BABYLON.Vector3.Zero();
  79214. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79215. return result;
  79216. };
  79217. /**
  79218. * Get the local position of a point that is in world space and copy it to the result param
  79219. * @param position The world position
  79220. * @param mesh The mesh that this bone is attached to
  79221. * @param result The vector3 that the local position should be copied to
  79222. */
  79223. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79224. if (mesh === void 0) { mesh = null; }
  79225. var wm = null;
  79226. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79227. if (mesh) {
  79228. wm = mesh.getWorldMatrix();
  79229. }
  79230. this._skeleton.computeAbsoluteTransforms();
  79231. var tmat = Bone._tmpMats[0];
  79232. tmat.copyFrom(this.getAbsoluteTransform());
  79233. if (mesh && wm) {
  79234. tmat.multiplyToRef(wm, tmat);
  79235. }
  79236. tmat.invert();
  79237. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79238. };
  79239. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79240. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79241. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79242. return Bone;
  79243. }(BABYLON.Node));
  79244. BABYLON.Bone = Bone;
  79245. })(BABYLON || (BABYLON = {}));
  79246. //# sourceMappingURL=babylon.bone.js.map
  79247. var BABYLON;
  79248. (function (BABYLON) {
  79249. /**
  79250. * Class used to apply inverse kinematics to bones
  79251. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79252. */
  79253. var BoneIKController = /** @class */ (function () {
  79254. /**
  79255. * Creates a new BoneIKController
  79256. * @param mesh defines the mesh to control
  79257. * @param bone defines the bone to control
  79258. * @param options defines options to set up the controller
  79259. */
  79260. function BoneIKController(mesh, bone, options) {
  79261. /**
  79262. * Gets or sets the target position
  79263. */
  79264. this.targetPosition = BABYLON.Vector3.Zero();
  79265. /**
  79266. * Gets or sets the pole target position
  79267. */
  79268. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79269. /**
  79270. * Gets or sets the pole target local offset
  79271. */
  79272. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79273. /**
  79274. * Gets or sets the pole angle
  79275. */
  79276. this.poleAngle = 0;
  79277. /**
  79278. * 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)
  79279. */
  79280. this.slerpAmount = 1;
  79281. this._bone1Quat = BABYLON.Quaternion.Identity();
  79282. this._bone1Mat = BABYLON.Matrix.Identity();
  79283. this._bone2Ang = Math.PI;
  79284. this._maxAngle = Math.PI;
  79285. this._rightHandedSystem = false;
  79286. this._bendAxis = BABYLON.Vector3.Right();
  79287. this._slerping = false;
  79288. this._adjustRoll = 0;
  79289. this._bone2 = bone;
  79290. this._bone1 = bone.getParent();
  79291. if (!this._bone1) {
  79292. return;
  79293. }
  79294. this.mesh = mesh;
  79295. var bonePos = bone.getPosition();
  79296. if (bone.getAbsoluteTransform().determinant() > 0) {
  79297. this._rightHandedSystem = true;
  79298. this._bendAxis.x = 0;
  79299. this._bendAxis.y = 0;
  79300. this._bendAxis.z = -1;
  79301. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79302. this._adjustRoll = Math.PI * .5;
  79303. this._bendAxis.z = 1;
  79304. }
  79305. }
  79306. if (this._bone1.length) {
  79307. var boneScale1 = this._bone1.getScale();
  79308. var boneScale2 = this._bone2.getScale();
  79309. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79310. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79311. }
  79312. else if (this._bone1.children[0]) {
  79313. mesh.computeWorldMatrix(true);
  79314. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79315. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79316. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79317. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79318. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79319. }
  79320. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79321. this.maxAngle = Math.PI;
  79322. if (options) {
  79323. if (options.targetMesh) {
  79324. this.targetMesh = options.targetMesh;
  79325. this.targetMesh.computeWorldMatrix(true);
  79326. }
  79327. if (options.poleTargetMesh) {
  79328. this.poleTargetMesh = options.poleTargetMesh;
  79329. this.poleTargetMesh.computeWorldMatrix(true);
  79330. }
  79331. else if (options.poleTargetBone) {
  79332. this.poleTargetBone = options.poleTargetBone;
  79333. }
  79334. else if (this._bone1.getParent()) {
  79335. this.poleTargetBone = this._bone1.getParent();
  79336. }
  79337. if (options.poleTargetLocalOffset) {
  79338. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79339. }
  79340. if (options.poleAngle) {
  79341. this.poleAngle = options.poleAngle;
  79342. }
  79343. if (options.bendAxis) {
  79344. this._bendAxis.copyFrom(options.bendAxis);
  79345. }
  79346. if (options.maxAngle) {
  79347. this.maxAngle = options.maxAngle;
  79348. }
  79349. if (options.slerpAmount) {
  79350. this.slerpAmount = options.slerpAmount;
  79351. }
  79352. }
  79353. }
  79354. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79355. /**
  79356. * Gets or sets maximum allowed angle
  79357. */
  79358. get: function () {
  79359. return this._maxAngle;
  79360. },
  79361. set: function (value) {
  79362. this._setMaxAngle(value);
  79363. },
  79364. enumerable: true,
  79365. configurable: true
  79366. });
  79367. BoneIKController.prototype._setMaxAngle = function (ang) {
  79368. if (ang < 0) {
  79369. ang = 0;
  79370. }
  79371. if (ang > Math.PI || ang == undefined) {
  79372. ang = Math.PI;
  79373. }
  79374. this._maxAngle = ang;
  79375. var a = this._bone1Length;
  79376. var b = this._bone2Length;
  79377. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79378. };
  79379. /**
  79380. * Force the controller to update the bones
  79381. */
  79382. BoneIKController.prototype.update = function () {
  79383. var bone1 = this._bone1;
  79384. if (!bone1) {
  79385. return;
  79386. }
  79387. var target = this.targetPosition;
  79388. var poleTarget = this.poleTargetPosition;
  79389. var mat1 = BoneIKController._tmpMats[0];
  79390. var mat2 = BoneIKController._tmpMats[1];
  79391. if (this.targetMesh) {
  79392. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79393. }
  79394. if (this.poleTargetBone) {
  79395. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79396. }
  79397. else if (this.poleTargetMesh) {
  79398. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79399. }
  79400. var bonePos = BoneIKController._tmpVecs[0];
  79401. var zaxis = BoneIKController._tmpVecs[1];
  79402. var xaxis = BoneIKController._tmpVecs[2];
  79403. var yaxis = BoneIKController._tmpVecs[3];
  79404. var upAxis = BoneIKController._tmpVecs[4];
  79405. var _tmpQuat = BoneIKController._tmpQuat;
  79406. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79407. poleTarget.subtractToRef(bonePos, upAxis);
  79408. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79409. upAxis.y = 1;
  79410. }
  79411. else {
  79412. upAxis.normalize();
  79413. }
  79414. target.subtractToRef(bonePos, yaxis);
  79415. yaxis.normalize();
  79416. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79417. zaxis.normalize();
  79418. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79419. xaxis.normalize();
  79420. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79421. var a = this._bone1Length;
  79422. var b = this._bone2Length;
  79423. var c = BABYLON.Vector3.Distance(bonePos, target);
  79424. if (this._maxReach > 0) {
  79425. c = Math.min(this._maxReach, c);
  79426. }
  79427. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79428. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79429. if (acosa > 1) {
  79430. acosa = 1;
  79431. }
  79432. if (acosb > 1) {
  79433. acosb = 1;
  79434. }
  79435. if (acosa < -1) {
  79436. acosa = -1;
  79437. }
  79438. if (acosb < -1) {
  79439. acosb = -1;
  79440. }
  79441. var angA = Math.acos(acosa);
  79442. var angB = Math.acos(acosb);
  79443. var angC = -angA - angB;
  79444. if (this._rightHandedSystem) {
  79445. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79446. mat2.multiplyToRef(mat1, mat1);
  79447. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79448. mat2.multiplyToRef(mat1, mat1);
  79449. }
  79450. else {
  79451. var _tmpVec = BoneIKController._tmpVecs[5];
  79452. _tmpVec.copyFrom(this._bendAxis);
  79453. _tmpVec.x *= -1;
  79454. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79455. mat2.multiplyToRef(mat1, mat1);
  79456. }
  79457. if (this.poleAngle) {
  79458. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79459. mat1.multiplyToRef(mat2, mat1);
  79460. }
  79461. if (this._bone1) {
  79462. if (this.slerpAmount < 1) {
  79463. if (!this._slerping) {
  79464. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79465. }
  79466. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79467. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79468. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79469. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79470. this._slerping = true;
  79471. }
  79472. else {
  79473. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79474. this._bone1Mat.copyFrom(mat1);
  79475. this._slerping = false;
  79476. }
  79477. }
  79478. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79479. this._bone2Ang = angC;
  79480. };
  79481. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79482. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79483. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79484. return BoneIKController;
  79485. }());
  79486. BABYLON.BoneIKController = BoneIKController;
  79487. })(BABYLON || (BABYLON = {}));
  79488. //# sourceMappingURL=babylon.boneIKController.js.map
  79489. var BABYLON;
  79490. (function (BABYLON) {
  79491. /**
  79492. * Class used to make a bone look toward a point in space
  79493. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79494. */
  79495. var BoneLookController = /** @class */ (function () {
  79496. /**
  79497. * Create a BoneLookController
  79498. * @param mesh the mesh that the bone belongs to
  79499. * @param bone the bone that will be looking to the target
  79500. * @param target the target Vector3 to look at
  79501. * @param settings optional settings:
  79502. * * maxYaw: the maximum angle the bone will yaw to
  79503. * * minYaw: the minimum angle the bone will yaw to
  79504. * * maxPitch: the maximum angle the bone will pitch to
  79505. * * minPitch: the minimum angle the bone will yaw to
  79506. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79507. * * upAxis: the up axis of the coordinate system
  79508. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79509. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79510. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79511. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79512. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79513. * * adjustRoll: used to make an adjustment to the roll of the bone
  79514. **/
  79515. function BoneLookController(mesh, bone, target, options) {
  79516. /**
  79517. * The up axis of the coordinate system that is used when the bone is rotated
  79518. */
  79519. this.upAxis = BABYLON.Vector3.Up();
  79520. /**
  79521. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79522. */
  79523. this.upAxisSpace = BABYLON.Space.LOCAL;
  79524. /**
  79525. * Used to make an adjustment to the yaw of the bone
  79526. */
  79527. this.adjustYaw = 0;
  79528. /**
  79529. * Used to make an adjustment to the pitch of the bone
  79530. */
  79531. this.adjustPitch = 0;
  79532. /**
  79533. * Used to make an adjustment to the roll of the bone
  79534. */
  79535. this.adjustRoll = 0;
  79536. /**
  79537. * 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)
  79538. */
  79539. this.slerpAmount = 1;
  79540. this._boneQuat = BABYLON.Quaternion.Identity();
  79541. this._slerping = false;
  79542. this._firstFrameSkipped = false;
  79543. this._fowardAxis = BABYLON.Vector3.Forward();
  79544. this.mesh = mesh;
  79545. this.bone = bone;
  79546. this.target = target;
  79547. if (options) {
  79548. if (options.adjustYaw) {
  79549. this.adjustYaw = options.adjustYaw;
  79550. }
  79551. if (options.adjustPitch) {
  79552. this.adjustPitch = options.adjustPitch;
  79553. }
  79554. if (options.adjustRoll) {
  79555. this.adjustRoll = options.adjustRoll;
  79556. }
  79557. if (options.maxYaw != null) {
  79558. this.maxYaw = options.maxYaw;
  79559. }
  79560. else {
  79561. this.maxYaw = Math.PI;
  79562. }
  79563. if (options.minYaw != null) {
  79564. this.minYaw = options.minYaw;
  79565. }
  79566. else {
  79567. this.minYaw = -Math.PI;
  79568. }
  79569. if (options.maxPitch != null) {
  79570. this.maxPitch = options.maxPitch;
  79571. }
  79572. else {
  79573. this.maxPitch = Math.PI;
  79574. }
  79575. if (options.minPitch != null) {
  79576. this.minPitch = options.minPitch;
  79577. }
  79578. else {
  79579. this.minPitch = -Math.PI;
  79580. }
  79581. if (options.slerpAmount != null) {
  79582. this.slerpAmount = options.slerpAmount;
  79583. }
  79584. if (options.upAxis != null) {
  79585. this.upAxis = options.upAxis;
  79586. }
  79587. if (options.upAxisSpace != null) {
  79588. this.upAxisSpace = options.upAxisSpace;
  79589. }
  79590. if (options.yawAxis != null || options.pitchAxis != null) {
  79591. var newYawAxis = BABYLON.Axis.Y;
  79592. var newPitchAxis = BABYLON.Axis.X;
  79593. if (options.yawAxis != null) {
  79594. newYawAxis = options.yawAxis.clone();
  79595. newYawAxis.normalize();
  79596. }
  79597. if (options.pitchAxis != null) {
  79598. newPitchAxis = options.pitchAxis.clone();
  79599. newPitchAxis.normalize();
  79600. }
  79601. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79602. this._transformYawPitch = BABYLON.Matrix.Identity();
  79603. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79604. this._transformYawPitchInv = this._transformYawPitch.clone();
  79605. this._transformYawPitch.invert();
  79606. }
  79607. }
  79608. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79609. this.upAxisSpace = BABYLON.Space.LOCAL;
  79610. }
  79611. }
  79612. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79613. /**
  79614. * Gets or sets the minimum yaw angle that the bone can look to
  79615. */
  79616. get: function () {
  79617. return this._minYaw;
  79618. },
  79619. set: function (value) {
  79620. this._minYaw = value;
  79621. this._minYawSin = Math.sin(value);
  79622. this._minYawCos = Math.cos(value);
  79623. if (this._maxYaw != null) {
  79624. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79625. this._yawRange = this._maxYaw - this._minYaw;
  79626. }
  79627. },
  79628. enumerable: true,
  79629. configurable: true
  79630. });
  79631. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79632. /**
  79633. * Gets or sets the maximum yaw angle that the bone can look to
  79634. */
  79635. get: function () {
  79636. return this._maxYaw;
  79637. },
  79638. set: function (value) {
  79639. this._maxYaw = value;
  79640. this._maxYawSin = Math.sin(value);
  79641. this._maxYawCos = Math.cos(value);
  79642. if (this._minYaw != null) {
  79643. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79644. this._yawRange = this._maxYaw - this._minYaw;
  79645. }
  79646. },
  79647. enumerable: true,
  79648. configurable: true
  79649. });
  79650. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79651. /**
  79652. * Gets or sets the minimum pitch angle that the bone can look to
  79653. */
  79654. get: function () {
  79655. return this._minPitch;
  79656. },
  79657. set: function (value) {
  79658. this._minPitch = value;
  79659. this._minPitchTan = Math.tan(value);
  79660. },
  79661. enumerable: true,
  79662. configurable: true
  79663. });
  79664. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79665. /**
  79666. * Gets or sets the maximum pitch angle that the bone can look to
  79667. */
  79668. get: function () {
  79669. return this._maxPitch;
  79670. },
  79671. set: function (value) {
  79672. this._maxPitch = value;
  79673. this._maxPitchTan = Math.tan(value);
  79674. },
  79675. enumerable: true,
  79676. configurable: true
  79677. });
  79678. /**
  79679. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79680. */
  79681. BoneLookController.prototype.update = function () {
  79682. //skip the first frame when slerping so that the mesh rotation is correct
  79683. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79684. this._firstFrameSkipped = true;
  79685. return;
  79686. }
  79687. var bone = this.bone;
  79688. var bonePos = BoneLookController._tmpVecs[0];
  79689. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79690. var target = this.target;
  79691. var _tmpMat1 = BoneLookController._tmpMats[0];
  79692. var _tmpMat2 = BoneLookController._tmpMats[1];
  79693. var mesh = this.mesh;
  79694. var parentBone = bone.getParent();
  79695. var upAxis = BoneLookController._tmpVecs[1];
  79696. upAxis.copyFrom(this.upAxis);
  79697. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79698. if (this._transformYawPitch) {
  79699. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79700. }
  79701. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79702. }
  79703. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79704. mesh.getDirectionToRef(upAxis, upAxis);
  79705. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79706. upAxis.normalize();
  79707. }
  79708. }
  79709. var checkYaw = false;
  79710. var checkPitch = false;
  79711. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79712. checkYaw = true;
  79713. }
  79714. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79715. checkPitch = true;
  79716. }
  79717. if (checkYaw || checkPitch) {
  79718. var spaceMat = BoneLookController._tmpMats[2];
  79719. var spaceMatInv = BoneLookController._tmpMats[3];
  79720. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79721. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79722. }
  79723. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79724. spaceMat.copyFrom(mesh.getWorldMatrix());
  79725. }
  79726. else {
  79727. var forwardAxis = BoneLookController._tmpVecs[2];
  79728. forwardAxis.copyFrom(this._fowardAxis);
  79729. if (this._transformYawPitch) {
  79730. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79731. }
  79732. if (parentBone) {
  79733. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79734. }
  79735. else {
  79736. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79737. }
  79738. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79739. rightAxis.normalize();
  79740. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79741. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79742. }
  79743. spaceMat.invertToRef(spaceMatInv);
  79744. var xzlen = null;
  79745. if (checkPitch) {
  79746. var localTarget = BoneLookController._tmpVecs[3];
  79747. target.subtractToRef(bonePos, localTarget);
  79748. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79749. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79750. var pitch = Math.atan2(localTarget.y, xzlen);
  79751. var newPitch = pitch;
  79752. if (pitch > this._maxPitch) {
  79753. localTarget.y = this._maxPitchTan * xzlen;
  79754. newPitch = this._maxPitch;
  79755. }
  79756. else if (pitch < this._minPitch) {
  79757. localTarget.y = this._minPitchTan * xzlen;
  79758. newPitch = this._minPitch;
  79759. }
  79760. if (pitch != newPitch) {
  79761. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79762. localTarget.addInPlace(bonePos);
  79763. target = localTarget;
  79764. }
  79765. }
  79766. if (checkYaw) {
  79767. var localTarget = BoneLookController._tmpVecs[4];
  79768. target.subtractToRef(bonePos, localTarget);
  79769. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79770. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79771. var newYaw = yaw;
  79772. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79773. if (xzlen == null) {
  79774. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79775. }
  79776. if (this._yawRange > Math.PI) {
  79777. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79778. localTarget.z = this._maxYawCos * xzlen;
  79779. localTarget.x = this._maxYawSin * xzlen;
  79780. newYaw = this._maxYaw;
  79781. }
  79782. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79783. localTarget.z = this._minYawCos * xzlen;
  79784. localTarget.x = this._minYawSin * xzlen;
  79785. newYaw = this._minYaw;
  79786. }
  79787. }
  79788. else {
  79789. if (yaw > this._maxYaw) {
  79790. localTarget.z = this._maxYawCos * xzlen;
  79791. localTarget.x = this._maxYawSin * xzlen;
  79792. newYaw = this._maxYaw;
  79793. }
  79794. else if (yaw < this._minYaw) {
  79795. localTarget.z = this._minYawCos * xzlen;
  79796. localTarget.x = this._minYawSin * xzlen;
  79797. newYaw = this._minYaw;
  79798. }
  79799. }
  79800. }
  79801. if (this._slerping && this._yawRange > Math.PI) {
  79802. //are we going to be crossing into the min/max region?
  79803. var boneFwd = BoneLookController._tmpVecs[8];
  79804. boneFwd.copyFrom(BABYLON.Axis.Z);
  79805. if (this._transformYawPitch) {
  79806. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79807. }
  79808. var boneRotMat = BoneLookController._tmpMats[4];
  79809. this._boneQuat.toRotationMatrix(boneRotMat);
  79810. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79811. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79812. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79813. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79814. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79815. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79816. if (angBtwTar > angBtwMidYaw) {
  79817. if (xzlen == null) {
  79818. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79819. }
  79820. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79821. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79822. if (angBtwMin < angBtwMax) {
  79823. newYaw = boneYaw + Math.PI * .75;
  79824. localTarget.z = Math.cos(newYaw) * xzlen;
  79825. localTarget.x = Math.sin(newYaw) * xzlen;
  79826. }
  79827. else {
  79828. newYaw = boneYaw - Math.PI * .75;
  79829. localTarget.z = Math.cos(newYaw) * xzlen;
  79830. localTarget.x = Math.sin(newYaw) * xzlen;
  79831. }
  79832. }
  79833. }
  79834. if (yaw != newYaw) {
  79835. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79836. localTarget.addInPlace(bonePos);
  79837. target = localTarget;
  79838. }
  79839. }
  79840. }
  79841. var zaxis = BoneLookController._tmpVecs[5];
  79842. var xaxis = BoneLookController._tmpVecs[6];
  79843. var yaxis = BoneLookController._tmpVecs[7];
  79844. var _tmpQuat = BoneLookController._tmpQuat;
  79845. target.subtractToRef(bonePos, zaxis);
  79846. zaxis.normalize();
  79847. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79848. xaxis.normalize();
  79849. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79850. yaxis.normalize();
  79851. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79852. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79853. return;
  79854. }
  79855. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79856. return;
  79857. }
  79858. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79859. return;
  79860. }
  79861. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79862. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79863. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79864. }
  79865. if (this.slerpAmount < 1) {
  79866. if (!this._slerping) {
  79867. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79868. }
  79869. if (this._transformYawPitch) {
  79870. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79871. }
  79872. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79873. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79874. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79875. this._slerping = true;
  79876. }
  79877. else {
  79878. if (this._transformYawPitch) {
  79879. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79880. }
  79881. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79882. this._slerping = false;
  79883. }
  79884. };
  79885. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79886. var angDiff = ang2 - ang1;
  79887. angDiff %= Math.PI * 2;
  79888. if (angDiff > Math.PI) {
  79889. angDiff -= Math.PI * 2;
  79890. }
  79891. else if (angDiff < -Math.PI) {
  79892. angDiff += Math.PI * 2;
  79893. }
  79894. return angDiff;
  79895. };
  79896. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79897. ang1 %= (2 * Math.PI);
  79898. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79899. ang2 %= (2 * Math.PI);
  79900. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79901. var ab = 0;
  79902. if (ang1 < ang2) {
  79903. ab = ang2 - ang1;
  79904. }
  79905. else {
  79906. ab = ang1 - ang2;
  79907. }
  79908. if (ab > Math.PI) {
  79909. ab = Math.PI * 2 - ab;
  79910. }
  79911. return ab;
  79912. };
  79913. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79914. ang %= (2 * Math.PI);
  79915. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79916. ang1 %= (2 * Math.PI);
  79917. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79918. ang2 %= (2 * Math.PI);
  79919. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79920. if (ang1 < ang2) {
  79921. if (ang > ang1 && ang < ang2) {
  79922. return true;
  79923. }
  79924. }
  79925. else {
  79926. if (ang > ang2 && ang < ang1) {
  79927. return true;
  79928. }
  79929. }
  79930. return false;
  79931. };
  79932. 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()];
  79933. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79934. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79935. return BoneLookController;
  79936. }());
  79937. BABYLON.BoneLookController = BoneLookController;
  79938. })(BABYLON || (BABYLON = {}));
  79939. //# sourceMappingURL=babylon.boneLookController.js.map
  79940. var BABYLON;
  79941. (function (BABYLON) {
  79942. /**
  79943. * Class used to handle skinning animations
  79944. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79945. */
  79946. var Skeleton = /** @class */ (function () {
  79947. /**
  79948. * Creates a new skeleton
  79949. * @param name defines the skeleton name
  79950. * @param id defines the skeleton Id
  79951. * @param scene defines the hosting scene
  79952. */
  79953. function Skeleton(
  79954. /** defines the skeleton name */
  79955. name,
  79956. /** defines the skeleton Id */
  79957. id, scene) {
  79958. this.name = name;
  79959. this.id = id;
  79960. /**
  79961. * Gets the list of child bones
  79962. */
  79963. this.bones = new Array();
  79964. /**
  79965. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79966. */
  79967. this.needInitialSkinMatrix = false;
  79968. this._isDirty = true;
  79969. this._meshesWithPoseMatrix = new Array();
  79970. this._identity = BABYLON.Matrix.Identity();
  79971. this._ranges = {};
  79972. this._lastAbsoluteTransformsUpdateId = -1;
  79973. /**
  79974. * Specifies if the skeleton should be serialized
  79975. */
  79976. this.doNotSerialize = false;
  79977. this._animationPropertiesOverride = null;
  79978. // Events
  79979. /**
  79980. * An observable triggered before computing the skeleton's matrices
  79981. */
  79982. this.onBeforeComputeObservable = new BABYLON.Observable();
  79983. this.bones = [];
  79984. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79985. scene.skeletons.push(this);
  79986. //make sure it will recalculate the matrix next time prepare is called.
  79987. this._isDirty = true;
  79988. }
  79989. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79990. /**
  79991. * Gets or sets the animation properties override
  79992. */
  79993. get: function () {
  79994. if (!this._animationPropertiesOverride) {
  79995. return this._scene.animationPropertiesOverride;
  79996. }
  79997. return this._animationPropertiesOverride;
  79998. },
  79999. set: function (value) {
  80000. this._animationPropertiesOverride = value;
  80001. },
  80002. enumerable: true,
  80003. configurable: true
  80004. });
  80005. // Members
  80006. /**
  80007. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80008. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80009. * @returns a Float32Array containing matrices data
  80010. */
  80011. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80012. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80013. return mesh._bonesTransformMatrices;
  80014. }
  80015. if (!this._transformMatrices) {
  80016. this.prepare();
  80017. }
  80018. return this._transformMatrices;
  80019. };
  80020. /**
  80021. * Gets the current hosting scene
  80022. * @returns a scene object
  80023. */
  80024. Skeleton.prototype.getScene = function () {
  80025. return this._scene;
  80026. };
  80027. // Methods
  80028. /**
  80029. * Gets a string representing the current skeleton data
  80030. * @param fullDetails defines a boolean indicating if we want a verbose version
  80031. * @returns a string representing the current skeleton data
  80032. */
  80033. Skeleton.prototype.toString = function (fullDetails) {
  80034. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80035. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80036. if (fullDetails) {
  80037. ret += ", Ranges: {";
  80038. var first = true;
  80039. for (var name_1 in this._ranges) {
  80040. if (first) {
  80041. ret += ", ";
  80042. first = false;
  80043. }
  80044. ret += name_1;
  80045. }
  80046. ret += "}";
  80047. }
  80048. return ret;
  80049. };
  80050. /**
  80051. * Get bone's index searching by name
  80052. * @param name defines bone's name to search for
  80053. * @return the indice of the bone. Returns -1 if not found
  80054. */
  80055. Skeleton.prototype.getBoneIndexByName = function (name) {
  80056. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80057. if (this.bones[boneIndex].name === name) {
  80058. return boneIndex;
  80059. }
  80060. }
  80061. return -1;
  80062. };
  80063. /**
  80064. * Creater a new animation range
  80065. * @param name defines the name of the range
  80066. * @param from defines the start key
  80067. * @param to defines the end key
  80068. */
  80069. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80070. // check name not already in use
  80071. if (!this._ranges[name]) {
  80072. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80073. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80074. if (this.bones[i].animations[0]) {
  80075. this.bones[i].animations[0].createRange(name, from, to);
  80076. }
  80077. }
  80078. }
  80079. };
  80080. /**
  80081. * Delete a specific animation range
  80082. * @param name defines the name of the range
  80083. * @param deleteFrames defines if frames must be removed as well
  80084. */
  80085. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80086. if (deleteFrames === void 0) { deleteFrames = true; }
  80087. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80088. if (this.bones[i].animations[0]) {
  80089. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80090. }
  80091. }
  80092. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80093. };
  80094. /**
  80095. * Gets a specific animation range
  80096. * @param name defines the name of the range to look for
  80097. * @returns the requested animation range or null if not found
  80098. */
  80099. Skeleton.prototype.getAnimationRange = function (name) {
  80100. return this._ranges[name];
  80101. };
  80102. /**
  80103. * Gets the list of all animation ranges defined on this skeleton
  80104. * @returns an array
  80105. */
  80106. Skeleton.prototype.getAnimationRanges = function () {
  80107. var animationRanges = [];
  80108. var name;
  80109. var i = 0;
  80110. for (name in this._ranges) {
  80111. animationRanges[i] = this._ranges[name];
  80112. i++;
  80113. }
  80114. return animationRanges;
  80115. };
  80116. /**
  80117. * Copy animation range from a source skeleton.
  80118. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80119. * @param source defines the source skeleton
  80120. * @param name defines the name of the range to copy
  80121. * @param rescaleAsRequired defines if rescaling must be applied if required
  80122. * @returns true if operation was successful
  80123. */
  80124. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80125. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80126. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80127. return false;
  80128. }
  80129. var ret = true;
  80130. var frameOffset = this._getHighestAnimationFrame() + 1;
  80131. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80132. var boneDict = {};
  80133. var sourceBones = source.bones;
  80134. var nBones;
  80135. var i;
  80136. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80137. boneDict[sourceBones[i].name] = sourceBones[i];
  80138. }
  80139. if (this.bones.length !== sourceBones.length) {
  80140. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80141. ret = false;
  80142. }
  80143. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80144. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80145. var boneName = this.bones[i].name;
  80146. var sourceBone = boneDict[boneName];
  80147. if (sourceBone) {
  80148. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80149. }
  80150. else {
  80151. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80152. ret = false;
  80153. }
  80154. }
  80155. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80156. var range = source.getAnimationRange(name);
  80157. if (range) {
  80158. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80159. }
  80160. return ret;
  80161. };
  80162. /**
  80163. * Forces the skeleton to go to rest pose
  80164. */
  80165. Skeleton.prototype.returnToRest = function () {
  80166. for (var index = 0; index < this.bones.length; index++) {
  80167. this.bones[index].returnToRest();
  80168. }
  80169. };
  80170. Skeleton.prototype._getHighestAnimationFrame = function () {
  80171. var ret = 0;
  80172. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80173. if (this.bones[i].animations[0]) {
  80174. var highest = this.bones[i].animations[0].getHighestFrame();
  80175. if (ret < highest) {
  80176. ret = highest;
  80177. }
  80178. }
  80179. }
  80180. return ret;
  80181. };
  80182. /**
  80183. * Begin a specific animation range
  80184. * @param name defines the name of the range to start
  80185. * @param loop defines if looping must be turned on (false by default)
  80186. * @param speedRatio defines the speed ratio to apply (1 by default)
  80187. * @param onAnimationEnd defines a callback which will be called when animation will end
  80188. * @returns a new animatable
  80189. */
  80190. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80191. var range = this.getAnimationRange(name);
  80192. if (!range) {
  80193. return null;
  80194. }
  80195. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80196. };
  80197. /** @hidden */
  80198. Skeleton.prototype._markAsDirty = function () {
  80199. this._isDirty = true;
  80200. };
  80201. /** @hidden */
  80202. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80203. this._meshesWithPoseMatrix.push(mesh);
  80204. };
  80205. /** @hidden */
  80206. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80207. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80208. if (index > -1) {
  80209. this._meshesWithPoseMatrix.splice(index, 1);
  80210. }
  80211. };
  80212. /** @hidden */
  80213. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80214. this.onBeforeComputeObservable.notifyObservers(this);
  80215. for (var index = 0; index < this.bones.length; index++) {
  80216. var bone = this.bones[index];
  80217. var parentBone = bone.getParent();
  80218. if (parentBone) {
  80219. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80220. }
  80221. else {
  80222. if (initialSkinMatrix) {
  80223. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80224. }
  80225. else {
  80226. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80227. }
  80228. }
  80229. if (bone._index !== -1) {
  80230. var mappedIndex = bone._index === null ? index : bone._index;
  80231. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80232. }
  80233. }
  80234. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80235. };
  80236. /**
  80237. * Build all resources required to render a skeleton
  80238. */
  80239. Skeleton.prototype.prepare = function () {
  80240. if (!this._isDirty) {
  80241. return;
  80242. }
  80243. if (this.needInitialSkinMatrix) {
  80244. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80245. var mesh = this._meshesWithPoseMatrix[index];
  80246. var poseMatrix = mesh.getPoseMatrix();
  80247. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80248. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80249. }
  80250. if (this._synchronizedWithMesh !== mesh) {
  80251. this._synchronizedWithMesh = mesh;
  80252. // Prepare bones
  80253. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80254. var bone = this.bones[boneIndex];
  80255. if (!bone.getParent()) {
  80256. var matrix = bone.getBaseMatrix();
  80257. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80258. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80259. }
  80260. }
  80261. }
  80262. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80263. }
  80264. }
  80265. else {
  80266. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80267. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80268. }
  80269. this._computeTransformMatrices(this._transformMatrices, null);
  80270. }
  80271. this._isDirty = false;
  80272. this._scene._activeBones.addCount(this.bones.length, false);
  80273. };
  80274. /**
  80275. * Gets the list of animatables currently running for this skeleton
  80276. * @returns an array of animatables
  80277. */
  80278. Skeleton.prototype.getAnimatables = function () {
  80279. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80280. this._animatables = [];
  80281. for (var index = 0; index < this.bones.length; index++) {
  80282. this._animatables.push(this.bones[index]);
  80283. }
  80284. }
  80285. return this._animatables;
  80286. };
  80287. /**
  80288. * Clone the current skeleton
  80289. * @param name defines the name of the new skeleton
  80290. * @param id defines the id of the enw skeleton
  80291. * @returns the new skeleton
  80292. */
  80293. Skeleton.prototype.clone = function (name, id) {
  80294. var result = new Skeleton(name, id || name, this._scene);
  80295. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80296. for (var index = 0; index < this.bones.length; index++) {
  80297. var source = this.bones[index];
  80298. var parentBone = null;
  80299. var parent_1 = source.getParent();
  80300. if (parent_1) {
  80301. var parentIndex = this.bones.indexOf(parent_1);
  80302. parentBone = result.bones[parentIndex];
  80303. }
  80304. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80305. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80306. }
  80307. if (this._ranges) {
  80308. result._ranges = {};
  80309. for (var rangeName in this._ranges) {
  80310. var range = this._ranges[rangeName];
  80311. if (range) {
  80312. result._ranges[rangeName] = range.clone();
  80313. }
  80314. }
  80315. }
  80316. this._isDirty = true;
  80317. return result;
  80318. };
  80319. /**
  80320. * Enable animation blending for this skeleton
  80321. * @param blendingSpeed defines the blending speed to apply
  80322. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80323. */
  80324. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80325. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80326. this.bones.forEach(function (bone) {
  80327. bone.animations.forEach(function (animation) {
  80328. animation.enableBlending = true;
  80329. animation.blendingSpeed = blendingSpeed;
  80330. });
  80331. });
  80332. };
  80333. /**
  80334. * Releases all resources associated with the current skeleton
  80335. */
  80336. Skeleton.prototype.dispose = function () {
  80337. this._meshesWithPoseMatrix = [];
  80338. // Animations
  80339. this.getScene().stopAnimation(this);
  80340. // Remove from scene
  80341. this.getScene().removeSkeleton(this);
  80342. };
  80343. /**
  80344. * Serialize the skeleton in a JSON object
  80345. * @returns a JSON object
  80346. */
  80347. Skeleton.prototype.serialize = function () {
  80348. var serializationObject = {};
  80349. serializationObject.name = this.name;
  80350. serializationObject.id = this.id;
  80351. if (this.dimensionsAtRest) {
  80352. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80353. }
  80354. serializationObject.bones = [];
  80355. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80356. for (var index = 0; index < this.bones.length; index++) {
  80357. var bone = this.bones[index];
  80358. var parent_2 = bone.getParent();
  80359. var serializedBone = {
  80360. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80361. name: bone.name,
  80362. matrix: bone.getBaseMatrix().toArray(),
  80363. rest: bone.getRestPose().toArray()
  80364. };
  80365. serializationObject.bones.push(serializedBone);
  80366. if (bone.length) {
  80367. serializedBone.length = bone.length;
  80368. }
  80369. if (bone.metadata) {
  80370. serializedBone.metadata = bone.metadata;
  80371. }
  80372. if (bone.animations && bone.animations.length > 0) {
  80373. serializedBone.animation = bone.animations[0].serialize();
  80374. }
  80375. serializationObject.ranges = [];
  80376. for (var name in this._ranges) {
  80377. var source = this._ranges[name];
  80378. if (!source) {
  80379. continue;
  80380. }
  80381. var range = {};
  80382. range.name = name;
  80383. range.from = source.from;
  80384. range.to = source.to;
  80385. serializationObject.ranges.push(range);
  80386. }
  80387. }
  80388. return serializationObject;
  80389. };
  80390. /**
  80391. * Creates a new skeleton from serialized data
  80392. * @param parsedSkeleton defines the serialized data
  80393. * @param scene defines the hosting scene
  80394. * @returns a new skeleton
  80395. */
  80396. Skeleton.Parse = function (parsedSkeleton, scene) {
  80397. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80398. if (parsedSkeleton.dimensionsAtRest) {
  80399. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80400. }
  80401. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80402. var index;
  80403. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80404. var parsedBone = parsedSkeleton.bones[index];
  80405. var parentBone = null;
  80406. if (parsedBone.parentBoneIndex > -1) {
  80407. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80408. }
  80409. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80410. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80411. if (parsedBone.length) {
  80412. bone.length = parsedBone.length;
  80413. }
  80414. if (parsedBone.metadata) {
  80415. bone.metadata = parsedBone.metadata;
  80416. }
  80417. if (parsedBone.animation) {
  80418. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80419. }
  80420. }
  80421. // placed after bones, so createAnimationRange can cascade down
  80422. if (parsedSkeleton.ranges) {
  80423. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80424. var data = parsedSkeleton.ranges[index];
  80425. skeleton.createAnimationRange(data.name, data.from, data.to);
  80426. }
  80427. }
  80428. return skeleton;
  80429. };
  80430. /**
  80431. * Compute all node absolute transforms
  80432. * @param forceUpdate defines if computation must be done even if cache is up to date
  80433. */
  80434. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80435. if (forceUpdate === void 0) { forceUpdate = false; }
  80436. var renderId = this._scene.getRenderId();
  80437. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80438. this.bones[0].computeAbsoluteTransforms();
  80439. this._lastAbsoluteTransformsUpdateId = renderId;
  80440. }
  80441. };
  80442. /**
  80443. * Gets the root pose matrix
  80444. * @returns a matrix
  80445. */
  80446. Skeleton.prototype.getPoseMatrix = function () {
  80447. var poseMatrix = null;
  80448. if (this._meshesWithPoseMatrix.length > 0) {
  80449. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80450. }
  80451. return poseMatrix;
  80452. };
  80453. /**
  80454. * Sorts bones per internal index
  80455. */
  80456. Skeleton.prototype.sortBones = function () {
  80457. var bones = new Array();
  80458. var visited = new Array(this.bones.length);
  80459. for (var index = 0; index < this.bones.length; index++) {
  80460. this._sortBones(index, bones, visited);
  80461. }
  80462. this.bones = bones;
  80463. };
  80464. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80465. if (visited[index]) {
  80466. return;
  80467. }
  80468. visited[index] = true;
  80469. var bone = this.bones[index];
  80470. if (bone._index === undefined) {
  80471. bone._index = index;
  80472. }
  80473. var parentBone = bone.getParent();
  80474. if (parentBone) {
  80475. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80476. }
  80477. bones.push(bone);
  80478. };
  80479. return Skeleton;
  80480. }());
  80481. BABYLON.Skeleton = Skeleton;
  80482. })(BABYLON || (BABYLON = {}));
  80483. //# sourceMappingURL=babylon.skeleton.js.map
  80484. var BABYLON;
  80485. (function (BABYLON) {
  80486. var SphericalPolynomial = /** @class */ (function () {
  80487. function SphericalPolynomial() {
  80488. this.x = BABYLON.Vector3.Zero();
  80489. this.y = BABYLON.Vector3.Zero();
  80490. this.z = BABYLON.Vector3.Zero();
  80491. this.xx = BABYLON.Vector3.Zero();
  80492. this.yy = BABYLON.Vector3.Zero();
  80493. this.zz = BABYLON.Vector3.Zero();
  80494. this.xy = BABYLON.Vector3.Zero();
  80495. this.yz = BABYLON.Vector3.Zero();
  80496. this.zx = BABYLON.Vector3.Zero();
  80497. }
  80498. SphericalPolynomial.prototype.addAmbient = function (color) {
  80499. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80500. this.xx = this.xx.add(colorVector);
  80501. this.yy = this.yy.add(colorVector);
  80502. this.zz = this.zz.add(colorVector);
  80503. };
  80504. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80505. var result = new SphericalPolynomial();
  80506. result.x = harmonics.L11.scale(1.02333);
  80507. result.y = harmonics.L1_1.scale(1.02333);
  80508. result.z = harmonics.L10.scale(1.02333);
  80509. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80510. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80511. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80512. result.yz = harmonics.L2_1.scale(0.858086);
  80513. result.zx = harmonics.L21.scale(0.858086);
  80514. result.xy = harmonics.L2_2.scale(0.858086);
  80515. result.scale(1.0 / Math.PI);
  80516. return result;
  80517. };
  80518. SphericalPolynomial.prototype.scale = function (scale) {
  80519. this.x = this.x.scale(scale);
  80520. this.y = this.y.scale(scale);
  80521. this.z = this.z.scale(scale);
  80522. this.xx = this.xx.scale(scale);
  80523. this.yy = this.yy.scale(scale);
  80524. this.zz = this.zz.scale(scale);
  80525. this.yz = this.yz.scale(scale);
  80526. this.zx = this.zx.scale(scale);
  80527. this.xy = this.xy.scale(scale);
  80528. };
  80529. return SphericalPolynomial;
  80530. }());
  80531. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80532. var SphericalHarmonics = /** @class */ (function () {
  80533. function SphericalHarmonics() {
  80534. this.L00 = BABYLON.Vector3.Zero();
  80535. this.L1_1 = BABYLON.Vector3.Zero();
  80536. this.L10 = BABYLON.Vector3.Zero();
  80537. this.L11 = BABYLON.Vector3.Zero();
  80538. this.L2_2 = BABYLON.Vector3.Zero();
  80539. this.L2_1 = BABYLON.Vector3.Zero();
  80540. this.L20 = BABYLON.Vector3.Zero();
  80541. this.L21 = BABYLON.Vector3.Zero();
  80542. this.L22 = BABYLON.Vector3.Zero();
  80543. }
  80544. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80545. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80546. var c = colorVector.scale(deltaSolidAngle);
  80547. this.L00 = this.L00.add(c.scale(0.282095));
  80548. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80549. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80550. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80551. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80552. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80553. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80554. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80555. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80556. };
  80557. SphericalHarmonics.prototype.scale = function (scale) {
  80558. this.L00 = this.L00.scale(scale);
  80559. this.L1_1 = this.L1_1.scale(scale);
  80560. this.L10 = this.L10.scale(scale);
  80561. this.L11 = this.L11.scale(scale);
  80562. this.L2_2 = this.L2_2.scale(scale);
  80563. this.L2_1 = this.L2_1.scale(scale);
  80564. this.L20 = this.L20.scale(scale);
  80565. this.L21 = this.L21.scale(scale);
  80566. this.L22 = this.L22.scale(scale);
  80567. };
  80568. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80569. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80570. //
  80571. // E_lm = A_l * L_lm
  80572. //
  80573. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80574. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80575. // the scaling factors are given in equation 9.
  80576. // Constant (Band 0)
  80577. this.L00 = this.L00.scale(3.141593);
  80578. // Linear (Band 1)
  80579. this.L1_1 = this.L1_1.scale(2.094395);
  80580. this.L10 = this.L10.scale(2.094395);
  80581. this.L11 = this.L11.scale(2.094395);
  80582. // Quadratic (Band 2)
  80583. this.L2_2 = this.L2_2.scale(0.785398);
  80584. this.L2_1 = this.L2_1.scale(0.785398);
  80585. this.L20 = this.L20.scale(0.785398);
  80586. this.L21 = this.L21.scale(0.785398);
  80587. this.L22 = this.L22.scale(0.785398);
  80588. };
  80589. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80590. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80591. // L = (1/pi) * E * rho
  80592. //
  80593. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80594. this.scale(1.0 / Math.PI);
  80595. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80596. // (The pixel shader must apply albedo after texture fetches, etc).
  80597. };
  80598. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80599. var result = new SphericalHarmonics();
  80600. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80601. result.L1_1 = polynomial.y.scale(0.977204);
  80602. result.L10 = polynomial.z.scale(0.977204);
  80603. result.L11 = polynomial.x.scale(0.977204);
  80604. result.L2_2 = polynomial.xy.scale(1.16538);
  80605. result.L2_1 = polynomial.yz.scale(1.16538);
  80606. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80607. result.L21 = polynomial.zx.scale(1.16538);
  80608. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80609. result.scale(Math.PI);
  80610. return result;
  80611. };
  80612. return SphericalHarmonics;
  80613. }());
  80614. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80615. })(BABYLON || (BABYLON = {}));
  80616. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80617. var BABYLON;
  80618. (function (BABYLON) {
  80619. var FileFaceOrientation = /** @class */ (function () {
  80620. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80621. this.name = name;
  80622. this.worldAxisForNormal = worldAxisForNormal;
  80623. this.worldAxisForFileX = worldAxisForFileX;
  80624. this.worldAxisForFileY = worldAxisForFileY;
  80625. }
  80626. return FileFaceOrientation;
  80627. }());
  80628. ;
  80629. /**
  80630. * Helper class dealing with the extraction of spherical polynomial dataArray
  80631. * from a cube map.
  80632. */
  80633. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80634. function CubeMapToSphericalPolynomialTools() {
  80635. }
  80636. /**
  80637. * Converts a texture to the according Spherical Polynomial data.
  80638. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80639. *
  80640. * @param texture The texture to extract the information from.
  80641. * @return The Spherical Polynomial data.
  80642. */
  80643. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80644. if (!texture.isCube) {
  80645. // Only supports cube Textures currently.
  80646. return null;
  80647. }
  80648. var size = texture.getSize().width;
  80649. var right = texture.readPixels(0);
  80650. var left = texture.readPixels(1);
  80651. var up;
  80652. var down;
  80653. if (texture.isRenderTarget) {
  80654. up = texture.readPixels(3);
  80655. down = texture.readPixels(2);
  80656. }
  80657. else {
  80658. up = texture.readPixels(2);
  80659. down = texture.readPixels(3);
  80660. }
  80661. var front = texture.readPixels(4);
  80662. var back = texture.readPixels(5);
  80663. var gammaSpace = texture.gammaSpace;
  80664. // Always read as RGBA.
  80665. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80666. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80667. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80668. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80669. }
  80670. var cubeInfo = {
  80671. size: size,
  80672. right: right,
  80673. left: left,
  80674. up: up,
  80675. down: down,
  80676. front: front,
  80677. back: back,
  80678. format: format,
  80679. type: type,
  80680. gammaSpace: gammaSpace,
  80681. };
  80682. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80683. };
  80684. /**
  80685. * Converts a cubemap to the according Spherical Polynomial data.
  80686. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80687. *
  80688. * @param cubeInfo The Cube map to extract the information from.
  80689. * @return The Spherical Polynomial data.
  80690. */
  80691. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80692. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80693. var totalSolidAngle = 0.0;
  80694. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80695. var du = 2.0 / cubeInfo.size;
  80696. var dv = du;
  80697. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80698. var minUV = du * 0.5 - 1.0;
  80699. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80700. var fileFace = this.FileFaces[faceIndex];
  80701. var dataArray = cubeInfo[fileFace.name];
  80702. var v = minUV;
  80703. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80704. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80705. // Because SP is still linear, so summation is fine in that basis.
  80706. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80707. for (var y = 0; y < cubeInfo.size; y++) {
  80708. var u = minUV;
  80709. for (var x = 0; x < cubeInfo.size; x++) {
  80710. // World direction (not normalised)
  80711. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80712. worldDirection.normalize();
  80713. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80714. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80715. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80716. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80717. // Handle Integer types.
  80718. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80719. r /= 255;
  80720. g /= 255;
  80721. b /= 255;
  80722. }
  80723. // Handle Gamma space textures.
  80724. if (cubeInfo.gammaSpace) {
  80725. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80726. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80727. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80728. }
  80729. var color = new BABYLON.Color3(r, g, b);
  80730. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80731. totalSolidAngle += deltaSolidAngle;
  80732. u += du;
  80733. }
  80734. v += dv;
  80735. }
  80736. }
  80737. // Solid angle for entire sphere is 4*pi
  80738. var sphereSolidAngle = 4.0 * Math.PI;
  80739. // Adjust the solid angle to allow for how many faces we processed.
  80740. var facesProcessed = 6.0;
  80741. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80742. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80743. // This is needed because the numerical integration over the cube uses a
  80744. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80745. // and also to compensate for accumulative error due to float precision in the summation.
  80746. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80747. sphericalHarmonics.scale(correctionFactor);
  80748. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80749. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80750. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80751. };
  80752. CubeMapToSphericalPolynomialTools.FileFaces = [
  80753. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80754. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80755. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80756. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80757. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80758. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80759. ];
  80760. return CubeMapToSphericalPolynomialTools;
  80761. }());
  80762. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80763. })(BABYLON || (BABYLON = {}));
  80764. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80765. var BABYLON;
  80766. (function (BABYLON) {
  80767. /**
  80768. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80769. */
  80770. var PanoramaToCubeMapTools = /** @class */ (function () {
  80771. function PanoramaToCubeMapTools() {
  80772. }
  80773. /**
  80774. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80775. *
  80776. * @param float32Array The source data.
  80777. * @param inputWidth The width of the input panorama.
  80778. * @param inputhHeight The height of the input panorama.
  80779. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80780. * @return The cubemap data
  80781. */
  80782. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80783. if (!float32Array) {
  80784. throw "ConvertPanoramaToCubemap: input cannot be null";
  80785. }
  80786. if (float32Array.length != inputWidth * inputHeight * 3) {
  80787. throw "ConvertPanoramaToCubemap: input size is wrong";
  80788. }
  80789. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80790. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80791. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80792. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80793. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80794. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80795. return {
  80796. front: textureFront,
  80797. back: textureBack,
  80798. left: textureLeft,
  80799. right: textureRight,
  80800. up: textureUp,
  80801. down: textureDown,
  80802. size: size,
  80803. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80804. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80805. gammaSpace: false,
  80806. };
  80807. };
  80808. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80809. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80810. var textureArray = new Float32Array(buffer);
  80811. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80812. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80813. var dy = 1 / texSize;
  80814. var fy = 0;
  80815. for (var y = 0; y < texSize; y++) {
  80816. var xv1 = faceData[0];
  80817. var xv2 = faceData[2];
  80818. for (var x = 0; x < texSize; x++) {
  80819. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80820. v.normalize();
  80821. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80822. // 3 channels per pixels
  80823. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80824. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80825. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80826. xv1 = xv1.add(rotDX1);
  80827. xv2 = xv2.add(rotDX2);
  80828. }
  80829. fy += dy;
  80830. }
  80831. return textureArray;
  80832. };
  80833. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80834. var theta = Math.atan2(vDir.z, vDir.x);
  80835. var phi = Math.acos(vDir.y);
  80836. while (theta < -Math.PI)
  80837. theta += 2 * Math.PI;
  80838. while (theta > Math.PI)
  80839. theta -= 2 * Math.PI;
  80840. var dx = theta / Math.PI;
  80841. var dy = phi / Math.PI;
  80842. // recenter.
  80843. dx = dx * 0.5 + 0.5;
  80844. var px = Math.round(dx * inputWidth);
  80845. if (px < 0)
  80846. px = 0;
  80847. else if (px >= inputWidth)
  80848. px = inputWidth - 1;
  80849. var py = Math.round(dy * inputHeight);
  80850. if (py < 0)
  80851. py = 0;
  80852. else if (py >= inputHeight)
  80853. py = inputHeight - 1;
  80854. var inputY = (inputHeight - py - 1);
  80855. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80856. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80857. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80858. return {
  80859. r: r,
  80860. g: g,
  80861. b: b
  80862. };
  80863. };
  80864. PanoramaToCubeMapTools.FACE_FRONT = [
  80865. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80866. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80867. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80868. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80869. ];
  80870. PanoramaToCubeMapTools.FACE_BACK = [
  80871. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80872. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80873. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80874. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80875. ];
  80876. PanoramaToCubeMapTools.FACE_RIGHT = [
  80877. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80878. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80879. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80880. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80881. ];
  80882. PanoramaToCubeMapTools.FACE_LEFT = [
  80883. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80884. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80885. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80886. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80887. ];
  80888. PanoramaToCubeMapTools.FACE_DOWN = [
  80889. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80890. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80891. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80892. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80893. ];
  80894. PanoramaToCubeMapTools.FACE_UP = [
  80895. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80896. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80897. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80898. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80899. ];
  80900. return PanoramaToCubeMapTools;
  80901. }());
  80902. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80903. })(BABYLON || (BABYLON = {}));
  80904. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80905. var BABYLON;
  80906. (function (BABYLON) {
  80907. ;
  80908. /**
  80909. * This groups tools to convert HDR texture to native colors array.
  80910. */
  80911. var HDRTools = /** @class */ (function () {
  80912. function HDRTools() {
  80913. }
  80914. HDRTools.Ldexp = function (mantissa, exponent) {
  80915. if (exponent > 1023) {
  80916. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80917. }
  80918. if (exponent < -1074) {
  80919. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80920. }
  80921. return mantissa * Math.pow(2, exponent);
  80922. };
  80923. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80924. if (exponent > 0) { /*nonzero pixel*/
  80925. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80926. float32array[index + 0] = red * exponent;
  80927. float32array[index + 1] = green * exponent;
  80928. float32array[index + 2] = blue * exponent;
  80929. }
  80930. else {
  80931. float32array[index + 0] = 0;
  80932. float32array[index + 1] = 0;
  80933. float32array[index + 2] = 0;
  80934. }
  80935. };
  80936. HDRTools.readStringLine = function (uint8array, startIndex) {
  80937. var line = "";
  80938. var character = "";
  80939. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80940. character = String.fromCharCode(uint8array[i]);
  80941. if (character == "\n") {
  80942. break;
  80943. }
  80944. line += character;
  80945. }
  80946. return line;
  80947. };
  80948. /**
  80949. * Reads header information from an RGBE texture stored in a native array.
  80950. * More information on this format are available here:
  80951. * https://en.wikipedia.org/wiki/RGBE_image_format
  80952. *
  80953. * @param uint8array The binary file stored in native array.
  80954. * @return The header information.
  80955. */
  80956. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80957. var height = 0;
  80958. var width = 0;
  80959. var line = this.readStringLine(uint8array, 0);
  80960. if (line[0] != '#' || line[1] != '?') {
  80961. throw "Bad HDR Format.";
  80962. }
  80963. var endOfHeader = false;
  80964. var findFormat = false;
  80965. var lineIndex = 0;
  80966. do {
  80967. lineIndex += (line.length + 1);
  80968. line = this.readStringLine(uint8array, lineIndex);
  80969. if (line == "FORMAT=32-bit_rle_rgbe") {
  80970. findFormat = true;
  80971. }
  80972. else if (line.length == 0) {
  80973. endOfHeader = true;
  80974. }
  80975. } while (!endOfHeader);
  80976. if (!findFormat) {
  80977. throw "HDR Bad header format, unsupported FORMAT";
  80978. }
  80979. lineIndex += (line.length + 1);
  80980. line = this.readStringLine(uint8array, lineIndex);
  80981. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80982. var match = sizeRegexp.exec(line);
  80983. // TODO. Support +Y and -X if needed.
  80984. if (!match || match.length < 3) {
  80985. throw "HDR Bad header format, no size";
  80986. }
  80987. width = parseInt(match[2]);
  80988. height = parseInt(match[1]);
  80989. if (width < 8 || width > 0x7fff) {
  80990. throw "HDR Bad header format, unsupported size";
  80991. }
  80992. lineIndex += (line.length + 1);
  80993. return {
  80994. height: height,
  80995. width: width,
  80996. dataPosition: lineIndex
  80997. };
  80998. };
  80999. /**
  81000. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81001. * This RGBE texture needs to store the information as a panorama.
  81002. *
  81003. * More information on this format are available here:
  81004. * https://en.wikipedia.org/wiki/RGBE_image_format
  81005. *
  81006. * @param buffer The binary file stored in an array buffer.
  81007. * @param size The expected size of the extracted cubemap.
  81008. * @return The Cube Map information.
  81009. */
  81010. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81011. var uint8array = new Uint8Array(buffer);
  81012. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81013. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81014. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81015. return cubeMapData;
  81016. };
  81017. /**
  81018. * Returns the pixels data extracted from an RGBE texture.
  81019. * This pixels will be stored left to right up to down in the R G B order in one array.
  81020. *
  81021. * More information on this format are available here:
  81022. * https://en.wikipedia.org/wiki/RGBE_image_format
  81023. *
  81024. * @param uint8array The binary file stored in an array buffer.
  81025. * @param hdrInfo The header information of the file.
  81026. * @return The pixels data in RGB right to left up to down order.
  81027. */
  81028. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81029. // Keep for multi format supports.
  81030. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81031. };
  81032. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81033. var num_scanlines = hdrInfo.height;
  81034. var scanline_width = hdrInfo.width;
  81035. var a, b, c, d, count;
  81036. var dataIndex = hdrInfo.dataPosition;
  81037. var index = 0, endIndex = 0, i = 0;
  81038. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81039. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81040. // 3 channels of 4 bytes per pixel in float.
  81041. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81042. var resultArray = new Float32Array(resultBuffer);
  81043. // read in each successive scanline
  81044. while (num_scanlines > 0) {
  81045. a = uint8array[dataIndex++];
  81046. b = uint8array[dataIndex++];
  81047. c = uint8array[dataIndex++];
  81048. d = uint8array[dataIndex++];
  81049. if (a != 2 || b != 2 || (c & 0x80)) {
  81050. // this file is not run length encoded
  81051. throw "HDR Bad header format, not RLE";
  81052. }
  81053. if (((c << 8) | d) != scanline_width) {
  81054. throw "HDR Bad header format, wrong scan line width";
  81055. }
  81056. index = 0;
  81057. // read each of the four channels for the scanline into the buffer
  81058. for (i = 0; i < 4; i++) {
  81059. endIndex = (i + 1) * scanline_width;
  81060. while (index < endIndex) {
  81061. a = uint8array[dataIndex++];
  81062. b = uint8array[dataIndex++];
  81063. if (a > 128) {
  81064. // a run of the same value
  81065. count = a - 128;
  81066. if ((count == 0) || (count > endIndex - index)) {
  81067. throw "HDR Bad Format, bad scanline data (run)";
  81068. }
  81069. while (count-- > 0) {
  81070. scanLineArray[index++] = b;
  81071. }
  81072. }
  81073. else {
  81074. // a non-run
  81075. count = a;
  81076. if ((count == 0) || (count > endIndex - index)) {
  81077. throw "HDR Bad Format, bad scanline data (non-run)";
  81078. }
  81079. scanLineArray[index++] = b;
  81080. if (--count > 0) {
  81081. for (var j = 0; j < count; j++) {
  81082. scanLineArray[index++] = uint8array[dataIndex++];
  81083. }
  81084. }
  81085. }
  81086. }
  81087. }
  81088. // now convert data from buffer into floats
  81089. for (i = 0; i < scanline_width; i++) {
  81090. a = scanLineArray[i];
  81091. b = scanLineArray[i + scanline_width];
  81092. c = scanLineArray[i + 2 * scanline_width];
  81093. d = scanLineArray[i + 3 * scanline_width];
  81094. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81095. }
  81096. num_scanlines--;
  81097. }
  81098. return resultArray;
  81099. };
  81100. return HDRTools;
  81101. }());
  81102. BABYLON.HDRTools = HDRTools;
  81103. })(BABYLON || (BABYLON = {}));
  81104. //# sourceMappingURL=babylon.hdr.js.map
  81105. var BABYLON;
  81106. (function (BABYLON) {
  81107. /**
  81108. * Sets of helpers addressing the serialization and deserialization of environment texture
  81109. * stored in a BabylonJS env file.
  81110. * Those files are usually stored as .env files.
  81111. */
  81112. var EnvironmentTextureTools = /** @class */ (function () {
  81113. function EnvironmentTextureTools() {
  81114. }
  81115. /**
  81116. * Gets the environment info from an env file.
  81117. * @param data The array buffer containing the .env bytes.
  81118. * @returns the environment file info (the json header) if successfully parsed.
  81119. */
  81120. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81121. var dataView = new DataView(data);
  81122. var pos = 0;
  81123. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81124. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81125. BABYLON.Tools.Error('Not a babylon environment map');
  81126. return null;
  81127. }
  81128. }
  81129. // Read json manifest - collect characters up to null terminator
  81130. var manifestString = '';
  81131. var charCode = 0x00;
  81132. while ((charCode = dataView.getUint8(pos++))) {
  81133. manifestString += String.fromCharCode(charCode);
  81134. }
  81135. var manifest = JSON.parse(manifestString);
  81136. if (manifest.specular) {
  81137. // Extend the header with the position of the payload.
  81138. manifest.specular.specularDataPosition = pos;
  81139. }
  81140. return manifest;
  81141. };
  81142. /**
  81143. * Creates an environment texture from a loaded cube texture.
  81144. * @param texture defines the cube texture to convert in env file
  81145. * @return a promise containing the environment data if succesfull.
  81146. */
  81147. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81148. var _this = this;
  81149. var internalTexture = texture.getInternalTexture();
  81150. if (!internalTexture) {
  81151. return Promise.reject("The cube texture is invalid.");
  81152. }
  81153. if (!texture._prefiltered) {
  81154. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81155. }
  81156. var engine = internalTexture.getEngine();
  81157. if (engine && engine.premultipliedAlpha) {
  81158. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81159. }
  81160. var canvas = engine.getRenderingCanvas();
  81161. if (!canvas) {
  81162. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81163. }
  81164. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81165. if (!engine.getCaps().textureFloatRender) {
  81166. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81167. if (!engine.getCaps().textureHalfFloatRender) {
  81168. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81169. }
  81170. }
  81171. var cubeWidth = internalTexture.width;
  81172. var hostingScene = new BABYLON.Scene(engine);
  81173. var specularTextures = {};
  81174. var promises = [];
  81175. // Read and collect all mipmaps data from the cube.
  81176. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81177. mipmapsCount = Math.round(mipmapsCount);
  81178. var _loop_1 = function (i) {
  81179. var faceWidth = Math.pow(2, mipmapsCount - i);
  81180. var _loop_2 = function (face) {
  81181. var data = texture.readPixels(face, i);
  81182. // Creates a temp texture with the face data.
  81183. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81184. // And rgbdEncode them.
  81185. var promise = new Promise(function (resolve, reject) {
  81186. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81187. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81188. rgbdPostProcess.onApply = function (effect) {
  81189. effect._bindTexture("textureSampler", tempTexture);
  81190. };
  81191. // As the process needs to happen on the main canvas, keep track of the current size
  81192. var currentW = engine.getRenderWidth();
  81193. var currentH = engine.getRenderHeight();
  81194. // Set the desired size for the texture
  81195. engine.setSize(faceWidth, faceWidth);
  81196. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81197. // Reading datas from WebGL
  81198. canvas.toBlob(function (blob) {
  81199. var fileReader = new FileReader();
  81200. fileReader.onload = function (event) {
  81201. var arrayBuffer = event.target.result;
  81202. specularTextures[i * 6 + face] = arrayBuffer;
  81203. resolve();
  81204. };
  81205. fileReader.readAsArrayBuffer(blob);
  81206. });
  81207. // Reapply the previous canvas size
  81208. engine.setSize(currentW, currentH);
  81209. });
  81210. });
  81211. promises.push(promise);
  81212. };
  81213. // All faces of the cube.
  81214. for (var face = 0; face < 6; face++) {
  81215. _loop_2(face);
  81216. }
  81217. };
  81218. for (var i = 0; i <= mipmapsCount; i++) {
  81219. _loop_1(i);
  81220. }
  81221. // Once all the textures haves been collected as RGBD stored in PNGs
  81222. return Promise.all(promises).then(function () {
  81223. // We can delete the hosting scene keeping track of all the creation objects
  81224. hostingScene.dispose();
  81225. // Creates the json header for the env texture
  81226. var info = {
  81227. version: 1,
  81228. width: cubeWidth,
  81229. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81230. specular: {
  81231. mipmaps: []
  81232. }
  81233. };
  81234. // Sets the specular image data information
  81235. var position = 0;
  81236. for (var i = 0; i <= mipmapsCount; i++) {
  81237. for (var face = 0; face < 6; face++) {
  81238. var byteLength = specularTextures[i * 6 + face].byteLength;
  81239. info.specular.mipmaps.push({
  81240. length: byteLength,
  81241. position: position
  81242. });
  81243. position += byteLength;
  81244. }
  81245. }
  81246. // Encode the JSON as an array buffer
  81247. var infoString = JSON.stringify(info);
  81248. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81249. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81250. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81251. infoView[i] = infoString.charCodeAt(i);
  81252. }
  81253. // Ends up with a null terminator for easier parsing
  81254. infoView[infoString.length] = 0x00;
  81255. // Computes the final required size and creates the storage
  81256. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81257. var finalBuffer = new ArrayBuffer(totalSize);
  81258. var finalBufferView = new Uint8Array(finalBuffer);
  81259. var dataView = new DataView(finalBuffer);
  81260. // Copy the magic bytes identifying the file in
  81261. var pos = 0;
  81262. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81263. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81264. }
  81265. // Add the json info
  81266. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81267. pos += infoBuffer.byteLength;
  81268. // Finally inserts the texture data
  81269. for (var i = 0; i <= mipmapsCount; i++) {
  81270. for (var face = 0; face < 6; face++) {
  81271. var dataBuffer = specularTextures[i * 6 + face];
  81272. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81273. pos += dataBuffer.byteLength;
  81274. }
  81275. }
  81276. // Voila
  81277. return finalBuffer;
  81278. });
  81279. };
  81280. /**
  81281. * Creates a JSON representation of the spherical data.
  81282. * @param texture defines the texture containing the polynomials
  81283. * @return the JSON representation of the spherical info
  81284. */
  81285. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81286. var polynmials = texture.sphericalPolynomial;
  81287. if (polynmials == null) {
  81288. return null;
  81289. }
  81290. return {
  81291. polynomials: true,
  81292. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81293. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81294. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81295. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81296. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81297. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81298. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81299. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81300. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81301. };
  81302. };
  81303. /**
  81304. * Uploads the texture info contained in the env file to te GPU.
  81305. * @param texture defines the internal texture to upload to
  81306. * @param arrayBuffer defines the buffer cotaining the data to load
  81307. * @param info defines the texture info retrieved through the GetEnvInfo method
  81308. * @returns a promise
  81309. */
  81310. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81311. if (info.version !== 1) {
  81312. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81313. }
  81314. var specularInfo = info.specular;
  81315. if (!specularInfo) {
  81316. // Nothing else parsed so far
  81317. return Promise.resolve();
  81318. }
  81319. // Double checks the enclosed info
  81320. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81321. mipmapsCount = Math.round(mipmapsCount) + 1;
  81322. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81323. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81324. }
  81325. // Gets everything ready.
  81326. var engine = texture.getEngine();
  81327. var expandTexture = false;
  81328. var generateNonLODTextures = false;
  81329. var rgbdPostProcess = null;
  81330. var cubeRtt = null;
  81331. var lodTextures = null;
  81332. var caps = engine.getCaps();
  81333. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81334. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81335. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81336. // Add extra process if texture lod is not supported
  81337. if (!caps.textureLOD) {
  81338. expandTexture = false;
  81339. generateNonLODTextures = true;
  81340. lodTextures = {};
  81341. }
  81342. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81343. else if (engine.webGLVersion < 2) {
  81344. expandTexture = false;
  81345. }
  81346. // If half float available we can uncompress the texture
  81347. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81348. expandTexture = true;
  81349. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81350. }
  81351. // If full float available we can uncompress the texture
  81352. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81353. expandTexture = true;
  81354. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81355. }
  81356. // Expand the texture if possible
  81357. if (expandTexture) {
  81358. // Simply run through the decode PP
  81359. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81360. texture._isRGBD = false;
  81361. texture.invertY = false;
  81362. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81363. generateDepthBuffer: false,
  81364. generateMipMaps: true,
  81365. generateStencilBuffer: false,
  81366. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81367. type: texture.type,
  81368. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81369. });
  81370. }
  81371. else {
  81372. texture._isRGBD = true;
  81373. texture.invertY = true;
  81374. // In case of missing support, applies the same patch than DDS files.
  81375. if (generateNonLODTextures) {
  81376. var mipSlices = 3;
  81377. var scale = texture._lodGenerationScale;
  81378. var offset = texture._lodGenerationOffset;
  81379. for (var i = 0; i < mipSlices; i++) {
  81380. //compute LOD from even spacing in smoothness (matching shader calculation)
  81381. var smoothness = i / (mipSlices - 1);
  81382. var roughness = 1 - smoothness;
  81383. var minLODIndex = offset; // roughness = 0
  81384. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81385. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81386. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81387. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81388. glTextureFromLod.isCube = true;
  81389. glTextureFromLod.invertY = true;
  81390. glTextureFromLod.generateMipMaps = false;
  81391. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81392. // Wrap in a base texture for easy binding.
  81393. var lodTexture = new BABYLON.BaseTexture(null);
  81394. lodTexture.isCube = true;
  81395. lodTexture._texture = glTextureFromLod;
  81396. lodTextures[mipmapIndex] = lodTexture;
  81397. switch (i) {
  81398. case 0:
  81399. texture._lodTextureLow = lodTexture;
  81400. break;
  81401. case 1:
  81402. texture._lodTextureMid = lodTexture;
  81403. break;
  81404. case 2:
  81405. texture._lodTextureHigh = lodTexture;
  81406. break;
  81407. }
  81408. }
  81409. }
  81410. }
  81411. var promises = [];
  81412. var _loop_3 = function (i) {
  81413. var _loop_4 = function (face) {
  81414. // Retrieves the face data
  81415. var imageData = specularInfo.mipmaps[i * 6 + face];
  81416. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81417. // Constructs an image element from bytes
  81418. var blob = new Blob([bytes], { type: 'image/png' });
  81419. var url = URL.createObjectURL(blob);
  81420. var image = new Image();
  81421. image.src = url;
  81422. // Enqueue promise to upload to the texture.
  81423. var promise = new Promise(function (resolve, reject) {
  81424. ;
  81425. image.onload = function () {
  81426. if (expandTexture) {
  81427. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81428. reject(message);
  81429. }, image);
  81430. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81431. // Uncompress the data to a RTT
  81432. rgbdPostProcess.onApply = function (effect) {
  81433. effect._bindTexture("textureSampler", tempTexture_1);
  81434. effect.setFloat2("scale", 1, 1);
  81435. };
  81436. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81437. // Cleanup
  81438. engine.restoreDefaultFramebuffer();
  81439. tempTexture_1.dispose();
  81440. window.URL.revokeObjectURL(url);
  81441. resolve();
  81442. });
  81443. }
  81444. else {
  81445. engine._uploadImageToTexture(texture, face, i, image);
  81446. // Upload the face to the none lod texture support
  81447. if (generateNonLODTextures) {
  81448. var lodTexture = lodTextures[i];
  81449. if (lodTexture) {
  81450. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81451. }
  81452. }
  81453. resolve();
  81454. }
  81455. };
  81456. image.onerror = function (error) {
  81457. reject(error);
  81458. };
  81459. });
  81460. promises.push(promise);
  81461. };
  81462. // All faces
  81463. for (var face = 0; face < 6; face++) {
  81464. _loop_4(face);
  81465. }
  81466. };
  81467. // All mipmaps
  81468. for (var i = 0; i < mipmapsCount; i++) {
  81469. _loop_3(i);
  81470. }
  81471. // Once all done, finishes the cleanup and return
  81472. return Promise.all(promises).then(function () {
  81473. // Relase temp RTT.
  81474. if (cubeRtt) {
  81475. engine._releaseFramebufferObjects(cubeRtt);
  81476. cubeRtt._swapAndDie(texture);
  81477. }
  81478. // Relase temp Post Process.
  81479. if (rgbdPostProcess) {
  81480. rgbdPostProcess.dispose();
  81481. }
  81482. // Flag internal texture as ready in case they are in use.
  81483. if (generateNonLODTextures) {
  81484. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81485. texture._lodTextureHigh._texture.isReady = true;
  81486. }
  81487. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81488. texture._lodTextureMid._texture.isReady = true;
  81489. }
  81490. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81491. texture._lodTextureLow._texture.isReady = true;
  81492. }
  81493. }
  81494. });
  81495. };
  81496. /**
  81497. * Uploads spherical polynomials information to the texture.
  81498. * @param texture defines the texture we are trying to upload the information to
  81499. * @param arrayBuffer defines the array buffer holding the data
  81500. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81501. */
  81502. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81503. if (info.version !== 1) {
  81504. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81505. }
  81506. var irradianceInfo = info.irradiance;
  81507. if (!irradianceInfo) {
  81508. return;
  81509. }
  81510. //harmonics now represent radiance
  81511. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81512. if (irradianceInfo.polynomials) {
  81513. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81514. }
  81515. else {
  81516. // convert From SH to SP.
  81517. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81518. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81519. }
  81520. };
  81521. /**
  81522. * Upload spherical polynomial coefficients to the texture
  81523. * @param polynmials Spherical polynmial coefficients (9)
  81524. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81525. */
  81526. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81527. outPolynomialCoefficents.x.x = polynmials.x[0];
  81528. outPolynomialCoefficents.x.y = polynmials.x[1];
  81529. outPolynomialCoefficents.x.z = polynmials.x[2];
  81530. outPolynomialCoefficents.y.x = polynmials.y[0];
  81531. outPolynomialCoefficents.y.y = polynmials.y[1];
  81532. outPolynomialCoefficents.y.z = polynmials.y[2];
  81533. outPolynomialCoefficents.z.x = polynmials.z[0];
  81534. outPolynomialCoefficents.z.y = polynmials.z[1];
  81535. outPolynomialCoefficents.z.z = polynmials.z[2];
  81536. //xx
  81537. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81538. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81539. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81540. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81541. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81542. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81543. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81544. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81545. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81546. //yz
  81547. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81548. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81549. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81550. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81551. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81552. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81553. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81554. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81555. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81556. };
  81557. /**
  81558. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81559. * L = (1/pi) * E * rho
  81560. *
  81561. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81562. * @param harmonics Spherical harmonic coefficients (9)
  81563. */
  81564. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81565. var scaleFactor = 1 / Math.PI;
  81566. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81567. // (The pixel shader must apply albedo after texture fetches, etc).
  81568. harmonics.l00[0] *= scaleFactor;
  81569. harmonics.l00[1] *= scaleFactor;
  81570. harmonics.l00[2] *= scaleFactor;
  81571. harmonics.l1_1[0] *= scaleFactor;
  81572. harmonics.l1_1[1] *= scaleFactor;
  81573. harmonics.l1_1[2] *= scaleFactor;
  81574. harmonics.l10[0] *= scaleFactor;
  81575. harmonics.l10[1] *= scaleFactor;
  81576. harmonics.l10[2] *= scaleFactor;
  81577. harmonics.l11[0] *= scaleFactor;
  81578. harmonics.l11[1] *= scaleFactor;
  81579. harmonics.l11[2] *= scaleFactor;
  81580. harmonics.l2_2[0] *= scaleFactor;
  81581. harmonics.l2_2[1] *= scaleFactor;
  81582. harmonics.l2_2[2] *= scaleFactor;
  81583. harmonics.l2_1[0] *= scaleFactor;
  81584. harmonics.l2_1[1] *= scaleFactor;
  81585. harmonics.l2_1[2] *= scaleFactor;
  81586. harmonics.l20[0] *= scaleFactor;
  81587. harmonics.l20[1] *= scaleFactor;
  81588. harmonics.l20[2] *= scaleFactor;
  81589. harmonics.l21[0] *= scaleFactor;
  81590. harmonics.l21[1] *= scaleFactor;
  81591. harmonics.l21[2] *= scaleFactor;
  81592. harmonics.l22[0] *= scaleFactor;
  81593. harmonics.l22[1] *= scaleFactor;
  81594. harmonics.l22[2] *= scaleFactor;
  81595. };
  81596. /**
  81597. * Convert spherical harmonics to spherical polynomial coefficients
  81598. * @param harmonics Spherical harmonic coefficients (9)
  81599. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81600. */
  81601. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81602. var rPi = 1 / Math.PI;
  81603. //x
  81604. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81605. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81606. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81607. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81608. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81609. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81610. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81611. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81612. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81613. //xx
  81614. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81615. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81616. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81617. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81618. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81619. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81620. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81621. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81622. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81623. //yz
  81624. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81625. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81626. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81627. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81628. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81629. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81630. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81631. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81632. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81633. };
  81634. /**
  81635. * Magic number identifying the env file.
  81636. */
  81637. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81638. return EnvironmentTextureTools;
  81639. }());
  81640. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81641. })(BABYLON || (BABYLON = {}));
  81642. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81643. var BABYLON;
  81644. (function (BABYLON) {
  81645. /**
  81646. * This represents a texture coming from an HDR input.
  81647. *
  81648. * The only supported format is currently panorama picture stored in RGBE format.
  81649. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81650. */
  81651. var HDRCubeTexture = /** @class */ (function (_super) {
  81652. __extends(HDRCubeTexture, _super);
  81653. /**
  81654. * Instantiates an HDRTexture from the following parameters.
  81655. *
  81656. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81657. * @param scene The scene the texture will be used in
  81658. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81659. * @param noMipmap Forces to not generate the mipmap if true
  81660. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81661. * @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)
  81662. * @param reserved Reserved flag for internal use.
  81663. */
  81664. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81665. if (noMipmap === void 0) { noMipmap = false; }
  81666. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81667. if (gammaSpace === void 0) { gammaSpace = false; }
  81668. if (reserved === void 0) { reserved = false; }
  81669. if (onLoad === void 0) { onLoad = null; }
  81670. if (onError === void 0) { onError = null; }
  81671. var _this = _super.call(this, scene) || this;
  81672. _this._generateHarmonics = true;
  81673. _this._onLoad = null;
  81674. _this._onError = null;
  81675. /**
  81676. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81677. */
  81678. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81679. _this._isBlocking = true;
  81680. _this._rotationY = 0;
  81681. /**
  81682. * Gets or sets the center of the bounding box associated with the cube texture
  81683. * It must define where the camera used to render the texture was set
  81684. */
  81685. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81686. if (!url) {
  81687. return _this;
  81688. }
  81689. _this.name = url;
  81690. _this.url = url;
  81691. _this.hasAlpha = false;
  81692. _this.isCube = true;
  81693. _this._textureMatrix = BABYLON.Matrix.Identity();
  81694. _this._onLoad = onLoad;
  81695. _this._onError = onError;
  81696. _this.gammaSpace = gammaSpace;
  81697. _this._noMipmap = noMipmap;
  81698. _this._size = size;
  81699. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81700. if (!_this._texture) {
  81701. if (!scene.useDelayedTextureLoading) {
  81702. _this.loadTexture();
  81703. }
  81704. else {
  81705. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81706. }
  81707. }
  81708. return _this;
  81709. }
  81710. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81711. /**
  81712. * Gets wether or not the texture is blocking during loading.
  81713. */
  81714. get: function () {
  81715. return this._isBlocking;
  81716. },
  81717. /**
  81718. * Sets wether or not the texture is blocking during loading.
  81719. */
  81720. set: function (value) {
  81721. this._isBlocking = value;
  81722. },
  81723. enumerable: true,
  81724. configurable: true
  81725. });
  81726. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81727. /**
  81728. * Gets texture matrix rotation angle around Y axis radians.
  81729. */
  81730. get: function () {
  81731. return this._rotationY;
  81732. },
  81733. /**
  81734. * Sets texture matrix rotation angle around Y axis in radians.
  81735. */
  81736. set: function (value) {
  81737. this._rotationY = value;
  81738. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81739. },
  81740. enumerable: true,
  81741. configurable: true
  81742. });
  81743. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81744. get: function () {
  81745. return this._boundingBoxSize;
  81746. },
  81747. /**
  81748. * Gets or sets the size of the bounding box associated with the cube texture
  81749. * When defined, the cubemap will switch to local mode
  81750. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81751. * @example https://www.babylonjs-playground.com/#RNASML
  81752. */
  81753. set: function (value) {
  81754. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81755. return;
  81756. }
  81757. this._boundingBoxSize = value;
  81758. var scene = this.getScene();
  81759. if (scene) {
  81760. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81761. }
  81762. },
  81763. enumerable: true,
  81764. configurable: true
  81765. });
  81766. /**
  81767. * Occurs when the file is raw .hdr file.
  81768. */
  81769. HDRCubeTexture.prototype.loadTexture = function () {
  81770. var _this = this;
  81771. var callback = function (buffer) {
  81772. _this.lodGenerationOffset = 0.0;
  81773. _this.lodGenerationScale = 0.8;
  81774. var scene = _this.getScene();
  81775. if (!scene) {
  81776. return null;
  81777. }
  81778. // Extract the raw linear data.
  81779. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81780. // Generate harmonics if needed.
  81781. if (_this._generateHarmonics) {
  81782. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81783. _this.sphericalPolynomial = sphericalPolynomial;
  81784. }
  81785. var results = [];
  81786. var byteArray = null;
  81787. // Push each faces.
  81788. for (var j = 0; j < 6; j++) {
  81789. // Create uintarray fallback.
  81790. if (!scene.getEngine().getCaps().textureFloat) {
  81791. // 3 channels of 1 bytes per pixel in bytes.
  81792. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81793. byteArray = new Uint8Array(byteBuffer);
  81794. }
  81795. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81796. // If special cases.
  81797. if (_this.gammaSpace || byteArray) {
  81798. for (var i = 0; i < _this._size * _this._size; i++) {
  81799. // Put in gamma space if requested.
  81800. if (_this.gammaSpace) {
  81801. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81802. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81803. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81804. }
  81805. // Convert to int texture for fallback.
  81806. if (byteArray) {
  81807. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81808. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81809. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81810. // May use luminance instead if the result is not accurate.
  81811. var max = Math.max(Math.max(r, g), b);
  81812. if (max > 255) {
  81813. var scale = 255 / max;
  81814. r *= scale;
  81815. g *= scale;
  81816. b *= scale;
  81817. }
  81818. byteArray[(i * 3) + 0] = r;
  81819. byteArray[(i * 3) + 1] = g;
  81820. byteArray[(i * 3) + 2] = b;
  81821. }
  81822. }
  81823. }
  81824. if (byteArray) {
  81825. results.push(byteArray);
  81826. }
  81827. else {
  81828. results.push(dataFace);
  81829. }
  81830. }
  81831. return results;
  81832. };
  81833. var scene = this.getScene();
  81834. if (scene) {
  81835. 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);
  81836. }
  81837. };
  81838. HDRCubeTexture.prototype.clone = function () {
  81839. var scene = this.getScene();
  81840. if (!scene) {
  81841. return this;
  81842. }
  81843. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81844. // Base texture
  81845. newTexture.level = this.level;
  81846. newTexture.wrapU = this.wrapU;
  81847. newTexture.wrapV = this.wrapV;
  81848. newTexture.coordinatesIndex = this.coordinatesIndex;
  81849. newTexture.coordinatesMode = this.coordinatesMode;
  81850. return newTexture;
  81851. };
  81852. // Methods
  81853. HDRCubeTexture.prototype.delayLoad = function () {
  81854. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81855. return;
  81856. }
  81857. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81858. this._texture = this._getFromCache(this.url, this._noMipmap);
  81859. if (!this._texture) {
  81860. this.loadTexture();
  81861. }
  81862. };
  81863. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81864. return this._textureMatrix;
  81865. };
  81866. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81867. this._textureMatrix = value;
  81868. };
  81869. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81870. var texture = null;
  81871. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81872. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81873. texture.name = parsedTexture.name;
  81874. texture.hasAlpha = parsedTexture.hasAlpha;
  81875. texture.level = parsedTexture.level;
  81876. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81877. texture.isBlocking = parsedTexture.isBlocking;
  81878. }
  81879. if (texture) {
  81880. if (parsedTexture.boundingBoxPosition) {
  81881. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81882. }
  81883. if (parsedTexture.boundingBoxSize) {
  81884. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81885. }
  81886. if (parsedTexture.rotationY) {
  81887. texture.rotationY = parsedTexture.rotationY;
  81888. }
  81889. }
  81890. return texture;
  81891. };
  81892. HDRCubeTexture.prototype.serialize = function () {
  81893. if (!this.name) {
  81894. return null;
  81895. }
  81896. var serializationObject = {};
  81897. serializationObject.name = this.name;
  81898. serializationObject.hasAlpha = this.hasAlpha;
  81899. serializationObject.isCube = true;
  81900. serializationObject.level = this.level;
  81901. serializationObject.size = this._size;
  81902. serializationObject.coordinatesMode = this.coordinatesMode;
  81903. serializationObject.useInGammaSpace = this.gammaSpace;
  81904. serializationObject.generateHarmonics = this._generateHarmonics;
  81905. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81906. serializationObject.noMipmap = this._noMipmap;
  81907. serializationObject.isBlocking = this._isBlocking;
  81908. serializationObject.rotationY = this._rotationY;
  81909. return serializationObject;
  81910. };
  81911. HDRCubeTexture._facesMapping = [
  81912. "right",
  81913. "left",
  81914. "up",
  81915. "down",
  81916. "front",
  81917. "back"
  81918. ];
  81919. return HDRCubeTexture;
  81920. }(BABYLON.BaseTexture));
  81921. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81922. })(BABYLON || (BABYLON = {}));
  81923. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81924. var BABYLON;
  81925. (function (BABYLON) {
  81926. var IndexedVector2 = /** @class */ (function (_super) {
  81927. __extends(IndexedVector2, _super);
  81928. function IndexedVector2(original, index) {
  81929. var _this = _super.call(this, original.x, original.y) || this;
  81930. _this.index = index;
  81931. return _this;
  81932. }
  81933. return IndexedVector2;
  81934. }(BABYLON.Vector2));
  81935. var PolygonPoints = /** @class */ (function () {
  81936. function PolygonPoints() {
  81937. this.elements = new Array();
  81938. }
  81939. PolygonPoints.prototype.add = function (originalPoints) {
  81940. var _this = this;
  81941. var result = new Array();
  81942. originalPoints.forEach(function (point) {
  81943. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81944. var newPoint = new IndexedVector2(point, _this.elements.length);
  81945. result.push(newPoint);
  81946. _this.elements.push(newPoint);
  81947. }
  81948. });
  81949. return result;
  81950. };
  81951. PolygonPoints.prototype.computeBounds = function () {
  81952. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81953. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81954. this.elements.forEach(function (point) {
  81955. // x
  81956. if (point.x < lmin.x) {
  81957. lmin.x = point.x;
  81958. }
  81959. else if (point.x > lmax.x) {
  81960. lmax.x = point.x;
  81961. }
  81962. // y
  81963. if (point.y < lmin.y) {
  81964. lmin.y = point.y;
  81965. }
  81966. else if (point.y > lmax.y) {
  81967. lmax.y = point.y;
  81968. }
  81969. });
  81970. return {
  81971. min: lmin,
  81972. max: lmax,
  81973. width: lmax.x - lmin.x,
  81974. height: lmax.y - lmin.y
  81975. };
  81976. };
  81977. return PolygonPoints;
  81978. }());
  81979. var Polygon = /** @class */ (function () {
  81980. function Polygon() {
  81981. }
  81982. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81983. return [
  81984. new BABYLON.Vector2(xmin, ymin),
  81985. new BABYLON.Vector2(xmax, ymin),
  81986. new BABYLON.Vector2(xmax, ymax),
  81987. new BABYLON.Vector2(xmin, ymax)
  81988. ];
  81989. };
  81990. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81991. if (cx === void 0) { cx = 0; }
  81992. if (cy === void 0) { cy = 0; }
  81993. if (numberOfSides === void 0) { numberOfSides = 32; }
  81994. var result = new Array();
  81995. var angle = 0;
  81996. var increment = (Math.PI * 2) / numberOfSides;
  81997. for (var i = 0; i < numberOfSides; i++) {
  81998. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81999. angle -= increment;
  82000. }
  82001. return result;
  82002. };
  82003. Polygon.Parse = function (input) {
  82004. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82005. var i, result = [];
  82006. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82007. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82008. }
  82009. return result;
  82010. };
  82011. Polygon.StartingAt = function (x, y) {
  82012. return BABYLON.Path2.StartingAt(x, y);
  82013. };
  82014. return Polygon;
  82015. }());
  82016. BABYLON.Polygon = Polygon;
  82017. var PolygonMeshBuilder = /** @class */ (function () {
  82018. function PolygonMeshBuilder(name, contours, scene) {
  82019. this._points = new PolygonPoints();
  82020. this._outlinepoints = new PolygonPoints();
  82021. this._holes = new Array();
  82022. this._epoints = new Array();
  82023. this._eholes = new Array();
  82024. this._name = name;
  82025. this._scene = scene;
  82026. var points;
  82027. if (contours instanceof BABYLON.Path2) {
  82028. points = contours.getPoints();
  82029. }
  82030. else {
  82031. points = contours;
  82032. }
  82033. this._addToepoint(points);
  82034. this._points.add(points);
  82035. this._outlinepoints.add(points);
  82036. if (typeof earcut === 'undefined') {
  82037. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82038. }
  82039. }
  82040. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82041. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82042. var p = points_1[_i];
  82043. this._epoints.push(p.x, p.y);
  82044. }
  82045. };
  82046. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82047. this._points.add(hole);
  82048. var holepoints = new PolygonPoints();
  82049. holepoints.add(hole);
  82050. this._holes.push(holepoints);
  82051. this._eholes.push(this._epoints.length / 2);
  82052. this._addToepoint(hole);
  82053. return this;
  82054. };
  82055. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82056. var _this = this;
  82057. if (updatable === void 0) { updatable = false; }
  82058. if (depth === void 0) { depth = 0; }
  82059. var result = new BABYLON.Mesh(this._name, this._scene);
  82060. var normals = new Array();
  82061. var positions = new Array();
  82062. var uvs = new Array();
  82063. var bounds = this._points.computeBounds();
  82064. this._points.elements.forEach(function (p) {
  82065. normals.push(0, 1.0, 0);
  82066. positions.push(p.x, 0, p.y);
  82067. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82068. });
  82069. var indices = new Array();
  82070. var res = earcut(this._epoints, this._eholes, 2);
  82071. for (var i = 0; i < res.length; i++) {
  82072. indices.push(res[i]);
  82073. }
  82074. if (depth > 0) {
  82075. var positionscount = (positions.length / 3); //get the current pointcount
  82076. this._points.elements.forEach(function (p) {
  82077. normals.push(0, -1.0, 0);
  82078. positions.push(p.x, -depth, p.y);
  82079. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82080. });
  82081. var totalCount = indices.length;
  82082. for (var i = 0; i < totalCount; i += 3) {
  82083. var i0 = indices[i + 0];
  82084. var i1 = indices[i + 1];
  82085. var i2 = indices[i + 2];
  82086. indices.push(i2 + positionscount);
  82087. indices.push(i1 + positionscount);
  82088. indices.push(i0 + positionscount);
  82089. }
  82090. //Add the sides
  82091. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82092. this._holes.forEach(function (hole) {
  82093. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82094. });
  82095. }
  82096. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82097. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82098. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82099. result.setIndices(indices);
  82100. return result;
  82101. };
  82102. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82103. var StartIndex = positions.length / 3;
  82104. var ulength = 0;
  82105. for (var i = 0; i < points.elements.length; i++) {
  82106. var p = points.elements[i];
  82107. var p1;
  82108. if ((i + 1) > points.elements.length - 1) {
  82109. p1 = points.elements[0];
  82110. }
  82111. else {
  82112. p1 = points.elements[i + 1];
  82113. }
  82114. positions.push(p.x, 0, p.y);
  82115. positions.push(p.x, -depth, p.y);
  82116. positions.push(p1.x, 0, p1.y);
  82117. positions.push(p1.x, -depth, p1.y);
  82118. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82119. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82120. var v3 = v2.subtract(v1);
  82121. var v4 = new BABYLON.Vector3(0, 1, 0);
  82122. var vn = BABYLON.Vector3.Cross(v3, v4);
  82123. vn = vn.normalize();
  82124. uvs.push(ulength / bounds.width, 0);
  82125. uvs.push(ulength / bounds.width, 1);
  82126. ulength += v3.length();
  82127. uvs.push((ulength / bounds.width), 0);
  82128. uvs.push((ulength / bounds.width), 1);
  82129. if (!flip) {
  82130. normals.push(-vn.x, -vn.y, -vn.z);
  82131. normals.push(-vn.x, -vn.y, -vn.z);
  82132. normals.push(-vn.x, -vn.y, -vn.z);
  82133. normals.push(-vn.x, -vn.y, -vn.z);
  82134. indices.push(StartIndex);
  82135. indices.push(StartIndex + 1);
  82136. indices.push(StartIndex + 2);
  82137. indices.push(StartIndex + 1);
  82138. indices.push(StartIndex + 3);
  82139. indices.push(StartIndex + 2);
  82140. }
  82141. else {
  82142. normals.push(vn.x, vn.y, vn.z);
  82143. normals.push(vn.x, vn.y, vn.z);
  82144. normals.push(vn.x, vn.y, vn.z);
  82145. normals.push(vn.x, vn.y, vn.z);
  82146. indices.push(StartIndex);
  82147. indices.push(StartIndex + 2);
  82148. indices.push(StartIndex + 1);
  82149. indices.push(StartIndex + 1);
  82150. indices.push(StartIndex + 2);
  82151. indices.push(StartIndex + 3);
  82152. }
  82153. StartIndex += 4;
  82154. }
  82155. ;
  82156. };
  82157. return PolygonMeshBuilder;
  82158. }());
  82159. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82160. })(BABYLON || (BABYLON = {}));
  82161. //# sourceMappingURL=babylon.polygonMesh.js.map
  82162. var BABYLON;
  82163. (function (BABYLON) {
  82164. // Unique ID when we import meshes from Babylon to CSG
  82165. var currentCSGMeshId = 0;
  82166. // # class Vertex
  82167. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82168. // one to provide additional features like texture coordinates and vertex
  82169. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82170. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82171. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82172. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82173. // is not used anywhere else.
  82174. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82175. var Vertex = /** @class */ (function () {
  82176. function Vertex(pos, normal, uv) {
  82177. this.pos = pos;
  82178. this.normal = normal;
  82179. this.uv = uv;
  82180. }
  82181. Vertex.prototype.clone = function () {
  82182. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82183. };
  82184. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82185. // orientation of a polygon is flipped.
  82186. Vertex.prototype.flip = function () {
  82187. this.normal = this.normal.scale(-1);
  82188. };
  82189. // Create a new vertex between this vertex and `other` by linearly
  82190. // interpolating all properties using a parameter of `t`. Subclasses should
  82191. // override this to interpolate additional properties.
  82192. Vertex.prototype.interpolate = function (other, t) {
  82193. 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));
  82194. };
  82195. return Vertex;
  82196. }());
  82197. // # class Plane
  82198. // Represents a plane in 3D space.
  82199. var Plane = /** @class */ (function () {
  82200. function Plane(normal, w) {
  82201. this.normal = normal;
  82202. this.w = w;
  82203. }
  82204. Plane.FromPoints = function (a, b, c) {
  82205. var v0 = c.subtract(a);
  82206. var v1 = b.subtract(a);
  82207. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82208. return null;
  82209. }
  82210. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82211. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82212. };
  82213. Plane.prototype.clone = function () {
  82214. return new Plane(this.normal.clone(), this.w);
  82215. };
  82216. Plane.prototype.flip = function () {
  82217. this.normal.scaleInPlace(-1);
  82218. this.w = -this.w;
  82219. };
  82220. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82221. // fragments in the appropriate lists. Coplanar polygons go into either
  82222. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82223. // respect to this plane. Polygons in front or in back of this plane go into
  82224. // either `front` or `back`.
  82225. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82226. var COPLANAR = 0;
  82227. var FRONT = 1;
  82228. var BACK = 2;
  82229. var SPANNING = 3;
  82230. // Classify each point as well as the entire polygon into one of the above
  82231. // four classes.
  82232. var polygonType = 0;
  82233. var types = [];
  82234. var i;
  82235. var t;
  82236. for (i = 0; i < polygon.vertices.length; i++) {
  82237. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82238. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82239. polygonType |= type;
  82240. types.push(type);
  82241. }
  82242. // Put the polygon in the correct list, splitting it when necessary.
  82243. switch (polygonType) {
  82244. case COPLANAR:
  82245. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82246. break;
  82247. case FRONT:
  82248. front.push(polygon);
  82249. break;
  82250. case BACK:
  82251. back.push(polygon);
  82252. break;
  82253. case SPANNING:
  82254. var f = [], b = [];
  82255. for (i = 0; i < polygon.vertices.length; i++) {
  82256. var j = (i + 1) % polygon.vertices.length;
  82257. var ti = types[i], tj = types[j];
  82258. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82259. if (ti !== BACK)
  82260. f.push(vi);
  82261. if (ti !== FRONT)
  82262. b.push(ti !== BACK ? vi.clone() : vi);
  82263. if ((ti | tj) === SPANNING) {
  82264. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82265. var v = vi.interpolate(vj, t);
  82266. f.push(v);
  82267. b.push(v.clone());
  82268. }
  82269. }
  82270. var poly;
  82271. if (f.length >= 3) {
  82272. poly = new Polygon(f, polygon.shared);
  82273. if (poly.plane)
  82274. front.push(poly);
  82275. }
  82276. if (b.length >= 3) {
  82277. poly = new Polygon(b, polygon.shared);
  82278. if (poly.plane)
  82279. back.push(poly);
  82280. }
  82281. break;
  82282. }
  82283. };
  82284. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82285. // point is on the plane.
  82286. Plane.EPSILON = 1e-5;
  82287. return Plane;
  82288. }());
  82289. // # class Polygon
  82290. // Represents a convex polygon. The vertices used to initialize a polygon must
  82291. // be coplanar and form a convex loop.
  82292. //
  82293. // Each convex polygon has a `shared` property, which is shared between all
  82294. // polygons that are clones of each other or were split from the same polygon.
  82295. // This can be used to define per-polygon properties (such as surface color).
  82296. var Polygon = /** @class */ (function () {
  82297. function Polygon(vertices, shared) {
  82298. this.vertices = vertices;
  82299. this.shared = shared;
  82300. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82301. }
  82302. Polygon.prototype.clone = function () {
  82303. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82304. return new Polygon(vertices, this.shared);
  82305. };
  82306. Polygon.prototype.flip = function () {
  82307. this.vertices.reverse().map(function (v) { v.flip(); });
  82308. this.plane.flip();
  82309. };
  82310. return Polygon;
  82311. }());
  82312. // # class Node
  82313. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82314. // by picking a polygon to split along. That polygon (and all other coplanar
  82315. // polygons) are added directly to that node and the other polygons are added to
  82316. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82317. // no distinction between internal and leaf nodes.
  82318. var Node = /** @class */ (function () {
  82319. function Node(polygons) {
  82320. this.plane = null;
  82321. this.front = null;
  82322. this.back = null;
  82323. this.polygons = new Array();
  82324. if (polygons) {
  82325. this.build(polygons);
  82326. }
  82327. }
  82328. Node.prototype.clone = function () {
  82329. var node = new Node();
  82330. node.plane = this.plane && this.plane.clone();
  82331. node.front = this.front && this.front.clone();
  82332. node.back = this.back && this.back.clone();
  82333. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82334. return node;
  82335. };
  82336. // Convert solid space to empty space and empty space to solid space.
  82337. Node.prototype.invert = function () {
  82338. for (var i = 0; i < this.polygons.length; i++) {
  82339. this.polygons[i].flip();
  82340. }
  82341. if (this.plane) {
  82342. this.plane.flip();
  82343. }
  82344. if (this.front) {
  82345. this.front.invert();
  82346. }
  82347. if (this.back) {
  82348. this.back.invert();
  82349. }
  82350. var temp = this.front;
  82351. this.front = this.back;
  82352. this.back = temp;
  82353. };
  82354. // Recursively remove all polygons in `polygons` that are inside this BSP
  82355. // tree.
  82356. Node.prototype.clipPolygons = function (polygons) {
  82357. if (!this.plane)
  82358. return polygons.slice();
  82359. var front = new Array(), back = new Array();
  82360. for (var i = 0; i < polygons.length; i++) {
  82361. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82362. }
  82363. if (this.front) {
  82364. front = this.front.clipPolygons(front);
  82365. }
  82366. if (this.back) {
  82367. back = this.back.clipPolygons(back);
  82368. }
  82369. else {
  82370. back = [];
  82371. }
  82372. return front.concat(back);
  82373. };
  82374. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82375. // `bsp`.
  82376. Node.prototype.clipTo = function (bsp) {
  82377. this.polygons = bsp.clipPolygons(this.polygons);
  82378. if (this.front)
  82379. this.front.clipTo(bsp);
  82380. if (this.back)
  82381. this.back.clipTo(bsp);
  82382. };
  82383. // Return a list of all polygons in this BSP tree.
  82384. Node.prototype.allPolygons = function () {
  82385. var polygons = this.polygons.slice();
  82386. if (this.front)
  82387. polygons = polygons.concat(this.front.allPolygons());
  82388. if (this.back)
  82389. polygons = polygons.concat(this.back.allPolygons());
  82390. return polygons;
  82391. };
  82392. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82393. // new polygons are filtered down to the bottom of the tree and become new
  82394. // nodes there. Each set of polygons is partitioned using the first polygon
  82395. // (no heuristic is used to pick a good split).
  82396. Node.prototype.build = function (polygons) {
  82397. if (!polygons.length)
  82398. return;
  82399. if (!this.plane)
  82400. this.plane = polygons[0].plane.clone();
  82401. var front = new Array(), back = new Array();
  82402. for (var i = 0; i < polygons.length; i++) {
  82403. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82404. }
  82405. if (front.length) {
  82406. if (!this.front)
  82407. this.front = new Node();
  82408. this.front.build(front);
  82409. }
  82410. if (back.length) {
  82411. if (!this.back)
  82412. this.back = new Node();
  82413. this.back.build(back);
  82414. }
  82415. };
  82416. return Node;
  82417. }());
  82418. var CSG = /** @class */ (function () {
  82419. function CSG() {
  82420. this.polygons = new Array();
  82421. }
  82422. // Convert BABYLON.Mesh to BABYLON.CSG
  82423. CSG.FromMesh = function (mesh) {
  82424. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82425. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82426. if (mesh instanceof BABYLON.Mesh) {
  82427. mesh.computeWorldMatrix(true);
  82428. matrix = mesh.getWorldMatrix();
  82429. meshPosition = mesh.position.clone();
  82430. meshRotation = mesh.rotation.clone();
  82431. if (mesh.rotationQuaternion) {
  82432. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82433. }
  82434. meshScaling = mesh.scaling.clone();
  82435. }
  82436. else {
  82437. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82438. }
  82439. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82440. var subMeshes = mesh.subMeshes;
  82441. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82442. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82443. vertices = [];
  82444. for (var j = 0; j < 3; j++) {
  82445. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82446. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82447. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82448. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82449. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82450. vertex = new Vertex(position, normal, uv);
  82451. vertices.push(vertex);
  82452. }
  82453. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82454. // To handle the case of degenerated triangle
  82455. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82456. if (polygon.plane)
  82457. polygons.push(polygon);
  82458. }
  82459. }
  82460. var csg = CSG.FromPolygons(polygons);
  82461. csg.matrix = matrix;
  82462. csg.position = meshPosition;
  82463. csg.rotation = meshRotation;
  82464. csg.scaling = meshScaling;
  82465. csg.rotationQuaternion = meshRotationQuaternion;
  82466. currentCSGMeshId++;
  82467. return csg;
  82468. };
  82469. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82470. CSG.FromPolygons = function (polygons) {
  82471. var csg = new CSG();
  82472. csg.polygons = polygons;
  82473. return csg;
  82474. };
  82475. CSG.prototype.clone = function () {
  82476. var csg = new CSG();
  82477. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82478. csg.copyTransformAttributes(this);
  82479. return csg;
  82480. };
  82481. CSG.prototype.union = function (csg) {
  82482. var a = new Node(this.clone().polygons);
  82483. var b = new Node(csg.clone().polygons);
  82484. a.clipTo(b);
  82485. b.clipTo(a);
  82486. b.invert();
  82487. b.clipTo(a);
  82488. b.invert();
  82489. a.build(b.allPolygons());
  82490. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82491. };
  82492. CSG.prototype.unionInPlace = function (csg) {
  82493. var a = new Node(this.polygons);
  82494. var b = new Node(csg.polygons);
  82495. a.clipTo(b);
  82496. b.clipTo(a);
  82497. b.invert();
  82498. b.clipTo(a);
  82499. b.invert();
  82500. a.build(b.allPolygons());
  82501. this.polygons = a.allPolygons();
  82502. };
  82503. CSG.prototype.subtract = function (csg) {
  82504. var a = new Node(this.clone().polygons);
  82505. var b = new Node(csg.clone().polygons);
  82506. a.invert();
  82507. a.clipTo(b);
  82508. b.clipTo(a);
  82509. b.invert();
  82510. b.clipTo(a);
  82511. b.invert();
  82512. a.build(b.allPolygons());
  82513. a.invert();
  82514. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82515. };
  82516. CSG.prototype.subtractInPlace = function (csg) {
  82517. var a = new Node(this.polygons);
  82518. var b = new Node(csg.polygons);
  82519. a.invert();
  82520. a.clipTo(b);
  82521. b.clipTo(a);
  82522. b.invert();
  82523. b.clipTo(a);
  82524. b.invert();
  82525. a.build(b.allPolygons());
  82526. a.invert();
  82527. this.polygons = a.allPolygons();
  82528. };
  82529. CSG.prototype.intersect = function (csg) {
  82530. var a = new Node(this.clone().polygons);
  82531. var b = new Node(csg.clone().polygons);
  82532. a.invert();
  82533. b.clipTo(a);
  82534. b.invert();
  82535. a.clipTo(b);
  82536. b.clipTo(a);
  82537. a.build(b.allPolygons());
  82538. a.invert();
  82539. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82540. };
  82541. CSG.prototype.intersectInPlace = function (csg) {
  82542. var a = new Node(this.polygons);
  82543. var b = new Node(csg.polygons);
  82544. a.invert();
  82545. b.clipTo(a);
  82546. b.invert();
  82547. a.clipTo(b);
  82548. b.clipTo(a);
  82549. a.build(b.allPolygons());
  82550. a.invert();
  82551. this.polygons = a.allPolygons();
  82552. };
  82553. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82554. // not modified.
  82555. CSG.prototype.inverse = function () {
  82556. var csg = this.clone();
  82557. csg.inverseInPlace();
  82558. return csg;
  82559. };
  82560. CSG.prototype.inverseInPlace = function () {
  82561. this.polygons.map(function (p) { p.flip(); });
  82562. };
  82563. // This is used to keep meshes transformations so they can be restored
  82564. // when we build back a Babylon Mesh
  82565. // NB : All CSG operations are performed in world coordinates
  82566. CSG.prototype.copyTransformAttributes = function (csg) {
  82567. this.matrix = csg.matrix;
  82568. this.position = csg.position;
  82569. this.rotation = csg.rotation;
  82570. this.scaling = csg.scaling;
  82571. this.rotationQuaternion = csg.rotationQuaternion;
  82572. return this;
  82573. };
  82574. // Build Raw mesh from CSG
  82575. // Coordinates here are in world space
  82576. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82577. var matrix = this.matrix.clone();
  82578. matrix.invert();
  82579. 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;
  82580. if (keepSubMeshes) {
  82581. // Sort Polygons, since subMeshes are indices range
  82582. polygons.sort(function (a, b) {
  82583. if (a.shared.meshId === b.shared.meshId) {
  82584. return a.shared.subMeshId - b.shared.subMeshId;
  82585. }
  82586. else {
  82587. return a.shared.meshId - b.shared.meshId;
  82588. }
  82589. });
  82590. }
  82591. for (var i = 0, il = polygons.length; i < il; i++) {
  82592. polygon = polygons[i];
  82593. // Building SubMeshes
  82594. if (!subMesh_dict[polygon.shared.meshId]) {
  82595. subMesh_dict[polygon.shared.meshId] = {};
  82596. }
  82597. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82598. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82599. indexStart: +Infinity,
  82600. indexEnd: -Infinity,
  82601. materialIndex: polygon.shared.materialIndex
  82602. };
  82603. }
  82604. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82605. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82606. polygonIndices[0] = 0;
  82607. polygonIndices[1] = j - 1;
  82608. polygonIndices[2] = j;
  82609. for (var k = 0; k < 3; k++) {
  82610. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82611. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82612. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82613. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82614. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82615. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82616. // Check if 2 points can be merged
  82617. if (!(typeof vertex_idx !== 'undefined' &&
  82618. normals[vertex_idx * 3] === localNormal.x &&
  82619. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82620. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82621. uvs[vertex_idx * 2] === uv.x &&
  82622. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82623. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82624. uvs.push(uv.x, uv.y);
  82625. normals.push(normal.x, normal.y, normal.z);
  82626. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82627. }
  82628. indices.push(vertex_idx);
  82629. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82630. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82631. currentIndex++;
  82632. }
  82633. }
  82634. }
  82635. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82636. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82637. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82638. mesh.setIndices(indices, null);
  82639. if (keepSubMeshes) {
  82640. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82641. var materialIndexOffset = 0, materialMaxIndex;
  82642. mesh.subMeshes = new Array();
  82643. for (var m in subMesh_dict) {
  82644. materialMaxIndex = -1;
  82645. for (var sm in subMesh_dict[m]) {
  82646. subMesh_obj = subMesh_dict[m][sm];
  82647. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82648. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82649. }
  82650. materialIndexOffset += ++materialMaxIndex;
  82651. }
  82652. }
  82653. return mesh;
  82654. };
  82655. // Build Mesh from CSG taking material and transforms into account
  82656. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82657. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82658. mesh.material = material;
  82659. mesh.position.copyFrom(this.position);
  82660. mesh.rotation.copyFrom(this.rotation);
  82661. if (this.rotationQuaternion) {
  82662. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82663. }
  82664. mesh.scaling.copyFrom(this.scaling);
  82665. mesh.computeWorldMatrix(true);
  82666. return mesh;
  82667. };
  82668. return CSG;
  82669. }());
  82670. BABYLON.CSG = CSG;
  82671. })(BABYLON || (BABYLON = {}));
  82672. //# sourceMappingURL=babylon.csg.js.map
  82673. var BABYLON;
  82674. (function (BABYLON) {
  82675. var LensFlare = /** @class */ (function () {
  82676. function LensFlare(size, position, color, imgUrl, system) {
  82677. this.size = size;
  82678. this.position = position;
  82679. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82680. this.color = color || new BABYLON.Color3(1, 1, 1);
  82681. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82682. this._system = system;
  82683. system.lensFlares.push(this);
  82684. }
  82685. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82686. return new LensFlare(size, position, color, imgUrl, system);
  82687. };
  82688. LensFlare.prototype.dispose = function () {
  82689. if (this.texture) {
  82690. this.texture.dispose();
  82691. }
  82692. // Remove from scene
  82693. var index = this._system.lensFlares.indexOf(this);
  82694. this._system.lensFlares.splice(index, 1);
  82695. };
  82696. ;
  82697. return LensFlare;
  82698. }());
  82699. BABYLON.LensFlare = LensFlare;
  82700. })(BABYLON || (BABYLON = {}));
  82701. //# sourceMappingURL=babylon.lensFlare.js.map
  82702. var BABYLON;
  82703. (function (BABYLON) {
  82704. var LensFlareSystem = /** @class */ (function () {
  82705. function LensFlareSystem(name, emitter, scene) {
  82706. this.name = name;
  82707. this.lensFlares = new Array();
  82708. this.borderLimit = 300;
  82709. this.viewportBorder = 0;
  82710. this.layerMask = 0x0FFFFFFF;
  82711. this._vertexBuffers = {};
  82712. this._isEnabled = true;
  82713. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82714. this._emitter = emitter;
  82715. this.id = name;
  82716. scene.lensFlareSystems.push(this);
  82717. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82718. var engine = scene.getEngine();
  82719. // VBO
  82720. var vertices = [];
  82721. vertices.push(1, 1);
  82722. vertices.push(-1, 1);
  82723. vertices.push(-1, -1);
  82724. vertices.push(1, -1);
  82725. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82726. // Indices
  82727. var indices = [];
  82728. indices.push(0);
  82729. indices.push(1);
  82730. indices.push(2);
  82731. indices.push(0);
  82732. indices.push(2);
  82733. indices.push(3);
  82734. this._indexBuffer = engine.createIndexBuffer(indices);
  82735. // Effects
  82736. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82737. }
  82738. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82739. get: function () {
  82740. return this._isEnabled;
  82741. },
  82742. set: function (value) {
  82743. this._isEnabled = value;
  82744. },
  82745. enumerable: true,
  82746. configurable: true
  82747. });
  82748. LensFlareSystem.prototype.getScene = function () {
  82749. return this._scene;
  82750. };
  82751. LensFlareSystem.prototype.getEmitter = function () {
  82752. return this._emitter;
  82753. };
  82754. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82755. this._emitter = newEmitter;
  82756. };
  82757. LensFlareSystem.prototype.getEmitterPosition = function () {
  82758. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82759. };
  82760. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82761. var position = this.getEmitterPosition();
  82762. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82763. this._positionX = position.x;
  82764. this._positionY = position.y;
  82765. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82766. if (this.viewportBorder > 0) {
  82767. globalViewport.x -= this.viewportBorder;
  82768. globalViewport.y -= this.viewportBorder;
  82769. globalViewport.width += this.viewportBorder * 2;
  82770. globalViewport.height += this.viewportBorder * 2;
  82771. position.x += this.viewportBorder;
  82772. position.y += this.viewportBorder;
  82773. this._positionX += this.viewportBorder;
  82774. this._positionY += this.viewportBorder;
  82775. }
  82776. if (position.z > 0) {
  82777. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82778. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82779. return true;
  82780. }
  82781. return true;
  82782. }
  82783. return false;
  82784. };
  82785. LensFlareSystem.prototype._isVisible = function () {
  82786. if (!this._isEnabled || !this._scene.activeCamera) {
  82787. return false;
  82788. }
  82789. var emitterPosition = this.getEmitterPosition();
  82790. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82791. var distance = direction.length();
  82792. direction.normalize();
  82793. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82794. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82795. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82796. };
  82797. LensFlareSystem.prototype.render = function () {
  82798. if (!this._effect.isReady() || !this._scene.activeCamera)
  82799. return false;
  82800. var engine = this._scene.getEngine();
  82801. var viewport = this._scene.activeCamera.viewport;
  82802. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82803. // Position
  82804. if (!this.computeEffectivePosition(globalViewport)) {
  82805. return false;
  82806. }
  82807. // Visibility
  82808. if (!this._isVisible()) {
  82809. return false;
  82810. }
  82811. // Intensity
  82812. var awayX;
  82813. var awayY;
  82814. if (this._positionX < this.borderLimit + globalViewport.x) {
  82815. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82816. }
  82817. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82818. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82819. }
  82820. else {
  82821. awayX = 0;
  82822. }
  82823. if (this._positionY < this.borderLimit + globalViewport.y) {
  82824. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82825. }
  82826. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82827. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82828. }
  82829. else {
  82830. awayY = 0;
  82831. }
  82832. var away = (awayX > awayY) ? awayX : awayY;
  82833. away -= this.viewportBorder;
  82834. if (away > this.borderLimit) {
  82835. away = this.borderLimit;
  82836. }
  82837. var intensity = 1.0 - (away / this.borderLimit);
  82838. if (intensity < 0) {
  82839. return false;
  82840. }
  82841. if (intensity > 1.0) {
  82842. intensity = 1.0;
  82843. }
  82844. if (this.viewportBorder > 0) {
  82845. globalViewport.x += this.viewportBorder;
  82846. globalViewport.y += this.viewportBorder;
  82847. globalViewport.width -= this.viewportBorder * 2;
  82848. globalViewport.height -= this.viewportBorder * 2;
  82849. this._positionX -= this.viewportBorder;
  82850. this._positionY -= this.viewportBorder;
  82851. }
  82852. // Position
  82853. var centerX = globalViewport.x + globalViewport.width / 2;
  82854. var centerY = globalViewport.y + globalViewport.height / 2;
  82855. var distX = centerX - this._positionX;
  82856. var distY = centerY - this._positionY;
  82857. // Effects
  82858. engine.enableEffect(this._effect);
  82859. engine.setState(false);
  82860. engine.setDepthBuffer(false);
  82861. // VBOs
  82862. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82863. // Flares
  82864. for (var index = 0; index < this.lensFlares.length; index++) {
  82865. var flare = this.lensFlares[index];
  82866. engine.setAlphaMode(flare.alphaMode);
  82867. var x = centerX - (distX * flare.position);
  82868. var y = centerY - (distY * flare.position);
  82869. var cw = flare.size;
  82870. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82871. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82872. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82873. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82874. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82875. // Texture
  82876. this._effect.setTexture("textureSampler", flare.texture);
  82877. // Color
  82878. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82879. // Draw order
  82880. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82881. }
  82882. engine.setDepthBuffer(true);
  82883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82884. return true;
  82885. };
  82886. LensFlareSystem.prototype.dispose = function () {
  82887. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82888. if (vertexBuffer) {
  82889. vertexBuffer.dispose();
  82890. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82891. }
  82892. if (this._indexBuffer) {
  82893. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82894. this._indexBuffer = null;
  82895. }
  82896. while (this.lensFlares.length) {
  82897. this.lensFlares[0].dispose();
  82898. }
  82899. // Remove from scene
  82900. var index = this._scene.lensFlareSystems.indexOf(this);
  82901. this._scene.lensFlareSystems.splice(index, 1);
  82902. };
  82903. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82904. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82905. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82906. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82907. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82908. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82909. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82910. var parsedFlare = parsedLensFlareSystem.flares[index];
  82911. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82912. }
  82913. return lensFlareSystem;
  82914. };
  82915. LensFlareSystem.prototype.serialize = function () {
  82916. var serializationObject = {};
  82917. serializationObject.id = this.id;
  82918. serializationObject.name = this.name;
  82919. serializationObject.emitterId = this.getEmitter().id;
  82920. serializationObject.borderLimit = this.borderLimit;
  82921. serializationObject.flares = [];
  82922. for (var index = 0; index < this.lensFlares.length; index++) {
  82923. var flare = this.lensFlares[index];
  82924. serializationObject.flares.push({
  82925. size: flare.size,
  82926. position: flare.position,
  82927. color: flare.color.asArray(),
  82928. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82929. });
  82930. }
  82931. return serializationObject;
  82932. };
  82933. return LensFlareSystem;
  82934. }());
  82935. BABYLON.LensFlareSystem = LensFlareSystem;
  82936. })(BABYLON || (BABYLON = {}));
  82937. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82938. var BABYLON;
  82939. (function (BABYLON) {
  82940. /**
  82941. * This is a holder class for the physics joint created by the physics plugin.
  82942. * It holds a set of functions to control the underlying joint.
  82943. */
  82944. var PhysicsJoint = /** @class */ (function () {
  82945. function PhysicsJoint(type, jointData) {
  82946. this.type = type;
  82947. this.jointData = jointData;
  82948. jointData.nativeParams = jointData.nativeParams || {};
  82949. }
  82950. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82951. get: function () {
  82952. return this._physicsJoint;
  82953. },
  82954. set: function (newJoint) {
  82955. if (this._physicsJoint) {
  82956. //remove from the wolrd
  82957. }
  82958. this._physicsJoint = newJoint;
  82959. },
  82960. enumerable: true,
  82961. configurable: true
  82962. });
  82963. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82964. set: function (physicsPlugin) {
  82965. this._physicsPlugin = physicsPlugin;
  82966. },
  82967. enumerable: true,
  82968. configurable: true
  82969. });
  82970. /**
  82971. * Execute a function that is physics-plugin specific.
  82972. * @param {Function} func the function that will be executed.
  82973. * It accepts two parameters: the physics world and the physics joint.
  82974. */
  82975. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82976. func(this._physicsPlugin.world, this._physicsJoint);
  82977. };
  82978. //TODO check if the native joints are the same
  82979. //Joint Types
  82980. PhysicsJoint.DistanceJoint = 0;
  82981. PhysicsJoint.HingeJoint = 1;
  82982. PhysicsJoint.BallAndSocketJoint = 2;
  82983. PhysicsJoint.WheelJoint = 3;
  82984. PhysicsJoint.SliderJoint = 4;
  82985. //OIMO
  82986. PhysicsJoint.PrismaticJoint = 5;
  82987. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82988. PhysicsJoint.UniversalJoint = 6;
  82989. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82990. //Cannon
  82991. //Similar to a Ball-Joint. Different in params
  82992. PhysicsJoint.PointToPointJoint = 8;
  82993. //Cannon only at the moment
  82994. PhysicsJoint.SpringJoint = 9;
  82995. PhysicsJoint.LockJoint = 10;
  82996. return PhysicsJoint;
  82997. }());
  82998. BABYLON.PhysicsJoint = PhysicsJoint;
  82999. /**
  83000. * A class representing a physics distance joint.
  83001. */
  83002. var DistanceJoint = /** @class */ (function (_super) {
  83003. __extends(DistanceJoint, _super);
  83004. function DistanceJoint(jointData) {
  83005. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83006. }
  83007. /**
  83008. * Update the predefined distance.
  83009. */
  83010. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83011. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83012. };
  83013. return DistanceJoint;
  83014. }(PhysicsJoint));
  83015. BABYLON.DistanceJoint = DistanceJoint;
  83016. var MotorEnabledJoint = /** @class */ (function (_super) {
  83017. __extends(MotorEnabledJoint, _super);
  83018. function MotorEnabledJoint(type, jointData) {
  83019. return _super.call(this, type, jointData) || this;
  83020. }
  83021. /**
  83022. * Set the motor values.
  83023. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83024. * @param {number} force the force to apply
  83025. * @param {number} maxForce max force for this motor.
  83026. */
  83027. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83028. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83029. };
  83030. /**
  83031. * Set the motor's limits.
  83032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83033. */
  83034. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83035. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83036. };
  83037. return MotorEnabledJoint;
  83038. }(PhysicsJoint));
  83039. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83040. /**
  83041. * This class represents a single hinge physics joint
  83042. */
  83043. var HingeJoint = /** @class */ (function (_super) {
  83044. __extends(HingeJoint, _super);
  83045. function HingeJoint(jointData) {
  83046. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83047. }
  83048. /**
  83049. * Set the motor values.
  83050. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83051. * @param {number} force the force to apply
  83052. * @param {number} maxForce max force for this motor.
  83053. */
  83054. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83055. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83056. };
  83057. /**
  83058. * Set the motor's limits.
  83059. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83060. */
  83061. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83062. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83063. };
  83064. return HingeJoint;
  83065. }(MotorEnabledJoint));
  83066. BABYLON.HingeJoint = HingeJoint;
  83067. /**
  83068. * This class represents a dual hinge physics joint (same as wheel joint)
  83069. */
  83070. var Hinge2Joint = /** @class */ (function (_super) {
  83071. __extends(Hinge2Joint, _super);
  83072. function Hinge2Joint(jointData) {
  83073. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83074. }
  83075. /**
  83076. * Set the motor values.
  83077. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83078. * @param {number} force the force to apply
  83079. * @param {number} maxForce max force for this motor.
  83080. * @param {motorIndex} the motor's index, 0 or 1.
  83081. */
  83082. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83083. if (motorIndex === void 0) { motorIndex = 0; }
  83084. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83085. };
  83086. /**
  83087. * Set the motor limits.
  83088. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83089. * @param {number} upperLimit the upper limit
  83090. * @param {number} lowerLimit lower limit
  83091. * @param {motorIndex} the motor's index, 0 or 1.
  83092. */
  83093. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83094. if (motorIndex === void 0) { motorIndex = 0; }
  83095. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83096. };
  83097. return Hinge2Joint;
  83098. }(MotorEnabledJoint));
  83099. BABYLON.Hinge2Joint = Hinge2Joint;
  83100. })(BABYLON || (BABYLON = {}));
  83101. //# sourceMappingURL=babylon.physicsJoint.js.map
  83102. var BABYLON;
  83103. (function (BABYLON) {
  83104. var PhysicsImpostor = /** @class */ (function () {
  83105. function PhysicsImpostor(object, type, _options, _scene) {
  83106. if (_options === void 0) { _options = { mass: 0 }; }
  83107. var _this = this;
  83108. this.object = object;
  83109. this.type = type;
  83110. this._options = _options;
  83111. this._scene = _scene;
  83112. this._bodyUpdateRequired = false;
  83113. this._onBeforePhysicsStepCallbacks = new Array();
  83114. this._onAfterPhysicsStepCallbacks = new Array();
  83115. this._onPhysicsCollideCallbacks = [];
  83116. this._deltaPosition = BABYLON.Vector3.Zero();
  83117. this._isDisposed = false;
  83118. //temp variables for parent rotation calculations
  83119. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83120. this._tmpQuat = new BABYLON.Quaternion();
  83121. this._tmpQuat2 = new BABYLON.Quaternion();
  83122. /**
  83123. * this function is executed by the physics engine.
  83124. */
  83125. this.beforeStep = function () {
  83126. if (!_this._physicsEngine) {
  83127. return;
  83128. }
  83129. _this.object.translate(_this._deltaPosition, -1);
  83130. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83131. _this.object.computeWorldMatrix(false);
  83132. if (_this.object.parent && _this.object.rotationQuaternion) {
  83133. _this.getParentsRotation();
  83134. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83135. }
  83136. else {
  83137. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83138. }
  83139. if (!_this._options.disableBidirectionalTransformation) {
  83140. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83141. }
  83142. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83143. func(_this);
  83144. });
  83145. };
  83146. /**
  83147. * this function is executed by the physics engine.
  83148. */
  83149. this.afterStep = function () {
  83150. if (!_this._physicsEngine) {
  83151. return;
  83152. }
  83153. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83154. func(_this);
  83155. });
  83156. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83157. // object has now its world rotation. needs to be converted to local.
  83158. if (_this.object.parent && _this.object.rotationQuaternion) {
  83159. _this.getParentsRotation();
  83160. _this._tmpQuat.conjugateInPlace();
  83161. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83162. }
  83163. // take the position set and make it the absolute position of this object.
  83164. _this.object.setAbsolutePosition(_this.object.position);
  83165. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83166. _this.object.translate(_this._deltaPosition, 1);
  83167. };
  83168. /**
  83169. * Legacy collision detection event support
  83170. */
  83171. this.onCollideEvent = null;
  83172. //event and body object due to cannon's event-based architecture.
  83173. this.onCollide = function (e) {
  83174. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83175. return;
  83176. }
  83177. if (!_this._physicsEngine) {
  83178. return;
  83179. }
  83180. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83181. if (otherImpostor) {
  83182. // Legacy collision detection event support
  83183. if (_this.onCollideEvent) {
  83184. _this.onCollideEvent(_this, otherImpostor);
  83185. }
  83186. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83187. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83188. }).forEach(function (obj) {
  83189. obj.callback(_this, otherImpostor);
  83190. });
  83191. }
  83192. };
  83193. //sanity check!
  83194. if (!this.object) {
  83195. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83196. return;
  83197. }
  83198. //legacy support for old syntax.
  83199. if (!this._scene && object.getScene) {
  83200. this._scene = object.getScene();
  83201. }
  83202. if (!this._scene) {
  83203. return;
  83204. }
  83205. this._physicsEngine = this._scene.getPhysicsEngine();
  83206. if (!this._physicsEngine) {
  83207. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83208. }
  83209. else {
  83210. //set the object's quaternion, if not set
  83211. if (!this.object.rotationQuaternion) {
  83212. if (this.object.rotation) {
  83213. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83214. }
  83215. else {
  83216. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83217. }
  83218. }
  83219. //default options params
  83220. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83221. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83222. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83223. this._joints = [];
  83224. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83225. if (!this.object.parent || this._options.ignoreParent) {
  83226. this._init();
  83227. }
  83228. else if (this.object.parent.physicsImpostor) {
  83229. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83230. }
  83231. }
  83232. }
  83233. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83234. get: function () {
  83235. return this._isDisposed;
  83236. },
  83237. enumerable: true,
  83238. configurable: true
  83239. });
  83240. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83241. get: function () {
  83242. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83243. },
  83244. set: function (value) {
  83245. this.setMass(value);
  83246. },
  83247. enumerable: true,
  83248. configurable: true
  83249. });
  83250. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83251. get: function () {
  83252. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83253. },
  83254. set: function (value) {
  83255. if (!this._physicsEngine) {
  83256. return;
  83257. }
  83258. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83259. },
  83260. enumerable: true,
  83261. configurable: true
  83262. });
  83263. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83264. get: function () {
  83265. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83266. },
  83267. set: function (value) {
  83268. if (!this._physicsEngine) {
  83269. return;
  83270. }
  83271. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83272. },
  83273. enumerable: true,
  83274. configurable: true
  83275. });
  83276. /**
  83277. * This function will completly initialize this impostor.
  83278. * It will create a new body - but only if this mesh has no parent.
  83279. * If it has, this impostor will not be used other than to define the impostor
  83280. * of the child mesh.
  83281. */
  83282. PhysicsImpostor.prototype._init = function () {
  83283. if (!this._physicsEngine) {
  83284. return;
  83285. }
  83286. this._physicsEngine.removeImpostor(this);
  83287. this.physicsBody = null;
  83288. this._parent = this._parent || this._getPhysicsParent();
  83289. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83290. this._physicsEngine.addImpostor(this);
  83291. }
  83292. };
  83293. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83294. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83295. var parentMesh = this.object.parent;
  83296. return parentMesh.physicsImpostor;
  83297. }
  83298. return null;
  83299. };
  83300. /**
  83301. * Should a new body be generated.
  83302. */
  83303. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83304. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83305. };
  83306. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83307. this.forceUpdate();
  83308. };
  83309. /**
  83310. * Force a regeneration of this or the parent's impostor's body.
  83311. * Use under cautious - This will remove all joints already implemented.
  83312. */
  83313. PhysicsImpostor.prototype.forceUpdate = function () {
  83314. this._init();
  83315. if (this.parent && !this._options.ignoreParent) {
  83316. this.parent.forceUpdate();
  83317. }
  83318. };
  83319. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83320. /*public get mesh(): AbstractMesh {
  83321. return this._mesh;
  83322. }*/
  83323. /**
  83324. * Gets the body that holds this impostor. Either its own, or its parent.
  83325. */
  83326. get: function () {
  83327. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83328. },
  83329. /**
  83330. * Set the physics body. Used mainly by the physics engine/plugin
  83331. */
  83332. set: function (physicsBody) {
  83333. if (this._physicsBody && this._physicsEngine) {
  83334. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83335. }
  83336. this._physicsBody = physicsBody;
  83337. this.resetUpdateFlags();
  83338. },
  83339. enumerable: true,
  83340. configurable: true
  83341. });
  83342. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83343. get: function () {
  83344. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83345. },
  83346. set: function (value) {
  83347. this._parent = value;
  83348. },
  83349. enumerable: true,
  83350. configurable: true
  83351. });
  83352. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83353. this._bodyUpdateRequired = false;
  83354. };
  83355. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83356. if (this.object.getBoundingInfo) {
  83357. var q = this.object.rotationQuaternion;
  83358. //reset rotation
  83359. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83360. //calculate the world matrix with no rotation
  83361. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83362. var boundingInfo = this.object.getBoundingInfo();
  83363. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83364. //bring back the rotation
  83365. this.object.rotationQuaternion = q;
  83366. //calculate the world matrix with the new rotation
  83367. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83368. return size;
  83369. }
  83370. else {
  83371. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83372. }
  83373. };
  83374. PhysicsImpostor.prototype.getObjectCenter = function () {
  83375. if (this.object.getBoundingInfo) {
  83376. var boundingInfo = this.object.getBoundingInfo();
  83377. return boundingInfo.boundingBox.centerWorld;
  83378. }
  83379. else {
  83380. return this.object.position;
  83381. }
  83382. };
  83383. /**
  83384. * Get a specific parametes from the options parameter.
  83385. */
  83386. PhysicsImpostor.prototype.getParam = function (paramName) {
  83387. return this._options[paramName];
  83388. };
  83389. /**
  83390. * Sets a specific parameter in the options given to the physics plugin
  83391. */
  83392. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83393. this._options[paramName] = value;
  83394. this._bodyUpdateRequired = true;
  83395. };
  83396. /**
  83397. * Specifically change the body's mass option. Won't recreate the physics body object
  83398. */
  83399. PhysicsImpostor.prototype.setMass = function (mass) {
  83400. if (this.getParam("mass") !== mass) {
  83401. this.setParam("mass", mass);
  83402. }
  83403. if (this._physicsEngine) {
  83404. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83405. }
  83406. };
  83407. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83408. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83409. };
  83410. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83411. if (this._physicsEngine) {
  83412. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83413. }
  83414. };
  83415. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83416. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83417. };
  83418. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83419. if (this._physicsEngine) {
  83420. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83421. }
  83422. };
  83423. /**
  83424. * Execute a function with the physics plugin native code.
  83425. * Provide a function the will have two variables - the world object and the physics body object.
  83426. */
  83427. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83428. if (this._physicsEngine) {
  83429. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83430. }
  83431. };
  83432. /**
  83433. * Register a function that will be executed before the physics world is stepping forward.
  83434. */
  83435. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83436. this._onBeforePhysicsStepCallbacks.push(func);
  83437. };
  83438. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83439. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83440. if (index > -1) {
  83441. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83442. }
  83443. else {
  83444. BABYLON.Tools.Warn("Function to remove was not found");
  83445. }
  83446. };
  83447. /**
  83448. * Register a function that will be executed after the physics step
  83449. */
  83450. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83451. this._onAfterPhysicsStepCallbacks.push(func);
  83452. };
  83453. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83454. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83455. if (index > -1) {
  83456. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83457. }
  83458. else {
  83459. BABYLON.Tools.Warn("Function to remove was not found");
  83460. }
  83461. };
  83462. /**
  83463. * register a function that will be executed when this impostor collides against a different body.
  83464. */
  83465. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83466. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83467. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83468. };
  83469. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83470. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83471. var index = -1;
  83472. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83473. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83474. // chcek the arrays match
  83475. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83476. return collidedAgainstList.indexOf(impostor) > -1;
  83477. });
  83478. if (sameList) {
  83479. index = idx;
  83480. }
  83481. return sameList;
  83482. }
  83483. return false;
  83484. });
  83485. if (found) {
  83486. this._onPhysicsCollideCallbacks.splice(index, 1);
  83487. }
  83488. else {
  83489. BABYLON.Tools.Warn("Function to remove was not found");
  83490. }
  83491. };
  83492. PhysicsImpostor.prototype.getParentsRotation = function () {
  83493. var parent = this.object.parent;
  83494. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83495. while (parent) {
  83496. if (parent.rotationQuaternion) {
  83497. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83498. }
  83499. else {
  83500. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83501. }
  83502. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83503. parent = parent.parent;
  83504. }
  83505. return this._tmpQuat;
  83506. };
  83507. /**
  83508. * Apply a force
  83509. */
  83510. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83511. if (this._physicsEngine) {
  83512. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83513. }
  83514. return this;
  83515. };
  83516. /**
  83517. * Apply an impulse
  83518. */
  83519. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83520. if (this._physicsEngine) {
  83521. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83522. }
  83523. return this;
  83524. };
  83525. /**
  83526. * A help function to create a joint.
  83527. */
  83528. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83529. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83530. this.addJoint(otherImpostor, joint);
  83531. return this;
  83532. };
  83533. /**
  83534. * Add a joint to this impostor with a different impostor.
  83535. */
  83536. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83537. this._joints.push({
  83538. otherImpostor: otherImpostor,
  83539. joint: joint
  83540. });
  83541. if (this._physicsEngine) {
  83542. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83543. }
  83544. return this;
  83545. };
  83546. /**
  83547. * Will keep this body still, in a sleep mode.
  83548. */
  83549. PhysicsImpostor.prototype.sleep = function () {
  83550. if (this._physicsEngine) {
  83551. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83552. }
  83553. return this;
  83554. };
  83555. /**
  83556. * Wake the body up.
  83557. */
  83558. PhysicsImpostor.prototype.wakeUp = function () {
  83559. if (this._physicsEngine) {
  83560. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83561. }
  83562. return this;
  83563. };
  83564. PhysicsImpostor.prototype.clone = function (newObject) {
  83565. if (!newObject)
  83566. return null;
  83567. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83568. };
  83569. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83570. var _this = this;
  83571. //no dispose if no physics engine is available.
  83572. if (!this._physicsEngine) {
  83573. return;
  83574. }
  83575. this._joints.forEach(function (j) {
  83576. if (_this._physicsEngine) {
  83577. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83578. }
  83579. });
  83580. //dispose the physics body
  83581. this._physicsEngine.removeImpostor(this);
  83582. if (this.parent) {
  83583. this.parent.forceUpdate();
  83584. }
  83585. else {
  83586. /*this._object.getChildMeshes().forEach(function(mesh) {
  83587. if (mesh.physicsImpostor) {
  83588. if (disposeChildren) {
  83589. mesh.physicsImpostor.dispose();
  83590. mesh.physicsImpostor = null;
  83591. }
  83592. }
  83593. })*/
  83594. }
  83595. this._isDisposed = true;
  83596. };
  83597. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83598. this._deltaPosition.copyFrom(position);
  83599. };
  83600. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83601. if (!this._deltaRotation) {
  83602. this._deltaRotation = new BABYLON.Quaternion();
  83603. }
  83604. this._deltaRotation.copyFrom(rotation);
  83605. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83606. };
  83607. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83608. if (this._physicsEngine) {
  83609. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83610. }
  83611. return this;
  83612. };
  83613. PhysicsImpostor.prototype.getRadius = function () {
  83614. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83615. };
  83616. /**
  83617. * Sync a bone with this impostor
  83618. * @param bone The bone to sync to the impostor.
  83619. * @param boneMesh The mesh that the bone is influencing.
  83620. * @param jointPivot The pivot of the joint / bone in local space.
  83621. * @param distToJoint Optional distance from the impostor to the joint.
  83622. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83623. */
  83624. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83625. var tempVec = PhysicsImpostor._tmpVecs[0];
  83626. var mesh = this.object;
  83627. if (mesh.rotationQuaternion) {
  83628. if (adjustRotation) {
  83629. var tempQuat = PhysicsImpostor._tmpQuat;
  83630. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83631. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83632. }
  83633. else {
  83634. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83635. }
  83636. }
  83637. tempVec.x = 0;
  83638. tempVec.y = 0;
  83639. tempVec.z = 0;
  83640. if (jointPivot) {
  83641. tempVec.x = jointPivot.x;
  83642. tempVec.y = jointPivot.y;
  83643. tempVec.z = jointPivot.z;
  83644. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83645. if (distToJoint === undefined || distToJoint === null) {
  83646. distToJoint = jointPivot.length();
  83647. }
  83648. tempVec.x *= distToJoint;
  83649. tempVec.y *= distToJoint;
  83650. tempVec.z *= distToJoint;
  83651. }
  83652. if (bone.getParent()) {
  83653. tempVec.addInPlace(mesh.getAbsolutePosition());
  83654. bone.setAbsolutePosition(tempVec, boneMesh);
  83655. }
  83656. else {
  83657. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83658. boneMesh.position.x -= tempVec.x;
  83659. boneMesh.position.y -= tempVec.y;
  83660. boneMesh.position.z -= tempVec.z;
  83661. }
  83662. };
  83663. /**
  83664. * Sync impostor to a bone
  83665. * @param bone The bone that the impostor will be synced to.
  83666. * @param boneMesh The mesh that the bone is influencing.
  83667. * @param jointPivot The pivot of the joint / bone in local space.
  83668. * @param distToJoint Optional distance from the impostor to the joint.
  83669. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83670. * @param boneAxis Optional vector3 axis the bone is aligned with
  83671. */
  83672. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83673. var mesh = this.object;
  83674. if (mesh.rotationQuaternion) {
  83675. if (adjustRotation) {
  83676. var tempQuat = PhysicsImpostor._tmpQuat;
  83677. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83678. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83679. }
  83680. else {
  83681. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83682. }
  83683. }
  83684. var pos = PhysicsImpostor._tmpVecs[0];
  83685. var boneDir = PhysicsImpostor._tmpVecs[1];
  83686. if (!boneAxis) {
  83687. boneAxis = PhysicsImpostor._tmpVecs[2];
  83688. boneAxis.x = 0;
  83689. boneAxis.y = 1;
  83690. boneAxis.z = 0;
  83691. }
  83692. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83693. bone.getAbsolutePositionToRef(boneMesh, pos);
  83694. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83695. distToJoint = jointPivot.length();
  83696. }
  83697. if (distToJoint !== undefined && distToJoint !== null) {
  83698. pos.x += boneDir.x * distToJoint;
  83699. pos.y += boneDir.y * distToJoint;
  83700. pos.z += boneDir.z * distToJoint;
  83701. }
  83702. mesh.setAbsolutePosition(pos);
  83703. };
  83704. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83705. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83706. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83707. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83708. //Impostor types
  83709. PhysicsImpostor.NoImpostor = 0;
  83710. PhysicsImpostor.SphereImpostor = 1;
  83711. PhysicsImpostor.BoxImpostor = 2;
  83712. PhysicsImpostor.PlaneImpostor = 3;
  83713. PhysicsImpostor.MeshImpostor = 4;
  83714. PhysicsImpostor.CylinderImpostor = 7;
  83715. PhysicsImpostor.ParticleImpostor = 8;
  83716. PhysicsImpostor.HeightmapImpostor = 9;
  83717. return PhysicsImpostor;
  83718. }());
  83719. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83720. })(BABYLON || (BABYLON = {}));
  83721. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83722. var BABYLON;
  83723. (function (BABYLON) {
  83724. var PhysicsEngine = /** @class */ (function () {
  83725. function PhysicsEngine(gravity, _physicsPlugin) {
  83726. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83727. this._physicsPlugin = _physicsPlugin;
  83728. //new methods and parameters
  83729. this._impostors = [];
  83730. this._joints = [];
  83731. if (!this._physicsPlugin.isSupported()) {
  83732. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83733. + "Please make sure it is included.");
  83734. }
  83735. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83736. this.setGravity(gravity);
  83737. this.setTimeStep();
  83738. }
  83739. PhysicsEngine.prototype.setGravity = function (gravity) {
  83740. this.gravity = gravity;
  83741. this._physicsPlugin.setGravity(this.gravity);
  83742. };
  83743. /**
  83744. * Set the time step of the physics engine.
  83745. * default is 1/60.
  83746. * To slow it down, enter 1/600 for example.
  83747. * To speed it up, 1/30
  83748. * @param {number} newTimeStep the new timestep to apply to this world.
  83749. */
  83750. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83751. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83752. this._physicsPlugin.setTimeStep(newTimeStep);
  83753. };
  83754. /**
  83755. * Get the time step of the physics engine.
  83756. */
  83757. PhysicsEngine.prototype.getTimeStep = function () {
  83758. return this._physicsPlugin.getTimeStep();
  83759. };
  83760. PhysicsEngine.prototype.dispose = function () {
  83761. this._impostors.forEach(function (impostor) {
  83762. impostor.dispose();
  83763. });
  83764. this._physicsPlugin.dispose();
  83765. };
  83766. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83767. return this._physicsPlugin.name;
  83768. };
  83769. /**
  83770. * Adding a new impostor for the impostor tracking.
  83771. * This will be done by the impostor itself.
  83772. * @param {PhysicsImpostor} impostor the impostor to add
  83773. */
  83774. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83775. impostor.uniqueId = this._impostors.push(impostor);
  83776. //if no parent, generate the body
  83777. if (!impostor.parent) {
  83778. this._physicsPlugin.generatePhysicsBody(impostor);
  83779. }
  83780. };
  83781. /**
  83782. * Remove an impostor from the engine.
  83783. * This impostor and its mesh will not longer be updated by the physics engine.
  83784. * @param {PhysicsImpostor} impostor the impostor to remove
  83785. */
  83786. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83787. var index = this._impostors.indexOf(impostor);
  83788. if (index > -1) {
  83789. var removed = this._impostors.splice(index, 1);
  83790. //Is it needed?
  83791. if (removed.length) {
  83792. //this will also remove it from the world.
  83793. removed[0].physicsBody = null;
  83794. }
  83795. }
  83796. };
  83797. /**
  83798. * Add a joint to the physics engine
  83799. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83800. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83801. * @param {PhysicsJoint} the joint that will connect both impostors.
  83802. */
  83803. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83804. var impostorJoint = {
  83805. mainImpostor: mainImpostor,
  83806. connectedImpostor: connectedImpostor,
  83807. joint: joint
  83808. };
  83809. joint.physicsPlugin = this._physicsPlugin;
  83810. this._joints.push(impostorJoint);
  83811. this._physicsPlugin.generateJoint(impostorJoint);
  83812. };
  83813. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83814. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83815. return (impostorJoint.connectedImpostor === connectedImpostor
  83816. && impostorJoint.joint === joint
  83817. && impostorJoint.mainImpostor === mainImpostor);
  83818. });
  83819. if (matchingJoints.length) {
  83820. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83821. //TODO remove it from the list as well
  83822. }
  83823. };
  83824. /**
  83825. * Called by the scene. no need to call it.
  83826. */
  83827. PhysicsEngine.prototype._step = function (delta) {
  83828. var _this = this;
  83829. //check if any mesh has no body / requires an update
  83830. this._impostors.forEach(function (impostor) {
  83831. if (impostor.isBodyInitRequired()) {
  83832. _this._physicsPlugin.generatePhysicsBody(impostor);
  83833. }
  83834. });
  83835. if (delta > 0.1) {
  83836. delta = 0.1;
  83837. }
  83838. else if (delta <= 0) {
  83839. delta = 1.0 / 60.0;
  83840. }
  83841. this._physicsPlugin.executeStep(delta, this._impostors);
  83842. };
  83843. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83844. return this._physicsPlugin;
  83845. };
  83846. PhysicsEngine.prototype.getImpostors = function () {
  83847. return this._impostors;
  83848. };
  83849. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83850. for (var i = 0; i < this._impostors.length; ++i) {
  83851. if (this._impostors[i].object === object) {
  83852. return this._impostors[i];
  83853. }
  83854. }
  83855. return null;
  83856. };
  83857. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83858. for (var i = 0; i < this._impostors.length; ++i) {
  83859. if (this._impostors[i].physicsBody === body) {
  83860. return this._impostors[i];
  83861. }
  83862. }
  83863. return null;
  83864. };
  83865. // Statics
  83866. PhysicsEngine.Epsilon = 0.001;
  83867. return PhysicsEngine;
  83868. }());
  83869. BABYLON.PhysicsEngine = PhysicsEngine;
  83870. })(BABYLON || (BABYLON = {}));
  83871. //# sourceMappingURL=babylon.physicsEngine.js.map
  83872. var BABYLON;
  83873. (function (BABYLON) {
  83874. var PhysicsHelper = /** @class */ (function () {
  83875. function PhysicsHelper(scene) {
  83876. this._scene = scene;
  83877. this._physicsEngine = this._scene.getPhysicsEngine();
  83878. if (!this._physicsEngine) {
  83879. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83880. }
  83881. }
  83882. /**
  83883. * @param {Vector3} origin the origin of the explosion
  83884. * @param {number} radius the explosion radius
  83885. * @param {number} strength the explosion strength
  83886. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83887. */
  83888. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83889. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83890. if (!this._physicsEngine) {
  83891. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83892. return null;
  83893. }
  83894. var impostors = this._physicsEngine.getImpostors();
  83895. if (impostors.length === 0) {
  83896. return null;
  83897. }
  83898. var event = new PhysicsRadialExplosionEvent(this._scene);
  83899. impostors.forEach(function (impostor) {
  83900. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83901. if (!impostorForceAndContactPoint) {
  83902. return;
  83903. }
  83904. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83905. });
  83906. event.dispose(false);
  83907. return event;
  83908. };
  83909. /**
  83910. * @param {Vector3} origin the origin of the explosion
  83911. * @param {number} radius the explosion radius
  83912. * @param {number} strength the explosion strength
  83913. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83914. */
  83915. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83916. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83917. if (!this._physicsEngine) {
  83918. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83919. return null;
  83920. }
  83921. var impostors = this._physicsEngine.getImpostors();
  83922. if (impostors.length === 0) {
  83923. return null;
  83924. }
  83925. var event = new PhysicsRadialExplosionEvent(this._scene);
  83926. impostors.forEach(function (impostor) {
  83927. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83928. if (!impostorForceAndContactPoint) {
  83929. return;
  83930. }
  83931. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83932. });
  83933. event.dispose(false);
  83934. return event;
  83935. };
  83936. /**
  83937. * @param {Vector3} origin the origin of the explosion
  83938. * @param {number} radius the explosion radius
  83939. * @param {number} strength the explosion strength
  83940. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83941. */
  83942. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83943. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83944. if (!this._physicsEngine) {
  83945. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83946. return null;
  83947. }
  83948. var impostors = this._physicsEngine.getImpostors();
  83949. if (impostors.length === 0) {
  83950. return null;
  83951. }
  83952. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83953. event.dispose(false);
  83954. return event;
  83955. };
  83956. /**
  83957. * @param {Vector3} origin the origin of the updraft
  83958. * @param {number} radius the radius of the updraft
  83959. * @param {number} strength the strength of the updraft
  83960. * @param {number} height the height of the updraft
  83961. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83962. */
  83963. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83964. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83965. if (!this._physicsEngine) {
  83966. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83967. return null;
  83968. }
  83969. if (this._physicsEngine.getImpostors().length === 0) {
  83970. return null;
  83971. }
  83972. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83973. event.dispose(false);
  83974. return event;
  83975. };
  83976. /**
  83977. * @param {Vector3} origin the of the vortex
  83978. * @param {number} radius the radius of the vortex
  83979. * @param {number} strength the strength of the vortex
  83980. * @param {number} height the height of the vortex
  83981. */
  83982. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83983. if (!this._physicsEngine) {
  83984. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83985. return null;
  83986. }
  83987. if (this._physicsEngine.getImpostors().length === 0) {
  83988. return null;
  83989. }
  83990. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83991. event.dispose(false);
  83992. return event;
  83993. };
  83994. return PhysicsHelper;
  83995. }());
  83996. BABYLON.PhysicsHelper = PhysicsHelper;
  83997. /***** Radial explosion *****/
  83998. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83999. function PhysicsRadialExplosionEvent(scene) {
  84000. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84001. this._rays = [];
  84002. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84003. this._scene = scene;
  84004. }
  84005. /**
  84006. * Returns the data related to the radial explosion event (sphere & rays).
  84007. * @returns {PhysicsRadialExplosionEventData}
  84008. */
  84009. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84010. this._dataFetched = true;
  84011. return {
  84012. sphere: this._sphere,
  84013. rays: this._rays,
  84014. };
  84015. };
  84016. /**
  84017. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84018. * @param impostor
  84019. * @param {Vector3} origin the origin of the explosion
  84020. * @param {number} radius the explosion radius
  84021. * @param {number} strength the explosion strength
  84022. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84023. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84024. */
  84025. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84026. if (impostor.mass === 0) {
  84027. return null;
  84028. }
  84029. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84030. return null;
  84031. }
  84032. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84033. return null;
  84034. }
  84035. var impostorObjectCenter = impostor.getObjectCenter();
  84036. var direction = impostorObjectCenter.subtract(origin);
  84037. var ray = new BABYLON.Ray(origin, direction, radius);
  84038. this._rays.push(ray);
  84039. var hit = ray.intersectsMesh(impostor.object);
  84040. var contactPoint = hit.pickedPoint;
  84041. if (!contactPoint) {
  84042. return null;
  84043. }
  84044. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84045. if (distanceFromOrigin > radius) {
  84046. return null;
  84047. }
  84048. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84049. ? strength
  84050. : strength * (1 - (distanceFromOrigin / radius));
  84051. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84052. return { force: force, contactPoint: contactPoint };
  84053. };
  84054. /**
  84055. * Disposes the sphere.
  84056. * @param {bolean} force
  84057. */
  84058. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84059. var _this = this;
  84060. if (force === void 0) { force = true; }
  84061. if (force) {
  84062. this._sphere.dispose();
  84063. }
  84064. else {
  84065. setTimeout(function () {
  84066. if (!_this._dataFetched) {
  84067. _this._sphere.dispose();
  84068. }
  84069. }, 0);
  84070. }
  84071. };
  84072. /*** Helpers ***/
  84073. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84074. if (!this._sphere) {
  84075. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84076. this._sphere.isVisible = false;
  84077. }
  84078. };
  84079. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84080. var impostorObject = impostor.object;
  84081. this._prepareSphere();
  84082. this._sphere.position = origin;
  84083. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84084. this._sphere._updateBoundingInfo();
  84085. this._sphere.computeWorldMatrix(true);
  84086. return this._sphere.intersectsMesh(impostorObject, true);
  84087. };
  84088. return PhysicsRadialExplosionEvent;
  84089. }());
  84090. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84091. /***** Gravitational Field *****/
  84092. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84093. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84094. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84095. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84096. this._physicsHelper = physicsHelper;
  84097. this._scene = scene;
  84098. this._origin = origin;
  84099. this._radius = radius;
  84100. this._strength = strength;
  84101. this._falloff = falloff;
  84102. this._tickCallback = this._tick.bind(this);
  84103. }
  84104. /**
  84105. * Returns the data related to the gravitational field event (sphere).
  84106. * @returns {PhysicsGravitationalFieldEventData}
  84107. */
  84108. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84109. this._dataFetched = true;
  84110. return {
  84111. sphere: this._sphere,
  84112. };
  84113. };
  84114. /**
  84115. * Enables the gravitational field.
  84116. */
  84117. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84118. this._tickCallback.call(this);
  84119. this._scene.registerBeforeRender(this._tickCallback);
  84120. };
  84121. /**
  84122. * Disables the gravitational field.
  84123. */
  84124. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84125. this._scene.unregisterBeforeRender(this._tickCallback);
  84126. };
  84127. /**
  84128. * Disposes the sphere.
  84129. * @param {bolean} force
  84130. */
  84131. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84132. var _this = this;
  84133. if (force === void 0) { force = true; }
  84134. if (force) {
  84135. this._sphere.dispose();
  84136. }
  84137. else {
  84138. setTimeout(function () {
  84139. if (!_this._dataFetched) {
  84140. _this._sphere.dispose();
  84141. }
  84142. }, 0);
  84143. }
  84144. };
  84145. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84146. // Since the params won't change, we fetch the event only once
  84147. if (this._sphere) {
  84148. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84149. }
  84150. else {
  84151. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84152. if (radialExplosionEvent) {
  84153. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84154. }
  84155. }
  84156. };
  84157. return PhysicsGravitationalFieldEvent;
  84158. }());
  84159. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84160. /***** Updraft *****/
  84161. var PhysicsUpdraftEvent = /** @class */ (function () {
  84162. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84163. this._scene = _scene;
  84164. this._origin = _origin;
  84165. this._radius = _radius;
  84166. this._strength = _strength;
  84167. this._height = _height;
  84168. this._updraftMode = _updraftMode;
  84169. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84170. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84171. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84172. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84173. this._physicsEngine = this._scene.getPhysicsEngine();
  84174. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84175. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84176. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84177. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84178. }
  84179. this._tickCallback = this._tick.bind(this);
  84180. }
  84181. /**
  84182. * Returns the data related to the updraft event (cylinder).
  84183. * @returns {PhysicsUpdraftEventData}
  84184. */
  84185. PhysicsUpdraftEvent.prototype.getData = function () {
  84186. this._dataFetched = true;
  84187. return {
  84188. cylinder: this._cylinder,
  84189. };
  84190. };
  84191. /**
  84192. * Enables the updraft.
  84193. */
  84194. PhysicsUpdraftEvent.prototype.enable = function () {
  84195. this._tickCallback.call(this);
  84196. this._scene.registerBeforeRender(this._tickCallback);
  84197. };
  84198. /**
  84199. * Disables the cortex.
  84200. */
  84201. PhysicsUpdraftEvent.prototype.disable = function () {
  84202. this._scene.unregisterBeforeRender(this._tickCallback);
  84203. };
  84204. /**
  84205. * Disposes the sphere.
  84206. * @param {bolean} force
  84207. */
  84208. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84209. var _this = this;
  84210. if (force === void 0) { force = true; }
  84211. if (force) {
  84212. this._cylinder.dispose();
  84213. }
  84214. else {
  84215. setTimeout(function () {
  84216. if (!_this._dataFetched) {
  84217. _this._cylinder.dispose();
  84218. }
  84219. }, 0);
  84220. }
  84221. };
  84222. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84223. if (impostor.mass === 0) {
  84224. return null;
  84225. }
  84226. if (!this._intersectsWithCylinder(impostor)) {
  84227. return null;
  84228. }
  84229. var impostorObjectCenter = impostor.getObjectCenter();
  84230. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84231. var direction = this._originDirection;
  84232. }
  84233. else {
  84234. var direction = impostorObjectCenter.subtract(this._originTop);
  84235. }
  84236. var multiplier = this._strength * -1;
  84237. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84238. return { force: force, contactPoint: impostorObjectCenter };
  84239. };
  84240. PhysicsUpdraftEvent.prototype._tick = function () {
  84241. var _this = this;
  84242. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84243. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84244. if (!impostorForceAndContactPoint) {
  84245. return;
  84246. }
  84247. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84248. });
  84249. };
  84250. /*** Helpers ***/
  84251. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84252. if (!this._cylinder) {
  84253. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84254. height: this._height,
  84255. diameter: this._radius * 2,
  84256. }, this._scene);
  84257. this._cylinder.isVisible = false;
  84258. }
  84259. };
  84260. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84261. var impostorObject = impostor.object;
  84262. this._prepareCylinder();
  84263. this._cylinder.position = this._cylinderPosition;
  84264. return this._cylinder.intersectsMesh(impostorObject, true);
  84265. };
  84266. return PhysicsUpdraftEvent;
  84267. }());
  84268. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84269. /***** Vortex *****/
  84270. var PhysicsVortexEvent = /** @class */ (function () {
  84271. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84272. this._scene = _scene;
  84273. this._origin = _origin;
  84274. this._radius = _radius;
  84275. this._strength = _strength;
  84276. this._height = _height;
  84277. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84278. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84279. this._updraftMultiplier = 0.02;
  84280. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84281. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84282. this._physicsEngine = this._scene.getPhysicsEngine();
  84283. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84284. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84285. this._tickCallback = this._tick.bind(this);
  84286. }
  84287. /**
  84288. * Returns the data related to the vortex event (cylinder).
  84289. * @returns {PhysicsVortexEventData}
  84290. */
  84291. PhysicsVortexEvent.prototype.getData = function () {
  84292. this._dataFetched = true;
  84293. return {
  84294. cylinder: this._cylinder,
  84295. };
  84296. };
  84297. /**
  84298. * Enables the vortex.
  84299. */
  84300. PhysicsVortexEvent.prototype.enable = function () {
  84301. this._tickCallback.call(this);
  84302. this._scene.registerBeforeRender(this._tickCallback);
  84303. };
  84304. /**
  84305. * Disables the cortex.
  84306. */
  84307. PhysicsVortexEvent.prototype.disable = function () {
  84308. this._scene.unregisterBeforeRender(this._tickCallback);
  84309. };
  84310. /**
  84311. * Disposes the sphere.
  84312. * @param {bolean} force
  84313. */
  84314. PhysicsVortexEvent.prototype.dispose = function (force) {
  84315. var _this = this;
  84316. if (force === void 0) { force = true; }
  84317. if (force) {
  84318. this._cylinder.dispose();
  84319. }
  84320. else {
  84321. setTimeout(function () {
  84322. if (!_this._dataFetched) {
  84323. _this._cylinder.dispose();
  84324. }
  84325. }, 0);
  84326. }
  84327. };
  84328. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84329. if (impostor.mass === 0) {
  84330. return null;
  84331. }
  84332. if (!this._intersectsWithCylinder(impostor)) {
  84333. return null;
  84334. }
  84335. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84336. return null;
  84337. }
  84338. var impostorObjectCenter = impostor.getObjectCenter();
  84339. 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)
  84340. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84341. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84342. var hit = ray.intersectsMesh(impostor.object);
  84343. var contactPoint = hit.pickedPoint;
  84344. if (!contactPoint) {
  84345. return null;
  84346. }
  84347. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84348. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84349. var directionToOrigin = contactPoint.normalize();
  84350. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84351. directionToOrigin = directionToOrigin.negate();
  84352. }
  84353. // TODO: find a more physically based solution
  84354. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84355. var forceX = directionToOrigin.x * this._strength / 8;
  84356. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84357. var forceZ = directionToOrigin.z * this._strength / 8;
  84358. }
  84359. else {
  84360. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84361. var forceY = this._originTop.y * this._updraftMultiplier;
  84362. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84363. }
  84364. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84365. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84366. return { force: force, contactPoint: impostorObjectCenter };
  84367. };
  84368. PhysicsVortexEvent.prototype._tick = function () {
  84369. var _this = this;
  84370. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84371. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84372. if (!impostorForceAndContactPoint) {
  84373. return;
  84374. }
  84375. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84376. });
  84377. };
  84378. /*** Helpers ***/
  84379. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84380. if (!this._cylinder) {
  84381. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84382. height: this._height,
  84383. diameter: this._radius * 2,
  84384. }, this._scene);
  84385. this._cylinder.isVisible = false;
  84386. }
  84387. };
  84388. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84389. var impostorObject = impostor.object;
  84390. this._prepareCylinder();
  84391. this._cylinder.position = this._cylinderPosition;
  84392. return this._cylinder.intersectsMesh(impostorObject, true);
  84393. };
  84394. return PhysicsVortexEvent;
  84395. }());
  84396. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84397. /***** Enums *****/
  84398. /**
  84399. * The strenght of the force in correspondence to the distance of the affected object
  84400. */
  84401. var PhysicsRadialImpulseFalloff;
  84402. (function (PhysicsRadialImpulseFalloff) {
  84403. /** Defines that impulse is constant in strength across it's whole radius */
  84404. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84405. /** DEfines that impulse gets weaker if it's further from the origin */
  84406. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84407. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84408. /**
  84409. * The strenght of the force in correspondence to the distance of the affected object
  84410. */
  84411. var PhysicsUpdraftMode;
  84412. (function (PhysicsUpdraftMode) {
  84413. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84414. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84415. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84416. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84417. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84418. })(BABYLON || (BABYLON = {}));
  84419. //# sourceMappingURL=babylon.physicsHelper.js.map
  84420. var BABYLON;
  84421. (function (BABYLON) {
  84422. var CannonJSPlugin = /** @class */ (function () {
  84423. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84424. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84425. if (iterations === void 0) { iterations = 10; }
  84426. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84427. this.name = "CannonJSPlugin";
  84428. this._physicsMaterials = new Array();
  84429. this._fixedTimeStep = 1 / 60;
  84430. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84431. this.BJSCANNON = CANNON;
  84432. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84433. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84434. this._tmpPosition = BABYLON.Vector3.Zero();
  84435. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84436. this._tmpUnityRotation = new BABYLON.Quaternion();
  84437. if (!this.isSupported()) {
  84438. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84439. return;
  84440. }
  84441. this._extendNamespace();
  84442. this.world = new this.BJSCANNON.World();
  84443. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84444. this.world.solver.iterations = iterations;
  84445. }
  84446. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84447. this.world.gravity.copy(gravity);
  84448. };
  84449. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84450. this._fixedTimeStep = timeStep;
  84451. };
  84452. CannonJSPlugin.prototype.getTimeStep = function () {
  84453. return this._fixedTimeStep;
  84454. };
  84455. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84456. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84457. };
  84458. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84459. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84460. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84461. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84462. };
  84463. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84464. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84465. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84466. impostor.physicsBody.applyForce(impulse, worldPoint);
  84467. };
  84468. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84469. //parent-child relationship. Does this impostor has a parent impostor?
  84470. if (impostor.parent) {
  84471. if (impostor.physicsBody) {
  84472. this.removePhysicsBody(impostor);
  84473. //TODO is that needed?
  84474. impostor.forceUpdate();
  84475. }
  84476. return;
  84477. }
  84478. //should a new body be created for this impostor?
  84479. if (impostor.isBodyInitRequired()) {
  84480. var shape = this._createShape(impostor);
  84481. //unregister events, if body is being changed
  84482. var oldBody = impostor.physicsBody;
  84483. if (oldBody) {
  84484. this.removePhysicsBody(impostor);
  84485. }
  84486. //create the body and material
  84487. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84488. var bodyCreationObject = {
  84489. mass: impostor.getParam("mass"),
  84490. material: material
  84491. };
  84492. // A simple extend, in case native options were used.
  84493. var nativeOptions = impostor.getParam("nativeOptions");
  84494. for (var key in nativeOptions) {
  84495. if (nativeOptions.hasOwnProperty(key)) {
  84496. bodyCreationObject[key] = nativeOptions[key];
  84497. }
  84498. }
  84499. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84500. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84501. this.world.addEventListener("preStep", impostor.beforeStep);
  84502. this.world.addEventListener("postStep", impostor.afterStep);
  84503. impostor.physicsBody.addShape(shape);
  84504. this.world.add(impostor.physicsBody);
  84505. //try to keep the body moving in the right direction by taking old properties.
  84506. //Should be tested!
  84507. if (oldBody) {
  84508. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84509. impostor.physicsBody[param].copy(oldBody[param]);
  84510. });
  84511. }
  84512. this._processChildMeshes(impostor);
  84513. }
  84514. //now update the body's transformation
  84515. this._updatePhysicsBodyTransformation(impostor);
  84516. };
  84517. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84518. var _this = this;
  84519. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84520. var currentRotation = mainImpostor.object.rotationQuaternion;
  84521. if (meshChildren.length) {
  84522. var processMesh = function (localPosition, mesh) {
  84523. if (!currentRotation || !mesh.rotationQuaternion) {
  84524. return;
  84525. }
  84526. var childImpostor = mesh.getPhysicsImpostor();
  84527. if (childImpostor) {
  84528. var parent = childImpostor.parent;
  84529. if (parent !== mainImpostor) {
  84530. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84531. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84532. if (childImpostor.physicsBody) {
  84533. _this.removePhysicsBody(childImpostor);
  84534. childImpostor.physicsBody = null;
  84535. }
  84536. childImpostor.parent = mainImpostor;
  84537. childImpostor.resetUpdateFlags();
  84538. 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));
  84539. //Add the mass of the children.
  84540. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84541. }
  84542. }
  84543. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84544. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84545. };
  84546. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84547. }
  84548. };
  84549. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84550. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84551. this.world.removeEventListener("preStep", impostor.beforeStep);
  84552. this.world.removeEventListener("postStep", impostor.afterStep);
  84553. this.world.remove(impostor.physicsBody);
  84554. };
  84555. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84556. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84557. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84558. if (!mainBody || !connectedBody) {
  84559. return;
  84560. }
  84561. var constraint;
  84562. var jointData = impostorJoint.joint.jointData;
  84563. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84564. var constraintData = {
  84565. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84566. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84567. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84568. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84569. maxForce: jointData.nativeParams.maxForce,
  84570. collideConnected: !!jointData.collision
  84571. };
  84572. switch (impostorJoint.joint.type) {
  84573. case BABYLON.PhysicsJoint.HingeJoint:
  84574. case BABYLON.PhysicsJoint.Hinge2Joint:
  84575. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84576. break;
  84577. case BABYLON.PhysicsJoint.DistanceJoint:
  84578. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84579. break;
  84580. case BABYLON.PhysicsJoint.SpringJoint:
  84581. var springData = jointData;
  84582. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84583. restLength: springData.length,
  84584. stiffness: springData.stiffness,
  84585. damping: springData.damping,
  84586. localAnchorA: constraintData.pivotA,
  84587. localAnchorB: constraintData.pivotB
  84588. });
  84589. break;
  84590. case BABYLON.PhysicsJoint.LockJoint:
  84591. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84592. break;
  84593. case BABYLON.PhysicsJoint.PointToPointJoint:
  84594. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84595. default:
  84596. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84597. break;
  84598. }
  84599. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84600. constraint.collideConnected = !!jointData.collision;
  84601. impostorJoint.joint.physicsJoint = constraint;
  84602. //don't add spring as constraint, as it is not one.
  84603. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84604. this.world.addConstraint(constraint);
  84605. }
  84606. else {
  84607. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84608. constraint.applyForce();
  84609. });
  84610. }
  84611. };
  84612. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84613. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84614. };
  84615. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84616. var index;
  84617. var mat;
  84618. for (index = 0; index < this._physicsMaterials.length; index++) {
  84619. mat = this._physicsMaterials[index];
  84620. if (mat.friction === friction && mat.restitution === restitution) {
  84621. return mat;
  84622. }
  84623. }
  84624. var currentMat = new this.BJSCANNON.Material(name);
  84625. currentMat.friction = friction;
  84626. currentMat.restitution = restitution;
  84627. this._physicsMaterials.push(currentMat);
  84628. return currentMat;
  84629. };
  84630. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84631. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84632. };
  84633. CannonJSPlugin.prototype._createShape = function (impostor) {
  84634. var object = impostor.object;
  84635. var returnValue;
  84636. var extendSize = impostor.getObjectExtendSize();
  84637. switch (impostor.type) {
  84638. case BABYLON.PhysicsImpostor.SphereImpostor:
  84639. var radiusX = extendSize.x;
  84640. var radiusY = extendSize.y;
  84641. var radiusZ = extendSize.z;
  84642. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84643. break;
  84644. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84645. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84646. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84647. break;
  84648. case BABYLON.PhysicsImpostor.BoxImpostor:
  84649. var box = extendSize.scale(0.5);
  84650. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84651. break;
  84652. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84653. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84654. returnValue = new this.BJSCANNON.Plane();
  84655. break;
  84656. case BABYLON.PhysicsImpostor.MeshImpostor:
  84657. // should transform the vertex data to world coordinates!!
  84658. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84659. var rawFaces = object.getIndices ? object.getIndices() : [];
  84660. if (!rawVerts)
  84661. return;
  84662. // get only scale! so the object could transform correctly.
  84663. var oldPosition = object.position.clone();
  84664. var oldRotation = object.rotation && object.rotation.clone();
  84665. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84666. object.position.copyFromFloats(0, 0, 0);
  84667. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84668. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84669. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84670. var transform = object.computeWorldMatrix(true);
  84671. // convert rawVerts to object space
  84672. var temp = new Array();
  84673. var index;
  84674. for (index = 0; index < rawVerts.length; index += 3) {
  84675. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84676. }
  84677. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84678. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84679. //now set back the transformation!
  84680. object.position.copyFrom(oldPosition);
  84681. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84682. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84683. break;
  84684. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84685. var oldPosition2 = object.position.clone();
  84686. var oldRotation2 = object.rotation && object.rotation.clone();
  84687. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84688. object.position.copyFromFloats(0, 0, 0);
  84689. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84690. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84691. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84692. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84693. returnValue = this._createHeightmap(object);
  84694. object.position.copyFrom(oldPosition2);
  84695. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84696. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84697. object.computeWorldMatrix(true);
  84698. break;
  84699. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84700. returnValue = new this.BJSCANNON.Particle();
  84701. break;
  84702. }
  84703. return returnValue;
  84704. };
  84705. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84706. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84707. var transform = object.computeWorldMatrix(true);
  84708. // convert rawVerts to object space
  84709. var temp = new Array();
  84710. var index;
  84711. for (index = 0; index < pos.length; index += 3) {
  84712. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84713. }
  84714. pos = temp;
  84715. var matrix = new Array();
  84716. //For now pointDepth will not be used and will be automatically calculated.
  84717. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84718. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84719. var boundingInfo = object.getBoundingInfo();
  84720. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84721. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84722. var elementSize = dim * 2 / arraySize;
  84723. for (var i = 0; i < pos.length; i = i + 3) {
  84724. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84725. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84726. var y = -pos[i + 2] + minY;
  84727. if (!matrix[x]) {
  84728. matrix[x] = [];
  84729. }
  84730. if (!matrix[x][z]) {
  84731. matrix[x][z] = y;
  84732. }
  84733. matrix[x][z] = Math.max(y, matrix[x][z]);
  84734. }
  84735. for (var x = 0; x <= arraySize; ++x) {
  84736. if (!matrix[x]) {
  84737. var loc = 1;
  84738. while (!matrix[(x + loc) % arraySize]) {
  84739. loc++;
  84740. }
  84741. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84742. //console.log("missing x", x);
  84743. }
  84744. for (var z = 0; z <= arraySize; ++z) {
  84745. if (!matrix[x][z]) {
  84746. var loc = 1;
  84747. var newValue;
  84748. while (newValue === undefined) {
  84749. newValue = matrix[x][(z + loc++) % arraySize];
  84750. }
  84751. matrix[x][z] = newValue;
  84752. }
  84753. }
  84754. }
  84755. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84756. elementSize: elementSize
  84757. });
  84758. //For future reference, needed for body transformation
  84759. shape.minY = minY;
  84760. return shape;
  84761. };
  84762. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84763. var object = impostor.object;
  84764. //make sure it is updated...
  84765. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84766. // The delta between the mesh position and the mesh bounding box center
  84767. var bInfo = object.getBoundingInfo();
  84768. if (!bInfo)
  84769. return;
  84770. var center = impostor.getObjectCenter();
  84771. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84772. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84773. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84774. this._tmpPosition.copyFrom(center);
  84775. var quaternion = object.rotationQuaternion;
  84776. if (!quaternion) {
  84777. return;
  84778. }
  84779. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84780. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84781. //-90 DEG in X, precalculated
  84782. quaternion = quaternion.multiply(this._minus90X);
  84783. //Invert! (Precalculated, 90 deg in X)
  84784. //No need to clone. this will never change.
  84785. impostor.setDeltaRotation(this._plus90X);
  84786. }
  84787. //If it is a heightfield, if should be centered.
  84788. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84789. var mesh = object;
  84790. var boundingInfo = mesh.getBoundingInfo();
  84791. //calculate the correct body position:
  84792. var rotationQuaternion = mesh.rotationQuaternion;
  84793. mesh.rotationQuaternion = this._tmpUnityRotation;
  84794. mesh.computeWorldMatrix(true);
  84795. //get original center with no rotation
  84796. var c = center.clone();
  84797. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84798. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84799. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84800. mesh.setPreTransformMatrix(p);
  84801. mesh.computeWorldMatrix(true);
  84802. //calculate the translation
  84803. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84804. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84805. //add it inverted to the delta
  84806. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84807. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84808. //rotation is back
  84809. mesh.rotationQuaternion = rotationQuaternion;
  84810. mesh.setPreTransformMatrix(oldPivot);
  84811. mesh.computeWorldMatrix(true);
  84812. }
  84813. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84814. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84815. //this._tmpPosition.copyFrom(object.position);
  84816. }
  84817. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84818. //Now update the impostor object
  84819. impostor.physicsBody.position.copy(this._tmpPosition);
  84820. impostor.physicsBody.quaternion.copy(quaternion);
  84821. };
  84822. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84823. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84824. if (impostor.object.rotationQuaternion) {
  84825. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84826. }
  84827. };
  84828. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84829. impostor.physicsBody.position.copy(newPosition);
  84830. impostor.physicsBody.quaternion.copy(newRotation);
  84831. };
  84832. CannonJSPlugin.prototype.isSupported = function () {
  84833. return this.BJSCANNON !== undefined;
  84834. };
  84835. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84836. impostor.physicsBody.velocity.copy(velocity);
  84837. };
  84838. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84839. impostor.physicsBody.angularVelocity.copy(velocity);
  84840. };
  84841. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84842. var v = impostor.physicsBody.velocity;
  84843. if (!v) {
  84844. return null;
  84845. }
  84846. return new BABYLON.Vector3(v.x, v.y, v.z);
  84847. };
  84848. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84849. var v = impostor.physicsBody.angularVelocity;
  84850. if (!v) {
  84851. return null;
  84852. }
  84853. return new BABYLON.Vector3(v.x, v.y, v.z);
  84854. };
  84855. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84856. impostor.physicsBody.mass = mass;
  84857. impostor.physicsBody.updateMassProperties();
  84858. };
  84859. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84860. return impostor.physicsBody.mass;
  84861. };
  84862. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84863. return impostor.physicsBody.material.friction;
  84864. };
  84865. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84866. impostor.physicsBody.material.friction = friction;
  84867. };
  84868. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84869. return impostor.physicsBody.material.restitution;
  84870. };
  84871. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84872. impostor.physicsBody.material.restitution = restitution;
  84873. };
  84874. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84875. impostor.physicsBody.sleep();
  84876. };
  84877. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84878. impostor.physicsBody.wakeUp();
  84879. };
  84880. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84881. joint.physicsJoint.distance = maxDistance;
  84882. };
  84883. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84884. // if (!motorIndex) {
  84885. // joint.physicsJoint.enableMotor();
  84886. // }
  84887. // }
  84888. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84889. // if (!motorIndex) {
  84890. // joint.physicsJoint.disableMotor();
  84891. // }
  84892. // }
  84893. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84894. if (!motorIndex) {
  84895. joint.physicsJoint.enableMotor();
  84896. joint.physicsJoint.setMotorSpeed(speed);
  84897. if (maxForce) {
  84898. this.setLimit(joint, maxForce);
  84899. }
  84900. }
  84901. };
  84902. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84903. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84904. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84905. };
  84906. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84907. var body = impostor.physicsBody;
  84908. mesh.position.x = body.position.x;
  84909. mesh.position.y = body.position.y;
  84910. mesh.position.z = body.position.z;
  84911. if (mesh.rotationQuaternion) {
  84912. mesh.rotationQuaternion.x = body.quaternion.x;
  84913. mesh.rotationQuaternion.y = body.quaternion.y;
  84914. mesh.rotationQuaternion.z = body.quaternion.z;
  84915. mesh.rotationQuaternion.w = body.quaternion.w;
  84916. }
  84917. };
  84918. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84919. var shape = impostor.physicsBody.shapes[0];
  84920. return shape.boundingSphereRadius;
  84921. };
  84922. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84923. var shape = impostor.physicsBody.shapes[0];
  84924. result.x = shape.halfExtents.x * 2;
  84925. result.y = shape.halfExtents.y * 2;
  84926. result.z = shape.halfExtents.z * 2;
  84927. };
  84928. CannonJSPlugin.prototype.dispose = function () {
  84929. };
  84930. CannonJSPlugin.prototype._extendNamespace = function () {
  84931. //this will force cannon to execute at least one step when using interpolation
  84932. var step_tmp1 = new this.BJSCANNON.Vec3();
  84933. var Engine = this.BJSCANNON;
  84934. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84935. maxSubSteps = maxSubSteps || 10;
  84936. timeSinceLastCalled = timeSinceLastCalled || 0;
  84937. if (timeSinceLastCalled === 0) {
  84938. this.internalStep(dt);
  84939. this.time += dt;
  84940. }
  84941. else {
  84942. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84943. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84944. var t0 = performance.now();
  84945. for (var i = 0; i !== internalSteps; i++) {
  84946. this.internalStep(dt);
  84947. if (performance.now() - t0 > dt * 1000) {
  84948. break;
  84949. }
  84950. }
  84951. this.time += timeSinceLastCalled;
  84952. var h = this.time % dt;
  84953. var h_div_dt = h / dt;
  84954. var interpvelo = step_tmp1;
  84955. var bodies = this.bodies;
  84956. for (var j = 0; j !== bodies.length; j++) {
  84957. var b = bodies[j];
  84958. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84959. b.position.vsub(b.previousPosition, interpvelo);
  84960. interpvelo.scale(h_div_dt, interpvelo);
  84961. b.position.vadd(interpvelo, b.interpolatedPosition);
  84962. }
  84963. else {
  84964. b.interpolatedPosition.copy(b.position);
  84965. b.interpolatedQuaternion.copy(b.quaternion);
  84966. }
  84967. }
  84968. }
  84969. };
  84970. };
  84971. return CannonJSPlugin;
  84972. }());
  84973. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84974. })(BABYLON || (BABYLON = {}));
  84975. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84976. var BABYLON;
  84977. (function (BABYLON) {
  84978. var OimoJSPlugin = /** @class */ (function () {
  84979. function OimoJSPlugin(iterations) {
  84980. this.name = "OimoJSPlugin";
  84981. this._tmpImpostorsArray = [];
  84982. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84983. this.BJSOIMO = OIMO;
  84984. this.world = new this.BJSOIMO.World({
  84985. iterations: iterations
  84986. });
  84987. this.world.clear();
  84988. }
  84989. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84990. this.world.gravity.copy(gravity);
  84991. };
  84992. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84993. this.world.timeStep = timeStep;
  84994. };
  84995. OimoJSPlugin.prototype.getTimeStep = function () {
  84996. return this.world.timeStep;
  84997. };
  84998. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84999. var _this = this;
  85000. impostors.forEach(function (impostor) {
  85001. impostor.beforeStep();
  85002. });
  85003. this.world.step();
  85004. impostors.forEach(function (impostor) {
  85005. impostor.afterStep();
  85006. //update the ordered impostors array
  85007. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85008. });
  85009. //check for collisions
  85010. var contact = this.world.contacts;
  85011. while (contact !== null) {
  85012. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85013. contact = contact.next;
  85014. continue;
  85015. }
  85016. //is this body colliding with any other? get the impostor
  85017. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85018. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85019. if (!mainImpostor || !collidingImpostor) {
  85020. contact = contact.next;
  85021. continue;
  85022. }
  85023. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85024. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85025. contact = contact.next;
  85026. }
  85027. };
  85028. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85029. var mass = impostor.physicsBody.mass;
  85030. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85031. };
  85032. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85033. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85034. this.applyImpulse(impostor, force, contactPoint);
  85035. };
  85036. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85037. var _this = this;
  85038. //parent-child relationship. Does this impostor has a parent impostor?
  85039. if (impostor.parent) {
  85040. if (impostor.physicsBody) {
  85041. this.removePhysicsBody(impostor);
  85042. //TODO is that needed?
  85043. impostor.forceUpdate();
  85044. }
  85045. return;
  85046. }
  85047. if (impostor.isBodyInitRequired()) {
  85048. var bodyConfig = {
  85049. name: impostor.uniqueId,
  85050. //Oimo must have mass, also for static objects.
  85051. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85052. size: [],
  85053. type: [],
  85054. pos: [],
  85055. posShape: [],
  85056. rot: [],
  85057. rotShape: [],
  85058. move: impostor.getParam("mass") !== 0,
  85059. density: impostor.getParam("mass"),
  85060. friction: impostor.getParam("friction"),
  85061. restitution: impostor.getParam("restitution"),
  85062. //Supporting older versions of Oimo
  85063. world: this.world
  85064. };
  85065. var impostors = [impostor];
  85066. var addToArray = function (parent) {
  85067. if (!parent.getChildMeshes)
  85068. return;
  85069. parent.getChildMeshes().forEach(function (m) {
  85070. if (m.physicsImpostor) {
  85071. impostors.push(m.physicsImpostor);
  85072. //m.physicsImpostor._init();
  85073. }
  85074. });
  85075. };
  85076. addToArray(impostor.object);
  85077. var checkWithEpsilon_1 = function (value) {
  85078. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85079. };
  85080. impostors.forEach(function (i) {
  85081. if (!i.object.rotationQuaternion) {
  85082. return;
  85083. }
  85084. //get the correct bounding box
  85085. var oldQuaternion = i.object.rotationQuaternion;
  85086. var rot = oldQuaternion.toEulerAngles();
  85087. var extendSize = i.getObjectExtendSize();
  85088. var radToDeg = 57.295779513082320876;
  85089. if (i === impostor) {
  85090. var center = impostor.getObjectCenter();
  85091. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85092. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85093. //Can also use Array.prototype.push.apply
  85094. bodyConfig.pos.push(center.x);
  85095. bodyConfig.pos.push(center.y);
  85096. bodyConfig.pos.push(center.z);
  85097. bodyConfig.posShape.push(0, 0, 0);
  85098. //tmp solution
  85099. bodyConfig.rot.push(rot.x * radToDeg);
  85100. bodyConfig.rot.push(rot.y * radToDeg);
  85101. bodyConfig.rot.push(rot.z * radToDeg);
  85102. bodyConfig.rotShape.push(0, 0, 0);
  85103. }
  85104. else {
  85105. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85106. bodyConfig.posShape.push(localPosition.x);
  85107. bodyConfig.posShape.push(localPosition.y);
  85108. bodyConfig.posShape.push(localPosition.z);
  85109. bodyConfig.pos.push(0, 0, 0);
  85110. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85111. bodyConfig.rot.push(0);
  85112. bodyConfig.rot.push(0);
  85113. bodyConfig.rot.push(0);
  85114. bodyConfig.rotShape.push(rot.x * radToDeg);
  85115. bodyConfig.rotShape.push(rot.y * radToDeg);
  85116. bodyConfig.rotShape.push(rot.z * radToDeg);
  85117. }
  85118. // register mesh
  85119. switch (i.type) {
  85120. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85121. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85122. case BABYLON.PhysicsImpostor.SphereImpostor:
  85123. var radiusX = extendSize.x;
  85124. var radiusY = extendSize.y;
  85125. var radiusZ = extendSize.z;
  85126. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85127. bodyConfig.type.push('sphere');
  85128. //due to the way oimo works with compounds, add 3 times
  85129. bodyConfig.size.push(size);
  85130. bodyConfig.size.push(size);
  85131. bodyConfig.size.push(size);
  85132. break;
  85133. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85134. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85135. var sizeY = checkWithEpsilon_1(extendSize.y);
  85136. bodyConfig.type.push('cylinder');
  85137. bodyConfig.size.push(sizeX);
  85138. bodyConfig.size.push(sizeY);
  85139. //due to the way oimo works with compounds, add one more value.
  85140. bodyConfig.size.push(sizeY);
  85141. break;
  85142. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85143. case BABYLON.PhysicsImpostor.BoxImpostor:
  85144. default:
  85145. var sizeX = checkWithEpsilon_1(extendSize.x);
  85146. var sizeY = checkWithEpsilon_1(extendSize.y);
  85147. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85148. bodyConfig.type.push('box');
  85149. //if (i === impostor) {
  85150. bodyConfig.size.push(sizeX);
  85151. bodyConfig.size.push(sizeY);
  85152. bodyConfig.size.push(sizeZ);
  85153. //} else {
  85154. // bodyConfig.size.push(0,0,0);
  85155. //}
  85156. break;
  85157. }
  85158. //actually not needed, but hey...
  85159. i.object.rotationQuaternion = oldQuaternion;
  85160. });
  85161. impostor.physicsBody = this.world.add(bodyConfig);
  85162. }
  85163. else {
  85164. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85165. }
  85166. impostor.setDeltaPosition(this._tmpPositionVector);
  85167. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85168. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85169. };
  85170. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85171. //impostor.physicsBody.dispose();
  85172. //Same as : (older oimo versions)
  85173. this.world.removeRigidBody(impostor.physicsBody);
  85174. };
  85175. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85176. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85177. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85178. if (!mainBody || !connectedBody) {
  85179. return;
  85180. }
  85181. var jointData = impostorJoint.joint.jointData;
  85182. var options = jointData.nativeParams || {};
  85183. var type;
  85184. var nativeJointData = {
  85185. body1: mainBody,
  85186. body2: connectedBody,
  85187. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85188. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85189. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85190. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85191. min: options.min,
  85192. max: options.max,
  85193. collision: options.collision || jointData.collision,
  85194. spring: options.spring,
  85195. //supporting older version of Oimo
  85196. world: this.world
  85197. };
  85198. switch (impostorJoint.joint.type) {
  85199. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85200. type = "jointBall";
  85201. break;
  85202. case BABYLON.PhysicsJoint.SpringJoint:
  85203. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85204. var springData = jointData;
  85205. nativeJointData.min = springData.length || nativeJointData.min;
  85206. //Max should also be set, just make sure it is at least min
  85207. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85208. case BABYLON.PhysicsJoint.DistanceJoint:
  85209. type = "jointDistance";
  85210. nativeJointData.max = jointData.maxDistance;
  85211. break;
  85212. case BABYLON.PhysicsJoint.PrismaticJoint:
  85213. type = "jointPrisme";
  85214. break;
  85215. case BABYLON.PhysicsJoint.SliderJoint:
  85216. type = "jointSlide";
  85217. break;
  85218. case BABYLON.PhysicsJoint.WheelJoint:
  85219. type = "jointWheel";
  85220. break;
  85221. case BABYLON.PhysicsJoint.HingeJoint:
  85222. default:
  85223. type = "jointHinge";
  85224. break;
  85225. }
  85226. nativeJointData.type = type;
  85227. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85228. };
  85229. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85230. //Bug in Oimo prevents us from disposing a joint in the playground
  85231. //joint.joint.physicsJoint.dispose();
  85232. //So we will bruteforce it!
  85233. try {
  85234. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85235. }
  85236. catch (e) {
  85237. BABYLON.Tools.Warn(e);
  85238. }
  85239. };
  85240. OimoJSPlugin.prototype.isSupported = function () {
  85241. return this.BJSOIMO !== undefined;
  85242. };
  85243. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85244. if (!impostor.physicsBody.sleeping) {
  85245. //TODO check that
  85246. /*if (impostor.physicsBody.shapes.next) {
  85247. var parentShape = this._getLastShape(impostor.physicsBody);
  85248. impostor.object.position.copyFrom(parentShape.position);
  85249. console.log(parentShape.position);
  85250. } else {*/
  85251. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85252. //}
  85253. if (impostor.object.rotationQuaternion) {
  85254. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85255. }
  85256. }
  85257. };
  85258. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85259. var body = impostor.physicsBody;
  85260. body.position.copy(newPosition);
  85261. body.orientation.copy(newRotation);
  85262. body.syncShapes();
  85263. body.awake();
  85264. };
  85265. /*private _getLastShape(body: any): any {
  85266. var lastShape = body.shapes;
  85267. while (lastShape.next) {
  85268. lastShape = lastShape.next;
  85269. }
  85270. return lastShape;
  85271. }*/
  85272. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85273. impostor.physicsBody.linearVelocity.copy(velocity);
  85274. };
  85275. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85276. impostor.physicsBody.angularVelocity.copy(velocity);
  85277. };
  85278. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85279. var v = impostor.physicsBody.linearVelocity;
  85280. if (!v) {
  85281. return null;
  85282. }
  85283. return new BABYLON.Vector3(v.x, v.y, v.z);
  85284. };
  85285. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85286. var v = impostor.physicsBody.angularVelocity;
  85287. if (!v) {
  85288. return null;
  85289. }
  85290. return new BABYLON.Vector3(v.x, v.y, v.z);
  85291. };
  85292. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85293. var staticBody = mass === 0;
  85294. //this will actually set the body's density and not its mass.
  85295. //But this is how oimo treats the mass variable.
  85296. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85297. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85298. };
  85299. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85300. return impostor.physicsBody.shapes.density;
  85301. };
  85302. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85303. return impostor.physicsBody.shapes.friction;
  85304. };
  85305. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85306. impostor.physicsBody.shapes.friction = friction;
  85307. };
  85308. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85309. return impostor.physicsBody.shapes.restitution;
  85310. };
  85311. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85312. impostor.physicsBody.shapes.restitution = restitution;
  85313. };
  85314. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85315. impostor.physicsBody.sleep();
  85316. };
  85317. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85318. impostor.physicsBody.awake();
  85319. };
  85320. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85321. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85322. if (minDistance !== void 0) {
  85323. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85324. }
  85325. };
  85326. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85327. //TODO separate rotational and transational motors.
  85328. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85329. if (motor) {
  85330. motor.setMotor(speed, maxForce);
  85331. }
  85332. };
  85333. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85334. //TODO separate rotational and transational motors.
  85335. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85336. if (motor) {
  85337. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85338. }
  85339. };
  85340. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85341. var body = impostor.physicsBody;
  85342. mesh.position.x = body.position.x;
  85343. mesh.position.y = body.position.y;
  85344. mesh.position.z = body.position.z;
  85345. if (mesh.rotationQuaternion) {
  85346. mesh.rotationQuaternion.x = body.orientation.x;
  85347. mesh.rotationQuaternion.y = body.orientation.y;
  85348. mesh.rotationQuaternion.z = body.orientation.z;
  85349. mesh.rotationQuaternion.w = body.orientation.s;
  85350. }
  85351. };
  85352. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85353. return impostor.physicsBody.shapes.radius;
  85354. };
  85355. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85356. var shape = impostor.physicsBody.shapes;
  85357. result.x = shape.halfWidth * 2;
  85358. result.y = shape.halfHeight * 2;
  85359. result.z = shape.halfDepth * 2;
  85360. };
  85361. OimoJSPlugin.prototype.dispose = function () {
  85362. this.world.clear();
  85363. };
  85364. return OimoJSPlugin;
  85365. }());
  85366. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85367. })(BABYLON || (BABYLON = {}));
  85368. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85369. var BABYLON;
  85370. (function (BABYLON) {
  85371. /*
  85372. * Based on jsTGALoader - Javascript loader for TGA file
  85373. * By Vincent Thibault
  85374. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85375. */
  85376. var TGATools = /** @class */ (function () {
  85377. function TGATools() {
  85378. }
  85379. TGATools.GetTGAHeader = function (data) {
  85380. var offset = 0;
  85381. var header = {
  85382. id_length: data[offset++],
  85383. colormap_type: data[offset++],
  85384. image_type: data[offset++],
  85385. colormap_index: data[offset++] | data[offset++] << 8,
  85386. colormap_length: data[offset++] | data[offset++] << 8,
  85387. colormap_size: data[offset++],
  85388. origin: [
  85389. data[offset++] | data[offset++] << 8,
  85390. data[offset++] | data[offset++] << 8
  85391. ],
  85392. width: data[offset++] | data[offset++] << 8,
  85393. height: data[offset++] | data[offset++] << 8,
  85394. pixel_size: data[offset++],
  85395. flags: data[offset++]
  85396. };
  85397. return header;
  85398. };
  85399. TGATools.UploadContent = function (gl, data) {
  85400. // Not enough data to contain header ?
  85401. if (data.length < 19) {
  85402. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85403. return;
  85404. }
  85405. // Read Header
  85406. var offset = 18;
  85407. var header = TGATools.GetTGAHeader(data);
  85408. // Assume it's a valid Targa file.
  85409. if (header.id_length + offset > data.length) {
  85410. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85411. return;
  85412. }
  85413. // Skip not needed data
  85414. offset += header.id_length;
  85415. var use_rle = false;
  85416. var use_pal = false;
  85417. var use_grey = false;
  85418. // Get some informations.
  85419. switch (header.image_type) {
  85420. case TGATools._TYPE_RLE_INDEXED:
  85421. use_rle = true;
  85422. case TGATools._TYPE_INDEXED:
  85423. use_pal = true;
  85424. break;
  85425. case TGATools._TYPE_RLE_RGB:
  85426. use_rle = true;
  85427. case TGATools._TYPE_RGB:
  85428. // use_rgb = true;
  85429. break;
  85430. case TGATools._TYPE_RLE_GREY:
  85431. use_rle = true;
  85432. case TGATools._TYPE_GREY:
  85433. use_grey = true;
  85434. break;
  85435. }
  85436. var pixel_data;
  85437. // var numAlphaBits = header.flags & 0xf;
  85438. var pixel_size = header.pixel_size >> 3;
  85439. var pixel_total = header.width * header.height * pixel_size;
  85440. // Read palettes
  85441. var palettes;
  85442. if (use_pal) {
  85443. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85444. }
  85445. // Read LRE
  85446. if (use_rle) {
  85447. pixel_data = new Uint8Array(pixel_total);
  85448. var c, count, i;
  85449. var localOffset = 0;
  85450. var pixels = new Uint8Array(pixel_size);
  85451. while (offset < pixel_total && localOffset < pixel_total) {
  85452. c = data[offset++];
  85453. count = (c & 0x7f) + 1;
  85454. // RLE pixels
  85455. if (c & 0x80) {
  85456. // Bind pixel tmp array
  85457. for (i = 0; i < pixel_size; ++i) {
  85458. pixels[i] = data[offset++];
  85459. }
  85460. // Copy pixel array
  85461. for (i = 0; i < count; ++i) {
  85462. pixel_data.set(pixels, localOffset + i * pixel_size);
  85463. }
  85464. localOffset += pixel_size * count;
  85465. }
  85466. // Raw pixels
  85467. else {
  85468. count *= pixel_size;
  85469. for (i = 0; i < count; ++i) {
  85470. pixel_data[localOffset + i] = data[offset++];
  85471. }
  85472. localOffset += count;
  85473. }
  85474. }
  85475. }
  85476. // RAW Pixels
  85477. else {
  85478. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85479. }
  85480. // Load to texture
  85481. var x_start, y_start, x_step, y_step, y_end, x_end;
  85482. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85483. default:
  85484. case TGATools._ORIGIN_UL:
  85485. x_start = 0;
  85486. x_step = 1;
  85487. x_end = header.width;
  85488. y_start = 0;
  85489. y_step = 1;
  85490. y_end = header.height;
  85491. break;
  85492. case TGATools._ORIGIN_BL:
  85493. x_start = 0;
  85494. x_step = 1;
  85495. x_end = header.width;
  85496. y_start = header.height - 1;
  85497. y_step = -1;
  85498. y_end = -1;
  85499. break;
  85500. case TGATools._ORIGIN_UR:
  85501. x_start = header.width - 1;
  85502. x_step = -1;
  85503. x_end = -1;
  85504. y_start = 0;
  85505. y_step = 1;
  85506. y_end = header.height;
  85507. break;
  85508. case TGATools._ORIGIN_BR:
  85509. x_start = header.width - 1;
  85510. x_step = -1;
  85511. x_end = -1;
  85512. y_start = header.height - 1;
  85513. y_step = -1;
  85514. y_end = -1;
  85515. break;
  85516. }
  85517. // Load the specify method
  85518. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85519. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85520. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85521. };
  85522. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85523. var image = pixel_data, colormap = palettes;
  85524. var width = header.width, height = header.height;
  85525. var color, i = 0, x, y;
  85526. var imageData = new Uint8Array(width * height * 4);
  85527. for (y = y_start; y !== y_end; y += y_step) {
  85528. for (x = x_start; x !== x_end; x += x_step, i++) {
  85529. color = image[i];
  85530. imageData[(x + width * y) * 4 + 3] = 255;
  85531. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85532. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85533. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85534. }
  85535. }
  85536. return imageData;
  85537. };
  85538. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85539. var image = pixel_data;
  85540. var width = header.width, height = header.height;
  85541. var color, i = 0, x, y;
  85542. var imageData = new Uint8Array(width * height * 4);
  85543. for (y = y_start; y !== y_end; y += y_step) {
  85544. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85545. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85546. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85547. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85548. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85549. imageData[(x + width * y) * 4 + 0] = r;
  85550. imageData[(x + width * y) * 4 + 1] = g;
  85551. imageData[(x + width * y) * 4 + 2] = b;
  85552. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85553. }
  85554. }
  85555. return imageData;
  85556. };
  85557. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85558. var image = pixel_data;
  85559. var width = header.width, height = header.height;
  85560. var i = 0, x, y;
  85561. var imageData = new Uint8Array(width * height * 4);
  85562. for (y = y_start; y !== y_end; y += y_step) {
  85563. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85564. imageData[(x + width * y) * 4 + 3] = 255;
  85565. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85566. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85567. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85568. }
  85569. }
  85570. return imageData;
  85571. };
  85572. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85573. var image = pixel_data;
  85574. var width = header.width, height = header.height;
  85575. var i = 0, x, y;
  85576. var imageData = new Uint8Array(width * height * 4);
  85577. for (y = y_start; y !== y_end; y += y_step) {
  85578. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85579. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85580. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85581. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85582. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85583. }
  85584. }
  85585. return imageData;
  85586. };
  85587. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85588. var image = pixel_data;
  85589. var width = header.width, height = header.height;
  85590. var color, i = 0, x, y;
  85591. var imageData = new Uint8Array(width * height * 4);
  85592. for (y = y_start; y !== y_end; y += y_step) {
  85593. for (x = x_start; x !== x_end; x += x_step, i++) {
  85594. color = image[i];
  85595. imageData[(x + width * y) * 4 + 0] = color;
  85596. imageData[(x + width * y) * 4 + 1] = color;
  85597. imageData[(x + width * y) * 4 + 2] = color;
  85598. imageData[(x + width * y) * 4 + 3] = 255;
  85599. }
  85600. }
  85601. return imageData;
  85602. };
  85603. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85604. var image = pixel_data;
  85605. var width = header.width, height = header.height;
  85606. var i = 0, x, y;
  85607. var imageData = new Uint8Array(width * height * 4);
  85608. for (y = y_start; y !== y_end; y += y_step) {
  85609. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85610. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85611. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85612. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85613. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85614. }
  85615. }
  85616. return imageData;
  85617. };
  85618. //private static _TYPE_NO_DATA = 0;
  85619. TGATools._TYPE_INDEXED = 1;
  85620. TGATools._TYPE_RGB = 2;
  85621. TGATools._TYPE_GREY = 3;
  85622. TGATools._TYPE_RLE_INDEXED = 9;
  85623. TGATools._TYPE_RLE_RGB = 10;
  85624. TGATools._TYPE_RLE_GREY = 11;
  85625. TGATools._ORIGIN_MASK = 0x30;
  85626. TGATools._ORIGIN_SHIFT = 0x04;
  85627. TGATools._ORIGIN_BL = 0x00;
  85628. TGATools._ORIGIN_BR = 0x01;
  85629. TGATools._ORIGIN_UL = 0x02;
  85630. TGATools._ORIGIN_UR = 0x03;
  85631. return TGATools;
  85632. }());
  85633. BABYLON.TGATools = TGATools;
  85634. })(BABYLON || (BABYLON = {}));
  85635. //# sourceMappingURL=babylon.tga.js.map
  85636. var BABYLON;
  85637. (function (BABYLON) {
  85638. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85639. // All values and structures referenced from:
  85640. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85641. var DDS_MAGIC = 0x20534444;
  85642. var
  85643. //DDSD_CAPS = 0x1,
  85644. //DDSD_HEIGHT = 0x2,
  85645. //DDSD_WIDTH = 0x4,
  85646. //DDSD_PITCH = 0x8,
  85647. //DDSD_PIXELFORMAT = 0x1000,
  85648. DDSD_MIPMAPCOUNT = 0x20000;
  85649. //DDSD_LINEARSIZE = 0x80000,
  85650. //DDSD_DEPTH = 0x800000;
  85651. // var DDSCAPS_COMPLEX = 0x8,
  85652. // DDSCAPS_MIPMAP = 0x400000,
  85653. // DDSCAPS_TEXTURE = 0x1000;
  85654. var DDSCAPS2_CUBEMAP = 0x200;
  85655. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85656. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85657. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85658. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85659. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85660. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85661. // DDSCAPS2_VOLUME = 0x200000;
  85662. var
  85663. //DDPF_ALPHAPIXELS = 0x1,
  85664. //DDPF_ALPHA = 0x2,
  85665. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85666. //DDPF_YUV = 0x200,
  85667. DDPF_LUMINANCE = 0x20000;
  85668. function FourCCToInt32(value) {
  85669. return value.charCodeAt(0) +
  85670. (value.charCodeAt(1) << 8) +
  85671. (value.charCodeAt(2) << 16) +
  85672. (value.charCodeAt(3) << 24);
  85673. }
  85674. function Int32ToFourCC(value) {
  85675. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85676. }
  85677. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85678. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85679. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85680. var FOURCC_DX10 = FourCCToInt32("DX10");
  85681. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85682. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85683. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85684. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85685. var headerLengthInt = 31; // The header length in 32 bit ints
  85686. // Offsets into the header array
  85687. var off_magic = 0;
  85688. var off_size = 1;
  85689. var off_flags = 2;
  85690. var off_height = 3;
  85691. var off_width = 4;
  85692. var off_mipmapCount = 7;
  85693. var off_pfFlags = 20;
  85694. var off_pfFourCC = 21;
  85695. var off_RGBbpp = 22;
  85696. var off_RMask = 23;
  85697. var off_GMask = 24;
  85698. var off_BMask = 25;
  85699. var off_AMask = 26;
  85700. // var off_caps1 = 27;
  85701. var off_caps2 = 28;
  85702. // var off_caps3 = 29;
  85703. // var off_caps4 = 30;
  85704. var off_dxgiFormat = 32;
  85705. ;
  85706. var DDSTools = /** @class */ (function () {
  85707. function DDSTools() {
  85708. }
  85709. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85710. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85711. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85712. var mipmapCount = 1;
  85713. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85714. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85715. }
  85716. var fourCC = header[off_pfFourCC];
  85717. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85718. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85719. switch (fourCC) {
  85720. case FOURCC_D3DFMT_R16G16B16A16F:
  85721. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85722. break;
  85723. case FOURCC_D3DFMT_R32G32B32A32F:
  85724. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85725. break;
  85726. case FOURCC_DX10:
  85727. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85728. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85729. break;
  85730. }
  85731. }
  85732. return {
  85733. width: header[off_width],
  85734. height: header[off_height],
  85735. mipmapCount: mipmapCount,
  85736. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85737. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85738. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85739. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85740. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85741. dxgiFormat: dxgiFormat,
  85742. textureType: textureType
  85743. };
  85744. };
  85745. DDSTools._ToHalfFloat = function (value) {
  85746. if (!DDSTools._FloatView) {
  85747. DDSTools._FloatView = new Float32Array(1);
  85748. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85749. }
  85750. DDSTools._FloatView[0] = value;
  85751. var x = DDSTools._Int32View[0];
  85752. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85753. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85754. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85755. /* If zero, or denormal, or exponent underflows too much for a denormal
  85756. * half, return signed zero. */
  85757. if (e < 103) {
  85758. return bits;
  85759. }
  85760. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85761. if (e > 142) {
  85762. bits |= 0x7c00;
  85763. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85764. * not Inf, so make sure we set one mantissa bit too. */
  85765. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85766. return bits;
  85767. }
  85768. /* If exponent underflows but not too much, return a denormal */
  85769. if (e < 113) {
  85770. m |= 0x0800;
  85771. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85772. * to 1, which is OK. */
  85773. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85774. return bits;
  85775. }
  85776. bits |= ((e - 112) << 10) | (m >> 1);
  85777. bits += m & 1;
  85778. return bits;
  85779. };
  85780. DDSTools._FromHalfFloat = function (value) {
  85781. var s = (value & 0x8000) >> 15;
  85782. var e = (value & 0x7C00) >> 10;
  85783. var f = value & 0x03FF;
  85784. if (e === 0) {
  85785. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85786. }
  85787. else if (e == 0x1F) {
  85788. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85789. }
  85790. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85791. };
  85792. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85793. var destArray = new Float32Array(dataLength);
  85794. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85795. var index = 0;
  85796. for (var y = 0; y < height; y++) {
  85797. for (var x = 0; x < width; x++) {
  85798. var srcPos = (x + y * width) * 4;
  85799. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85800. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85801. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85802. if (DDSTools.StoreLODInAlphaChannel) {
  85803. destArray[index + 3] = lod;
  85804. }
  85805. else {
  85806. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85807. }
  85808. index += 4;
  85809. }
  85810. }
  85811. return destArray;
  85812. };
  85813. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85814. if (DDSTools.StoreLODInAlphaChannel) {
  85815. var destArray = new Uint16Array(dataLength);
  85816. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85817. var index = 0;
  85818. for (var y = 0; y < height; y++) {
  85819. for (var x = 0; x < width; x++) {
  85820. var srcPos = (x + y * width) * 4;
  85821. destArray[index] = srcData[srcPos];
  85822. destArray[index + 1] = srcData[srcPos + 1];
  85823. destArray[index + 2] = srcData[srcPos + 2];
  85824. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85825. index += 4;
  85826. }
  85827. }
  85828. return destArray;
  85829. }
  85830. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85831. };
  85832. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85833. if (DDSTools.StoreLODInAlphaChannel) {
  85834. var destArray = new Float32Array(dataLength);
  85835. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85836. var index = 0;
  85837. for (var y = 0; y < height; y++) {
  85838. for (var x = 0; x < width; x++) {
  85839. var srcPos = (x + y * width) * 4;
  85840. destArray[index] = srcData[srcPos];
  85841. destArray[index + 1] = srcData[srcPos + 1];
  85842. destArray[index + 2] = srcData[srcPos + 2];
  85843. destArray[index + 3] = lod;
  85844. index += 4;
  85845. }
  85846. }
  85847. return destArray;
  85848. }
  85849. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85850. };
  85851. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85852. var destArray = new Uint8Array(dataLength);
  85853. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85854. var index = 0;
  85855. for (var y = 0; y < height; y++) {
  85856. for (var x = 0; x < width; x++) {
  85857. var srcPos = (x + y * width) * 4;
  85858. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85859. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85860. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85861. if (DDSTools.StoreLODInAlphaChannel) {
  85862. destArray[index + 3] = lod;
  85863. }
  85864. else {
  85865. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85866. }
  85867. index += 4;
  85868. }
  85869. }
  85870. return destArray;
  85871. };
  85872. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85873. var destArray = new Uint8Array(dataLength);
  85874. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85875. var index = 0;
  85876. for (var y = 0; y < height; y++) {
  85877. for (var x = 0; x < width; x++) {
  85878. var srcPos = (x + y * width) * 4;
  85879. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85880. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85881. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85882. if (DDSTools.StoreLODInAlphaChannel) {
  85883. destArray[index + 3] = lod;
  85884. }
  85885. else {
  85886. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85887. }
  85888. index += 4;
  85889. }
  85890. }
  85891. return destArray;
  85892. };
  85893. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85894. var byteArray = new Uint8Array(dataLength);
  85895. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85896. var index = 0;
  85897. for (var y = 0; y < height; y++) {
  85898. for (var x = 0; x < width; x++) {
  85899. var srcPos = (x + y * width) * 4;
  85900. byteArray[index] = srcData[srcPos + rOffset];
  85901. byteArray[index + 1] = srcData[srcPos + gOffset];
  85902. byteArray[index + 2] = srcData[srcPos + bOffset];
  85903. byteArray[index + 3] = srcData[srcPos + aOffset];
  85904. index += 4;
  85905. }
  85906. }
  85907. return byteArray;
  85908. };
  85909. DDSTools._ExtractLongWordOrder = function (value) {
  85910. if (value === 0 || value === 255 || value === -16777216) {
  85911. return 0;
  85912. }
  85913. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85914. };
  85915. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85916. var byteArray = new Uint8Array(dataLength);
  85917. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85918. var index = 0;
  85919. for (var y = 0; y < height; y++) {
  85920. for (var x = 0; x < width; x++) {
  85921. var srcPos = (x + y * width) * 3;
  85922. byteArray[index] = srcData[srcPos + rOffset];
  85923. byteArray[index + 1] = srcData[srcPos + gOffset];
  85924. byteArray[index + 2] = srcData[srcPos + bOffset];
  85925. index += 3;
  85926. }
  85927. }
  85928. return byteArray;
  85929. };
  85930. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85931. var byteArray = new Uint8Array(dataLength);
  85932. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85933. var index = 0;
  85934. for (var y = 0; y < height; y++) {
  85935. for (var x = 0; x < width; x++) {
  85936. var srcPos = (x + y * width);
  85937. byteArray[index] = srcData[srcPos];
  85938. index++;
  85939. }
  85940. }
  85941. return byteArray;
  85942. };
  85943. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85944. if (lodIndex === void 0) { lodIndex = -1; }
  85945. var sphericalPolynomialFaces = null;
  85946. if (info.sphericalPolynomial) {
  85947. sphericalPolynomialFaces = new Array();
  85948. }
  85949. var ext = engine.getCaps().s3tc;
  85950. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85951. var fourCC, width, height, dataLength = 0, dataOffset;
  85952. var byteArray, mipmapCount, mip;
  85953. var internalFormat = 0;
  85954. var format = 0;
  85955. var blockBytes = 1;
  85956. if (header[off_magic] !== DDS_MAGIC) {
  85957. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85958. return;
  85959. }
  85960. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85961. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85962. return;
  85963. }
  85964. if (info.isCompressed && !ext) {
  85965. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85966. return;
  85967. }
  85968. var bpp = header[off_RGBbpp];
  85969. dataOffset = header[off_size] + 4;
  85970. var computeFormats = false;
  85971. if (info.isFourCC) {
  85972. fourCC = header[off_pfFourCC];
  85973. switch (fourCC) {
  85974. case FOURCC_DXT1:
  85975. blockBytes = 8;
  85976. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85977. break;
  85978. case FOURCC_DXT3:
  85979. blockBytes = 16;
  85980. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85981. break;
  85982. case FOURCC_DXT5:
  85983. blockBytes = 16;
  85984. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85985. break;
  85986. case FOURCC_D3DFMT_R16G16B16A16F:
  85987. computeFormats = true;
  85988. break;
  85989. case FOURCC_D3DFMT_R32G32B32A32F:
  85990. computeFormats = true;
  85991. break;
  85992. case FOURCC_DX10:
  85993. // There is an additionnal header so dataOffset need to be changed
  85994. dataOffset += 5 * 4; // 5 uints
  85995. var supported = false;
  85996. switch (info.dxgiFormat) {
  85997. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85998. computeFormats = true;
  85999. supported = true;
  86000. break;
  86001. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86002. info.isRGB = true;
  86003. info.isFourCC = false;
  86004. bpp = 32;
  86005. supported = true;
  86006. break;
  86007. }
  86008. if (supported) {
  86009. break;
  86010. }
  86011. default:
  86012. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86013. return;
  86014. }
  86015. }
  86016. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86017. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86018. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86019. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86020. if (computeFormats) {
  86021. format = engine._getWebGLTextureType(info.textureType);
  86022. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86023. }
  86024. mipmapCount = 1;
  86025. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86026. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86027. }
  86028. for (var face = 0; face < faces; face++) {
  86029. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86030. width = header[off_width];
  86031. height = header[off_height];
  86032. for (mip = 0; mip < mipmapCount; ++mip) {
  86033. if (lodIndex === -1 || lodIndex === mip) {
  86034. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86035. var i = (lodIndex === -1) ? mip : 0;
  86036. if (!info.isCompressed && info.isFourCC) {
  86037. dataLength = width * height * 4;
  86038. var floatArray = null;
  86039. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86040. if (bpp === 128) {
  86041. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86042. if (sphericalPolynomialFaces && i == 0) {
  86043. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86044. }
  86045. }
  86046. else if (bpp === 64) {
  86047. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86048. if (sphericalPolynomialFaces && i == 0) {
  86049. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86050. }
  86051. }
  86052. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86053. format = engine._getWebGLTextureType(info.textureType);
  86054. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86055. }
  86056. else {
  86057. if (bpp === 128) {
  86058. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86059. if (sphericalPolynomialFaces && i == 0) {
  86060. sphericalPolynomialFaces.push(floatArray);
  86061. }
  86062. }
  86063. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86064. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86065. if (sphericalPolynomialFaces && i == 0) {
  86066. sphericalPolynomialFaces.push(floatArray);
  86067. }
  86068. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86069. format = engine._getWebGLTextureType(info.textureType);
  86070. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86071. }
  86072. else { // 64
  86073. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86074. if (sphericalPolynomialFaces && i == 0) {
  86075. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86076. }
  86077. }
  86078. }
  86079. if (floatArray) {
  86080. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86081. }
  86082. }
  86083. else if (info.isRGB) {
  86084. if (bpp === 24) {
  86085. dataLength = width * height * 3;
  86086. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86087. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86088. }
  86089. else { // 32
  86090. dataLength = width * height * 4;
  86091. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86092. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86093. }
  86094. }
  86095. else if (info.isLuminance) {
  86096. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86097. var unpaddedRowSize = width;
  86098. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86099. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86100. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86101. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86102. }
  86103. else {
  86104. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86105. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86106. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86107. }
  86108. }
  86109. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86110. width *= 0.5;
  86111. height *= 0.5;
  86112. width = Math.max(1.0, width);
  86113. height = Math.max(1.0, height);
  86114. }
  86115. if (currentFace !== undefined) {
  86116. // Loading a single face
  86117. break;
  86118. }
  86119. }
  86120. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86121. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86122. size: header[off_width],
  86123. right: sphericalPolynomialFaces[0],
  86124. left: sphericalPolynomialFaces[1],
  86125. up: sphericalPolynomialFaces[2],
  86126. down: sphericalPolynomialFaces[3],
  86127. front: sphericalPolynomialFaces[4],
  86128. back: sphericalPolynomialFaces[5],
  86129. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86130. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86131. gammaSpace: false,
  86132. });
  86133. }
  86134. else {
  86135. info.sphericalPolynomial = undefined;
  86136. }
  86137. };
  86138. DDSTools.StoreLODInAlphaChannel = false;
  86139. return DDSTools;
  86140. }());
  86141. BABYLON.DDSTools = DDSTools;
  86142. })(BABYLON || (BABYLON = {}));
  86143. //# sourceMappingURL=babylon.dds.js.map
  86144. var BABYLON;
  86145. (function (BABYLON) {
  86146. /**
  86147. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86148. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86149. */
  86150. var KhronosTextureContainer = /** @class */ (function () {
  86151. /**
  86152. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86153. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86154. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86155. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86156. */
  86157. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86158. this.arrayBuffer = arrayBuffer;
  86159. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86160. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86161. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86162. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86163. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86164. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86165. BABYLON.Tools.Error("texture missing KTX identifier");
  86166. return;
  86167. }
  86168. // load the reset of the header in native 32 bit int
  86169. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86170. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86171. var oppositeEndianess = header[0] === 0x01020304;
  86172. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86173. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86174. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86175. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86176. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86177. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86178. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86179. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86180. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86181. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86182. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86183. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86184. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86185. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86186. if (this.glType !== 0) {
  86187. BABYLON.Tools.Error("only compressed formats currently supported");
  86188. return;
  86189. }
  86190. else {
  86191. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86192. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86193. }
  86194. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86195. BABYLON.Tools.Error("only 2D textures currently supported");
  86196. return;
  86197. }
  86198. if (this.numberOfArrayElements !== 0) {
  86199. BABYLON.Tools.Error("texture arrays not currently supported");
  86200. return;
  86201. }
  86202. if (this.numberOfFaces !== facesExpected) {
  86203. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86204. return;
  86205. }
  86206. // we now have a completely validated file, so could use existence of loadType as success
  86207. // would need to make this more elaborate & adjust checks above to support more than one load type
  86208. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86209. }
  86210. // not as fast hardware based, but will probably never need to use
  86211. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86212. return ((val & 0xFF) << 24)
  86213. | ((val & 0xFF00) << 8)
  86214. | ((val >> 8) & 0xFF00)
  86215. | ((val >> 24) & 0xFF);
  86216. };
  86217. /**
  86218. * It is assumed that the texture has already been created & is currently bound
  86219. */
  86220. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86221. switch (this.loadType) {
  86222. case KhronosTextureContainer.COMPRESSED_2D:
  86223. this._upload2DCompressedLevels(gl, loadMipmaps);
  86224. break;
  86225. case KhronosTextureContainer.TEX_2D:
  86226. case KhronosTextureContainer.COMPRESSED_3D:
  86227. case KhronosTextureContainer.TEX_3D:
  86228. }
  86229. };
  86230. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86231. // initialize width & height for level 1
  86232. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86233. var width = this.pixelWidth;
  86234. var height = this.pixelHeight;
  86235. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86236. for (var level = 0; level < mipmapCount; level++) {
  86237. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86238. for (var face = 0; face < this.numberOfFaces; face++) {
  86239. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86240. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86241. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86242. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86243. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86244. }
  86245. width = Math.max(1.0, width * 0.5);
  86246. height = Math.max(1.0, height * 0.5);
  86247. }
  86248. };
  86249. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86250. // load types
  86251. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86252. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86253. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86254. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86255. return KhronosTextureContainer;
  86256. }());
  86257. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86258. })(BABYLON || (BABYLON = {}));
  86259. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86260. var BABYLON;
  86261. (function (BABYLON) {
  86262. var Debug;
  86263. (function (Debug) {
  86264. /**
  86265. * Class used to render a debug view of a given skeleton
  86266. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86267. */
  86268. var SkeletonViewer = /** @class */ (function () {
  86269. /**
  86270. * Creates a new SkeletonViewer
  86271. * @param skeleton defines the skeleton to render
  86272. * @param mesh defines the mesh attached to the skeleton
  86273. * @param scene defines the hosting scene
  86274. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86275. * @param renderingGroupId defines the rendering group id to use with the viewer
  86276. */
  86277. function SkeletonViewer(
  86278. /** defines the skeleton to render */
  86279. skeleton,
  86280. /** defines the mesh attached to the skeleton */
  86281. mesh, scene,
  86282. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86283. autoUpdateBonesMatrices,
  86284. /** defines the rendering group id to use with the viewer */
  86285. renderingGroupId) {
  86286. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86287. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86288. this.skeleton = skeleton;
  86289. this.mesh = mesh;
  86290. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86291. this.renderingGroupId = renderingGroupId;
  86292. /** Gets or sets the color used to render the skeleton */
  86293. this.color = BABYLON.Color3.White();
  86294. this._debugLines = new Array();
  86295. this._isEnabled = false;
  86296. this._scene = scene;
  86297. this.update();
  86298. this._renderFunction = this.update.bind(this);
  86299. }
  86300. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86301. get: function () {
  86302. return this._isEnabled;
  86303. },
  86304. /** Gets or sets a boolean indicating if the viewer is enabled */
  86305. set: function (value) {
  86306. if (this._isEnabled === value) {
  86307. return;
  86308. }
  86309. this._isEnabled = value;
  86310. if (value) {
  86311. this._scene.registerBeforeRender(this._renderFunction);
  86312. }
  86313. else {
  86314. this._scene.unregisterBeforeRender(this._renderFunction);
  86315. }
  86316. },
  86317. enumerable: true,
  86318. configurable: true
  86319. });
  86320. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86321. if (x === void 0) { x = 0; }
  86322. if (y === void 0) { y = 0; }
  86323. if (z === void 0) { z = 0; }
  86324. var tmat = BABYLON.Tmp.Matrix[0];
  86325. var parentBone = bone.getParent();
  86326. tmat.copyFrom(bone.getLocalMatrix());
  86327. if (x !== 0 || y !== 0 || z !== 0) {
  86328. var tmat2 = BABYLON.Tmp.Matrix[1];
  86329. BABYLON.Matrix.IdentityToRef(tmat2);
  86330. tmat2.m[12] = x;
  86331. tmat2.m[13] = y;
  86332. tmat2.m[14] = z;
  86333. tmat2.multiplyToRef(tmat, tmat);
  86334. }
  86335. if (parentBone) {
  86336. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86337. }
  86338. tmat.multiplyToRef(meshMat, tmat);
  86339. position.x = tmat.m[12];
  86340. position.y = tmat.m[13];
  86341. position.z = tmat.m[14];
  86342. };
  86343. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86344. var len = bones.length;
  86345. var meshPos = this.mesh.position;
  86346. for (var i = 0; i < len; i++) {
  86347. var bone = bones[i];
  86348. var points = this._debugLines[i];
  86349. if (!points) {
  86350. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86351. this._debugLines[i] = points;
  86352. }
  86353. this._getBonePosition(points[0], bone, meshMat);
  86354. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86355. points[0].subtractInPlace(meshPos);
  86356. points[1].subtractInPlace(meshPos);
  86357. }
  86358. };
  86359. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86360. var len = bones.length;
  86361. var boneNum = 0;
  86362. var meshPos = this.mesh.position;
  86363. for (var i = len - 1; i >= 0; i--) {
  86364. var childBone = bones[i];
  86365. var parentBone = childBone.getParent();
  86366. if (!parentBone) {
  86367. continue;
  86368. }
  86369. var points = this._debugLines[boneNum];
  86370. if (!points) {
  86371. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86372. this._debugLines[boneNum] = points;
  86373. }
  86374. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86375. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86376. points[0].subtractInPlace(meshPos);
  86377. points[1].subtractInPlace(meshPos);
  86378. boneNum++;
  86379. }
  86380. };
  86381. /** Update the viewer to sync with current skeleton state */
  86382. SkeletonViewer.prototype.update = function () {
  86383. if (this.autoUpdateBonesMatrices) {
  86384. this.skeleton.computeAbsoluteTransforms();
  86385. }
  86386. if (this.skeleton.bones[0].length === undefined) {
  86387. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86388. }
  86389. else {
  86390. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86391. }
  86392. if (!this._debugMesh) {
  86393. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86394. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86395. }
  86396. else {
  86397. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86398. }
  86399. this._debugMesh.position.copyFrom(this.mesh.position);
  86400. this._debugMesh.color = this.color;
  86401. };
  86402. /** Release associated resources */
  86403. SkeletonViewer.prototype.dispose = function () {
  86404. if (this._debugMesh) {
  86405. this.isEnabled = false;
  86406. this._debugMesh.dispose();
  86407. this._debugMesh = null;
  86408. }
  86409. };
  86410. return SkeletonViewer;
  86411. }());
  86412. Debug.SkeletonViewer = SkeletonViewer;
  86413. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86414. })(BABYLON || (BABYLON = {}));
  86415. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86416. /**
  86417. * Module Debug contains the (visual) components to debug a scene correctly
  86418. */
  86419. var BABYLON;
  86420. (function (BABYLON) {
  86421. var Debug;
  86422. (function (Debug) {
  86423. /**
  86424. * The Axes viewer will show 3 axes in a specific point in space
  86425. */
  86426. var AxesViewer = /** @class */ (function () {
  86427. /**
  86428. * Creates a new AxesViewer
  86429. * @param scene defines the hosting scene
  86430. * @param scaleLines defines a number used to scale line length (1 by default)
  86431. */
  86432. function AxesViewer(scene, scaleLines) {
  86433. if (scaleLines === void 0) { scaleLines = 1; }
  86434. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86435. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86436. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86437. /**
  86438. * Gets or sets a number used to scale line length
  86439. */
  86440. this.scaleLines = 1;
  86441. this.scaleLines = scaleLines;
  86442. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86443. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86444. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86445. this._xmesh.renderingGroupId = 2;
  86446. this._ymesh.renderingGroupId = 2;
  86447. this._zmesh.renderingGroupId = 2;
  86448. this._xmesh.material.checkReadyOnlyOnce = true;
  86449. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86450. this._ymesh.material.checkReadyOnlyOnce = true;
  86451. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86452. this._zmesh.material.checkReadyOnlyOnce = true;
  86453. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86454. this.scene = scene;
  86455. }
  86456. /**
  86457. * Force the viewer to update
  86458. * @param position defines the position of the viewer
  86459. * @param xaxis defines the x axis of the viewer
  86460. * @param yaxis defines the y axis of the viewer
  86461. * @param zaxis defines the z axis of the viewer
  86462. */
  86463. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86464. var scaleLines = this.scaleLines;
  86465. if (this._xmesh) {
  86466. this._xmesh.position.copyFrom(position);
  86467. }
  86468. if (this._ymesh) {
  86469. this._ymesh.position.copyFrom(position);
  86470. }
  86471. if (this._zmesh) {
  86472. this._zmesh.position.copyFrom(position);
  86473. }
  86474. var point2 = this._xline[1];
  86475. point2.x = xaxis.x * scaleLines;
  86476. point2.y = xaxis.y * scaleLines;
  86477. point2.z = xaxis.z * scaleLines;
  86478. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86479. point2 = this._yline[1];
  86480. point2.x = yaxis.x * scaleLines;
  86481. point2.y = yaxis.y * scaleLines;
  86482. point2.z = yaxis.z * scaleLines;
  86483. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86484. point2 = this._zline[1];
  86485. point2.x = zaxis.x * scaleLines;
  86486. point2.y = zaxis.y * scaleLines;
  86487. point2.z = zaxis.z * scaleLines;
  86488. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86489. };
  86490. /** Releases resources */
  86491. AxesViewer.prototype.dispose = function () {
  86492. if (this._xmesh) {
  86493. this._xmesh.dispose();
  86494. }
  86495. if (this._ymesh) {
  86496. this._ymesh.dispose();
  86497. }
  86498. if (this._zmesh) {
  86499. this._zmesh.dispose();
  86500. }
  86501. this._xmesh = null;
  86502. this._ymesh = null;
  86503. this._zmesh = null;
  86504. this.scene = null;
  86505. };
  86506. return AxesViewer;
  86507. }());
  86508. Debug.AxesViewer = AxesViewer;
  86509. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86510. })(BABYLON || (BABYLON = {}));
  86511. //# sourceMappingURL=babylon.axesViewer.js.map
  86512. var BABYLON;
  86513. (function (BABYLON) {
  86514. var Debug;
  86515. (function (Debug) {
  86516. /**
  86517. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86518. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86519. */
  86520. var BoneAxesViewer = /** @class */ (function (_super) {
  86521. __extends(BoneAxesViewer, _super);
  86522. /**
  86523. * Creates a new BoneAxesViewer
  86524. * @param scene defines the hosting scene
  86525. * @param bone defines the target bone
  86526. * @param mesh defines the target mesh
  86527. * @param scaleLines defines a scaling factor for line length (1 by default)
  86528. */
  86529. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86530. if (scaleLines === void 0) { scaleLines = 1; }
  86531. var _this = _super.call(this, scene, scaleLines) || this;
  86532. /** Gets current position */
  86533. _this.pos = BABYLON.Vector3.Zero();
  86534. /** Gets direction of X axis */
  86535. _this.xaxis = BABYLON.Vector3.Zero();
  86536. /** Gets direction of Y axis */
  86537. _this.yaxis = BABYLON.Vector3.Zero();
  86538. /** Gets direction of Z axis */
  86539. _this.zaxis = BABYLON.Vector3.Zero();
  86540. _this.mesh = mesh;
  86541. _this.bone = bone;
  86542. return _this;
  86543. }
  86544. /**
  86545. * Force the viewer to update
  86546. */
  86547. BoneAxesViewer.prototype.update = function () {
  86548. if (!this.mesh || !this.bone) {
  86549. return;
  86550. }
  86551. var bone = this.bone;
  86552. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86553. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86554. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86555. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86556. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86557. };
  86558. /** Releases resources */
  86559. BoneAxesViewer.prototype.dispose = function () {
  86560. if (this.mesh) {
  86561. this.mesh = null;
  86562. this.bone = null;
  86563. _super.prototype.dispose.call(this);
  86564. }
  86565. };
  86566. return BoneAxesViewer;
  86567. }(Debug.AxesViewer));
  86568. Debug.BoneAxesViewer = BoneAxesViewer;
  86569. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86570. })(BABYLON || (BABYLON = {}));
  86571. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86572. var BABYLON;
  86573. (function (BABYLON) {
  86574. var RayHelper = /** @class */ (function () {
  86575. function RayHelper(ray) {
  86576. this.ray = ray;
  86577. }
  86578. RayHelper.CreateAndShow = function (ray, scene, color) {
  86579. var helper = new RayHelper(ray);
  86580. helper.show(scene, color);
  86581. return helper;
  86582. };
  86583. RayHelper.prototype.show = function (scene, color) {
  86584. if (!this._renderFunction && this.ray) {
  86585. var ray = this.ray;
  86586. this._renderFunction = this._render.bind(this);
  86587. this._scene = scene;
  86588. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86589. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86590. if (this._renderFunction) {
  86591. this._scene.registerBeforeRender(this._renderFunction);
  86592. }
  86593. }
  86594. if (color && this._renderLine) {
  86595. this._renderLine.color.copyFrom(color);
  86596. }
  86597. };
  86598. RayHelper.prototype.hide = function () {
  86599. if (this._renderFunction && this._scene) {
  86600. this._scene.unregisterBeforeRender(this._renderFunction);
  86601. this._scene = null;
  86602. this._renderFunction = null;
  86603. if (this._renderLine) {
  86604. this._renderLine.dispose();
  86605. this._renderLine = null;
  86606. }
  86607. this._renderPoints = [];
  86608. }
  86609. };
  86610. RayHelper.prototype._render = function () {
  86611. var ray = this.ray;
  86612. if (!ray) {
  86613. return;
  86614. }
  86615. var point = this._renderPoints[1];
  86616. var len = Math.min(ray.length, 1000000);
  86617. point.copyFrom(ray.direction);
  86618. point.scaleInPlace(len);
  86619. point.addInPlace(ray.origin);
  86620. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86621. };
  86622. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86623. this._attachedToMesh = mesh;
  86624. var ray = this.ray;
  86625. if (!ray) {
  86626. return;
  86627. }
  86628. if (!ray.direction) {
  86629. ray.direction = BABYLON.Vector3.Zero();
  86630. }
  86631. if (!ray.origin) {
  86632. ray.origin = BABYLON.Vector3.Zero();
  86633. }
  86634. if (length) {
  86635. ray.length = length;
  86636. }
  86637. if (!meshSpaceOrigin) {
  86638. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86639. }
  86640. if (!meshSpaceDirection) {
  86641. // -1 so that this will work with Mesh.lookAt
  86642. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86643. }
  86644. if (!this._meshSpaceDirection) {
  86645. this._meshSpaceDirection = meshSpaceDirection.clone();
  86646. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86647. }
  86648. else {
  86649. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86650. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86651. }
  86652. if (!this._updateToMeshFunction) {
  86653. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86654. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86655. }
  86656. this._updateToMesh();
  86657. };
  86658. RayHelper.prototype.detachFromMesh = function () {
  86659. if (this._attachedToMesh) {
  86660. if (this._updateToMeshFunction) {
  86661. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86662. }
  86663. this._attachedToMesh = null;
  86664. this._updateToMeshFunction = null;
  86665. }
  86666. };
  86667. RayHelper.prototype._updateToMesh = function () {
  86668. var ray = this.ray;
  86669. if (!this._attachedToMesh || !ray) {
  86670. return;
  86671. }
  86672. if (this._attachedToMesh._isDisposed) {
  86673. this.detachFromMesh();
  86674. return;
  86675. }
  86676. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86677. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86678. };
  86679. RayHelper.prototype.dispose = function () {
  86680. this.hide();
  86681. this.detachFromMesh();
  86682. this.ray = null;
  86683. };
  86684. return RayHelper;
  86685. }());
  86686. BABYLON.RayHelper = RayHelper;
  86687. })(BABYLON || (BABYLON = {}));
  86688. //# sourceMappingURL=babylon.rayHelper.js.map
  86689. var BABYLON;
  86690. (function (BABYLON) {
  86691. // load the inspector using require, if not present in the global namespace.
  86692. var DebugLayer = /** @class */ (function () {
  86693. function DebugLayer(scene) {
  86694. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86695. this._scene = scene;
  86696. // load inspector using require, if it doesn't exist on the global namespace.
  86697. }
  86698. /** Creates the inspector window. */
  86699. DebugLayer.prototype._createInspector = function (config) {
  86700. if (config === void 0) { config = {}; }
  86701. var popup = config.popup || false;
  86702. var initialTab = config.initialTab || 0;
  86703. var parentElement = config.parentElement || null;
  86704. if (!this._inspector) {
  86705. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86706. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86707. } // else nothing to do,; instance is already existing
  86708. };
  86709. DebugLayer.prototype.isVisible = function () {
  86710. if (!this._inspector) {
  86711. return false;
  86712. }
  86713. return true;
  86714. };
  86715. DebugLayer.prototype.hide = function () {
  86716. if (this._inspector) {
  86717. try {
  86718. this._inspector.dispose();
  86719. }
  86720. catch (e) {
  86721. // If the inspector has been removed directly from the inspector tool
  86722. }
  86723. this.onPropertyChangedObservable.clear();
  86724. this._inspector = null;
  86725. }
  86726. };
  86727. /**
  86728. *
  86729. * Launch the debugLayer.
  86730. *
  86731. * initialTab:
  86732. * | Value | Tab Name |
  86733. * | --- | --- |
  86734. * | 0 | Scene |
  86735. * | 1 | Console |
  86736. * | 2 | Stats |
  86737. * | 3 | Textures |
  86738. * | 4 | Mesh |
  86739. * | 5 | Light |
  86740. * | 6 | Material |
  86741. * | 7 | GLTF |
  86742. * | 8 | GUI |
  86743. * | 9 | Physics |
  86744. * | 10 | Camera |
  86745. * | 11 | Audio |
  86746. *
  86747. */
  86748. DebugLayer.prototype.show = function (config) {
  86749. if (config === void 0) { config = {}; }
  86750. if (typeof this.BJSINSPECTOR == 'undefined') {
  86751. // Load inspector and add it to the DOM
  86752. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86753. }
  86754. else {
  86755. // Otherwise creates the inspector
  86756. this._createInspector(config);
  86757. this.onPropertyChangedObservable = new BABYLON.Observable();
  86758. }
  86759. };
  86760. /**
  86761. * Gets the active tab
  86762. * @return the index of the active tab or -1 if the inspector is hidden
  86763. */
  86764. DebugLayer.prototype.getActiveTab = function () {
  86765. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86766. };
  86767. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86768. return DebugLayer;
  86769. }());
  86770. BABYLON.DebugLayer = DebugLayer;
  86771. })(BABYLON || (BABYLON = {}));
  86772. //# sourceMappingURL=babylon.debugLayer.js.map
  86773. var BABYLON;
  86774. (function (BABYLON) {
  86775. var Debug;
  86776. (function (Debug) {
  86777. /**
  86778. * Used to show the physics impostor around the specific mesh
  86779. */
  86780. var PhysicsViewer = /** @class */ (function () {
  86781. /**
  86782. * Creates a new PhysicsViewer
  86783. * @param scene defines the hosting scene
  86784. */
  86785. function PhysicsViewer(scene) {
  86786. /** @hidden */
  86787. this._impostors = [];
  86788. /** @hidden */
  86789. this._meshes = [];
  86790. /** @hidden */
  86791. this._numMeshes = 0;
  86792. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86793. var physicEngine = this._scene.getPhysicsEngine();
  86794. if (physicEngine) {
  86795. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86796. }
  86797. }
  86798. /** @hidden */
  86799. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86800. var plugin = this._physicsEnginePlugin;
  86801. for (var i = 0; i < this._numMeshes; i++) {
  86802. var impostor = this._impostors[i];
  86803. if (!impostor) {
  86804. continue;
  86805. }
  86806. if (impostor.isDisposed) {
  86807. this.hideImpostor(this._impostors[i--]);
  86808. }
  86809. else {
  86810. var mesh = this._meshes[i];
  86811. if (mesh && plugin) {
  86812. plugin.syncMeshWithImpostor(mesh, impostor);
  86813. }
  86814. }
  86815. }
  86816. };
  86817. /**
  86818. * Renders a specified physic impostor
  86819. * @param impostor defines the impostor to render
  86820. */
  86821. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86822. if (!this._scene) {
  86823. return;
  86824. }
  86825. for (var i = 0; i < this._numMeshes; i++) {
  86826. if (this._impostors[i] == impostor) {
  86827. return;
  86828. }
  86829. }
  86830. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86831. if (debugMesh) {
  86832. this._impostors[this._numMeshes] = impostor;
  86833. this._meshes[this._numMeshes] = debugMesh;
  86834. if (this._numMeshes === 0) {
  86835. this._renderFunction = this._updateDebugMeshes.bind(this);
  86836. this._scene.registerBeforeRender(this._renderFunction);
  86837. }
  86838. this._numMeshes++;
  86839. }
  86840. };
  86841. /**
  86842. * Hides a specified physic impostor
  86843. * @param impostor defines the impostor to hide
  86844. */
  86845. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86846. if (!impostor || !this._scene) {
  86847. return;
  86848. }
  86849. var removed = false;
  86850. for (var i = 0; i < this._numMeshes; i++) {
  86851. if (this._impostors[i] == impostor) {
  86852. var mesh = this._meshes[i];
  86853. if (!mesh) {
  86854. continue;
  86855. }
  86856. this._scene.removeMesh(mesh);
  86857. mesh.dispose();
  86858. this._numMeshes--;
  86859. if (this._numMeshes > 0) {
  86860. this._meshes[i] = this._meshes[this._numMeshes];
  86861. this._impostors[i] = this._impostors[this._numMeshes];
  86862. this._meshes[this._numMeshes] = null;
  86863. this._impostors[this._numMeshes] = null;
  86864. }
  86865. else {
  86866. this._meshes[0] = null;
  86867. this._impostors[0] = null;
  86868. }
  86869. removed = true;
  86870. break;
  86871. }
  86872. }
  86873. if (removed && this._numMeshes === 0) {
  86874. this._scene.unregisterBeforeRender(this._renderFunction);
  86875. }
  86876. };
  86877. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86878. if (!this._debugMaterial) {
  86879. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86880. this._debugMaterial.wireframe = true;
  86881. }
  86882. return this._debugMaterial;
  86883. };
  86884. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86885. if (!this._debugBoxMesh) {
  86886. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86887. this._debugBoxMesh.renderingGroupId = 1;
  86888. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86889. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86890. scene.removeMesh(this._debugBoxMesh);
  86891. }
  86892. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86893. };
  86894. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86895. if (!this._debugSphereMesh) {
  86896. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86897. this._debugSphereMesh.renderingGroupId = 1;
  86898. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86899. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86900. scene.removeMesh(this._debugSphereMesh);
  86901. }
  86902. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86903. };
  86904. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86905. var mesh = null;
  86906. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86907. mesh = this._getDebugBoxMesh(scene);
  86908. impostor.getBoxSizeToRef(mesh.scaling);
  86909. }
  86910. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86911. mesh = this._getDebugSphereMesh(scene);
  86912. var radius = impostor.getRadius();
  86913. mesh.scaling.x = radius * 2;
  86914. mesh.scaling.y = radius * 2;
  86915. mesh.scaling.z = radius * 2;
  86916. }
  86917. return mesh;
  86918. };
  86919. /** Releases all resources */
  86920. PhysicsViewer.prototype.dispose = function () {
  86921. for (var i = 0; i < this._numMeshes; i++) {
  86922. this.hideImpostor(this._impostors[i]);
  86923. }
  86924. if (this._debugBoxMesh) {
  86925. this._debugBoxMesh.dispose();
  86926. }
  86927. if (this._debugSphereMesh) {
  86928. this._debugSphereMesh.dispose();
  86929. }
  86930. if (this._debugMaterial) {
  86931. this._debugMaterial.dispose();
  86932. }
  86933. this._impostors.length = 0;
  86934. this._scene = null;
  86935. this._physicsEnginePlugin = null;
  86936. };
  86937. return PhysicsViewer;
  86938. }());
  86939. Debug.PhysicsViewer = PhysicsViewer;
  86940. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86941. })(BABYLON || (BABYLON = {}));
  86942. //# sourceMappingURL=babylon.physicsViewer.js.map
  86943. var BABYLON;
  86944. (function (BABYLON) {
  86945. var BoundingBoxRenderer = /** @class */ (function () {
  86946. function BoundingBoxRenderer(scene) {
  86947. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86948. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86949. this.showBackLines = true;
  86950. this.renderList = new BABYLON.SmartArray(32);
  86951. this._vertexBuffers = {};
  86952. this._scene = scene;
  86953. }
  86954. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86955. if (this._colorShader) {
  86956. return;
  86957. }
  86958. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86959. attributes: [BABYLON.VertexBuffer.PositionKind],
  86960. uniforms: ["world", "viewProjection", "color"]
  86961. });
  86962. var engine = this._scene.getEngine();
  86963. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86964. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86965. this._createIndexBuffer();
  86966. };
  86967. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86968. var engine = this._scene.getEngine();
  86969. 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]);
  86970. };
  86971. BoundingBoxRenderer.prototype._rebuild = function () {
  86972. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86973. if (vb) {
  86974. vb._rebuild();
  86975. }
  86976. this._createIndexBuffer();
  86977. };
  86978. BoundingBoxRenderer.prototype.reset = function () {
  86979. this.renderList.reset();
  86980. };
  86981. BoundingBoxRenderer.prototype.render = function () {
  86982. if (this.renderList.length === 0) {
  86983. return;
  86984. }
  86985. this._prepareRessources();
  86986. if (!this._colorShader.isReady()) {
  86987. return;
  86988. }
  86989. var engine = this._scene.getEngine();
  86990. engine.setDepthWrite(false);
  86991. this._colorShader._preBind();
  86992. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86993. var boundingBox = this.renderList.data[boundingBoxIndex];
  86994. var min = boundingBox.minimum;
  86995. var max = boundingBox.maximum;
  86996. var diff = max.subtract(min);
  86997. var median = min.add(diff.scale(0.5));
  86998. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86999. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87000. .multiply(boundingBox.getWorldMatrix());
  87001. // VBOs
  87002. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87003. if (this.showBackLines) {
  87004. // Back
  87005. engine.setDepthFunctionToGreaterOrEqual();
  87006. this._scene.resetCachedMaterial();
  87007. this._colorShader.setColor4("color", this.backColor.toColor4());
  87008. this._colorShader.bind(worldMatrix);
  87009. // Draw order
  87010. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87011. }
  87012. // Front
  87013. engine.setDepthFunctionToLess();
  87014. this._scene.resetCachedMaterial();
  87015. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87016. this._colorShader.bind(worldMatrix);
  87017. // Draw order
  87018. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87019. }
  87020. this._colorShader.unbind();
  87021. engine.setDepthFunctionToLessOrEqual();
  87022. engine.setDepthWrite(true);
  87023. };
  87024. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87025. this._prepareRessources();
  87026. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87027. return;
  87028. }
  87029. var engine = this._scene.getEngine();
  87030. engine.setDepthWrite(false);
  87031. engine.setColorWrite(false);
  87032. this._colorShader._preBind();
  87033. var boundingBox = mesh._boundingInfo.boundingBox;
  87034. var min = boundingBox.minimum;
  87035. var max = boundingBox.maximum;
  87036. var diff = max.subtract(min);
  87037. var median = min.add(diff.scale(0.5));
  87038. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87039. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87040. .multiply(boundingBox.getWorldMatrix());
  87041. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87042. engine.setDepthFunctionToLess();
  87043. this._scene.resetCachedMaterial();
  87044. this._colorShader.bind(worldMatrix);
  87045. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87046. this._colorShader.unbind();
  87047. engine.setDepthFunctionToLessOrEqual();
  87048. engine.setDepthWrite(true);
  87049. engine.setColorWrite(true);
  87050. };
  87051. BoundingBoxRenderer.prototype.dispose = function () {
  87052. if (!this._colorShader) {
  87053. return;
  87054. }
  87055. this.renderList.dispose();
  87056. this._colorShader.dispose();
  87057. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87058. if (buffer) {
  87059. buffer.dispose();
  87060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87061. }
  87062. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87063. };
  87064. return BoundingBoxRenderer;
  87065. }());
  87066. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87067. })(BABYLON || (BABYLON = {}));
  87068. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87069. var BABYLON;
  87070. (function (BABYLON) {
  87071. /**
  87072. * Renders a layer on top of an existing scene
  87073. */
  87074. var UtilityLayerRenderer = /** @class */ (function () {
  87075. /**
  87076. * Instantiates a UtilityLayerRenderer
  87077. * @param originalScene the original scene that will be rendered on top of
  87078. */
  87079. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87080. var _this = this;
  87081. this.originalScene = originalScene;
  87082. this._pointerCaptures = {};
  87083. this._lastPointerEvents = {};
  87084. /**
  87085. * If the utility layer should automatically be rendered on top of existing scene
  87086. */
  87087. this.shouldRender = true;
  87088. /**
  87089. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87090. */
  87091. this.onlyCheckPointerDownEvents = true;
  87092. /**
  87093. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87094. */
  87095. this.processAllEvents = false;
  87096. /**
  87097. * Observable raised when the pointer move from the utility layer scene to the main scene
  87098. */
  87099. this.onPointerOutObservable = new BABYLON.Observable();
  87100. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87101. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87102. originalScene.getEngine().scenes.pop();
  87103. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87104. this.utilityLayerScene.detachControl();
  87105. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87106. if (!_this.processAllEvents) {
  87107. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87108. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87109. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87110. return;
  87111. }
  87112. }
  87113. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87114. if (!prePointerInfo.ray && utilityScenePick) {
  87115. prePointerInfo.ray = utilityScenePick.ray;
  87116. }
  87117. // always fire the prepointer oversvable
  87118. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87119. // allow every non pointer down event to flow to the utility layer
  87120. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87121. if (!prePointerInfo.skipOnPointerObservable) {
  87122. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87123. }
  87124. var pointerEvent = (prePointerInfo.event);
  87125. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87126. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87127. }
  87128. return;
  87129. }
  87130. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87131. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87132. if (utilityScenePick && utilityScenePick.hit) {
  87133. if (!prePointerInfo.skipOnPointerObservable) {
  87134. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87135. }
  87136. prePointerInfo.skipOnPointerObservable = true;
  87137. }
  87138. }
  87139. else {
  87140. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87141. var pointerEvent = (prePointerInfo.event);
  87142. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87143. if (originalScenePick && utilityScenePick) {
  87144. if (utilityScenePick.distance === 0) {
  87145. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87146. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87147. }
  87148. }
  87149. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87150. if (!prePointerInfo.skipOnPointerObservable) {
  87151. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87152. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87153. }
  87154. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87155. }
  87156. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87157. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87158. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87159. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87160. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87161. }
  87162. }
  87163. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87164. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87165. }
  87166. }
  87167. }
  87168. });
  87169. // Render directly on top of existing scene without clearing
  87170. this.utilityLayerScene.autoClear = false;
  87171. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87172. if (_this.shouldRender) {
  87173. _this.render();
  87174. }
  87175. });
  87176. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87177. _this.dispose();
  87178. });
  87179. this._updateCamera();
  87180. }
  87181. /**
  87182. * Renders the utility layers scene on top of the original scene
  87183. */
  87184. UtilityLayerRenderer.prototype.render = function () {
  87185. this._updateCamera();
  87186. this.utilityLayerScene.render(false);
  87187. };
  87188. /**
  87189. * Disposes of the renderer
  87190. */
  87191. UtilityLayerRenderer.prototype.dispose = function () {
  87192. this.onPointerOutObservable.clear();
  87193. if (this._afterRenderObserver) {
  87194. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87195. }
  87196. if (this._sceneDisposeObserver) {
  87197. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87198. }
  87199. if (this._originalPointerObserver) {
  87200. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87201. }
  87202. this.utilityLayerScene.dispose();
  87203. };
  87204. UtilityLayerRenderer.prototype._updateCamera = function () {
  87205. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87206. };
  87207. return UtilityLayerRenderer;
  87208. }());
  87209. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87210. })(BABYLON || (BABYLON = {}));
  87211. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87212. //# sourceMappingURL=babylon.behavior.js.map
  87213. var BABYLON;
  87214. (function (BABYLON) {
  87215. /**
  87216. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87217. */
  87218. var PointerDragBehavior = /** @class */ (function () {
  87219. /**
  87220. * Creates a pointer drag behavior that can be attached to a mesh
  87221. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  87222. */
  87223. function PointerDragBehavior(options) {
  87224. this.options = options;
  87225. this._draggingID = -1;
  87226. // Debug mode will display drag planes to help visualize behavior
  87227. this._debugMode = false;
  87228. this._maxDragAngle = Math.PI / 5;
  87229. /**
  87230. * Fires each time the attached mesh is dragged with the pointer
  87231. * * delta between last drag position and current drag position in world space
  87232. * * dragDistance along the drag axis
  87233. * * dragPlaneNormal normal of the current drag plane used during the drag
  87234. * * dragPlanePoint in world space where the drag intersects the drag plane
  87235. */
  87236. this.onDragObservable = new BABYLON.Observable();
  87237. /**
  87238. * Fires each time a drag begins (eg. mouse down on mesh)
  87239. */
  87240. this.onDragStartObservable = new BABYLON.Observable();
  87241. /**
  87242. * Fires each time a drag ends (eg. mouse release after drag)
  87243. */
  87244. this.onDragEndObservable = new BABYLON.Observable();
  87245. /**
  87246. * If the attached mesh should be moved when dragged
  87247. */
  87248. this.moveAttached = true;
  87249. /**
  87250. * Mesh with the position where the drag plane should be placed
  87251. */
  87252. this._dragPlaneParent = null;
  87253. /**
  87254. * If the drag behavior will react to drag events
  87255. */
  87256. this.enabled = true;
  87257. var optionCount = 0;
  87258. if (options === undefined) {
  87259. options = {};
  87260. }
  87261. if (options.dragAxis) {
  87262. optionCount++;
  87263. }
  87264. if (options.dragPlaneNormal) {
  87265. optionCount++;
  87266. }
  87267. if (optionCount > 1) {
  87268. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87269. }
  87270. }
  87271. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87272. /**
  87273. * The name of the behavior
  87274. */
  87275. get: function () {
  87276. return "PointerDrag";
  87277. },
  87278. enumerable: true,
  87279. configurable: true
  87280. });
  87281. /**
  87282. * Initializes the behavior
  87283. */
  87284. PointerDragBehavior.prototype.init = function () { };
  87285. /**
  87286. * Attaches the drag behavior the passed in mesh
  87287. * @param ownerNode The mesh that will be dragged around once attached
  87288. */
  87289. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87290. var _this = this;
  87291. this._scene = ownerNode.getScene();
  87292. this._attachedNode = ownerNode;
  87293. // Initialize drag plane to not interfere with existing scene
  87294. if (!PointerDragBehavior._planeScene) {
  87295. if (this._debugMode) {
  87296. PointerDragBehavior._planeScene = this._scene;
  87297. }
  87298. else {
  87299. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87300. this._scene.getEngine().scenes.pop();
  87301. }
  87302. }
  87303. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87304. // State of the drag
  87305. var dragging = false;
  87306. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87307. var delta = new BABYLON.Vector3(0, 0, 0);
  87308. var dragLength = 0;
  87309. var pickPredicate = function (m) {
  87310. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87311. };
  87312. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87313. if (!_this.enabled) {
  87314. return;
  87315. }
  87316. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87317. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87318. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87319. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87320. if (pickedPoint) {
  87321. dragging = true;
  87322. _this._draggingID = pointerInfo.event.pointerId;
  87323. lastPosition.copyFrom(pickedPoint);
  87324. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87325. }
  87326. }
  87327. }
  87328. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87329. if (_this._draggingID == pointerInfo.event.pointerId) {
  87330. dragging = false;
  87331. _this._draggingID = -1;
  87332. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87333. }
  87334. }
  87335. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87336. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87337. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87338. // Get angle between drag plane and ray. Only update the drag plane at non steep angles to avoid jumps in delta position
  87339. var angle = Math.acos(BABYLON.Vector3.Dot(_this._dragPlane.forward, pointerInfo.pickInfo.ray.direction));
  87340. if (angle < _this._maxDragAngle) {
  87341. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87342. }
  87343. if (pickedPoint) {
  87344. // depending on the drag mode option drag accordingly
  87345. if (_this.options.dragAxis) {
  87346. // Convert local drag axis to world
  87347. var worldDragAxis = BABYLON.Vector3.TransformCoordinates(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix());
  87348. // Project delta drag from the drag plane onto the drag axis
  87349. dragLength = BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), worldDragAxis);
  87350. worldDragAxis.scaleToRef(dragLength, delta);
  87351. }
  87352. else {
  87353. dragLength = delta.length();
  87354. pickedPoint.subtractToRef(lastPosition, delta);
  87355. }
  87356. if (_this.moveAttached) {
  87357. _this._attachedNode.position.addInPlace(delta);
  87358. }
  87359. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward });
  87360. lastPosition.copyFrom(pickedPoint);
  87361. }
  87362. }
  87363. }
  87364. });
  87365. };
  87366. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87367. var _this = this;
  87368. if (!ray) {
  87369. return null;
  87370. }
  87371. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87372. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87373. return pickResult.pickedPoint;
  87374. }
  87375. else {
  87376. return null;
  87377. }
  87378. };
  87379. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87380. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87381. var pointA = this._dragPlaneParent ? this._dragPlaneParent.absolutePosition : this._attachedNode.absolutePosition;
  87382. if (this.options.dragAxis) {
  87383. var localAxis = BABYLON.Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  87384. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87385. var pointB = pointA.add(localAxis); // towards drag axis
  87386. var pointC = pointA.add(ray.origin.subtract(pointA).normalize()); // towards camera
  87387. // Get perpendicular line from direction to camera and drag axis
  87388. var lineA = pointB.subtract(pointA);
  87389. var lineB = pointC.subtract(pointA);
  87390. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87391. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87392. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87393. this._dragPlane.position.copyFrom(pointA);
  87394. this._dragPlane.lookAt(pointA.subtract(norm));
  87395. }
  87396. else if (this.options.dragPlaneNormal) {
  87397. this._dragPlane.position.copyFrom(pointA);
  87398. this._dragPlane.lookAt(pointA.subtract(this.options.dragPlaneNormal));
  87399. }
  87400. else {
  87401. this._dragPlane.position.copyFrom(pointA);
  87402. this._dragPlane.lookAt(ray.origin);
  87403. }
  87404. this._dragPlane.computeWorldMatrix(true);
  87405. };
  87406. /**
  87407. * Detaches the behavior from the mesh
  87408. */
  87409. PointerDragBehavior.prototype.detach = function () {
  87410. if (this._pointerObserver) {
  87411. this._scene.onPointerObservable.remove(this._pointerObserver);
  87412. }
  87413. };
  87414. return PointerDragBehavior;
  87415. }());
  87416. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87417. })(BABYLON || (BABYLON = {}));
  87418. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87419. var BABYLON;
  87420. (function (BABYLON) {
  87421. /**
  87422. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87423. */
  87424. var Gizmo = /** @class */ (function () {
  87425. /**
  87426. * Creates a gizmo
  87427. * @param gizmoLayer The utility layer the gizmo will be added to
  87428. */
  87429. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87430. var _this = this;
  87431. this.gizmoLayer = gizmoLayer;
  87432. /**
  87433. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  87434. */
  87435. this._updateScale = true;
  87436. this._interactionsEnabled = true;
  87437. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87438. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87439. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87440. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87441. _this._rootMesh.scaling.set(dist, dist, dist);
  87442. }
  87443. if (_this.attachedMesh) {
  87444. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87445. }
  87446. });
  87447. }
  87448. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87449. };
  87450. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87451. get: function () {
  87452. return this._interactionsEnabled;
  87453. },
  87454. /**
  87455. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87456. */
  87457. set: function (value) {
  87458. this._interactionsEnabled = value;
  87459. this._onInteractionsEnabledChanged(value);
  87460. },
  87461. enumerable: true,
  87462. configurable: true
  87463. });
  87464. /**
  87465. * Disposes of the gizmo
  87466. */
  87467. Gizmo.prototype.dispose = function () {
  87468. this._rootMesh.dispose();
  87469. if (this._beforeRenderObserver) {
  87470. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87471. }
  87472. };
  87473. return Gizmo;
  87474. }());
  87475. BABYLON.Gizmo = Gizmo;
  87476. })(BABYLON || (BABYLON = {}));
  87477. //# sourceMappingURL=babylon.gizmo.js.map
  87478. var BABYLON;
  87479. (function (BABYLON) {
  87480. /**
  87481. * Single axis drag gizmo
  87482. */
  87483. var AxisDragGizmo = /** @class */ (function (_super) {
  87484. __extends(AxisDragGizmo, _super);
  87485. /**
  87486. * Creates an AxisDragGizmo
  87487. * @param gizmoLayer The utility layer the gizmo will be added to
  87488. * @param dragAxis The axis which the gizmo will be able to drag on
  87489. * @param color The color of the gizmo
  87490. */
  87491. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87492. var _this = _super.call(this, gizmoLayer) || this;
  87493. // Create Material
  87494. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87495. coloredMaterial.disableLighting = true;
  87496. coloredMaterial.emissiveColor = color;
  87497. // Build mesh on root node
  87498. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87499. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87500. _this._rootMesh.addChild(arrowMesh);
  87501. _this._rootMesh.addChild(arrowTail);
  87502. // Position arrow pointing in its drag axis
  87503. arrowMesh.scaling.scaleInPlace(0.1);
  87504. arrowMesh.material = coloredMaterial;
  87505. arrowMesh.rotation.x = Math.PI / 2;
  87506. arrowMesh.position.z += 0.3;
  87507. arrowTail.rotation.x = Math.PI / 2;
  87508. arrowTail.material = coloredMaterial;
  87509. arrowTail.position.z += 0.2;
  87510. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87511. // Add drag behavior to handle events when the gizmo is dragged
  87512. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87513. _this._dragBehavior.moveAttached = false;
  87514. _this._rootMesh.addBehavior(_this._dragBehavior);
  87515. _this._dragBehavior.onDragObservable.add(function (event) {
  87516. if (!_this.interactionsEnabled) {
  87517. return;
  87518. }
  87519. if (_this.attachedMesh) {
  87520. _this.attachedMesh.position.addInPlace(event.delta);
  87521. }
  87522. });
  87523. return _this;
  87524. }
  87525. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87526. this._dragBehavior.enabled = value;
  87527. };
  87528. /**
  87529. * Disposes of the gizmo
  87530. */
  87531. AxisDragGizmo.prototype.dispose = function () {
  87532. this._dragBehavior.detach();
  87533. _super.prototype.dispose.call(this);
  87534. };
  87535. return AxisDragGizmo;
  87536. }(BABYLON.Gizmo));
  87537. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87538. })(BABYLON || (BABYLON = {}));
  87539. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87540. var BABYLON;
  87541. (function (BABYLON) {
  87542. /**
  87543. * Single axis scale gizmo
  87544. */
  87545. var AxisScaleGizmo = /** @class */ (function (_super) {
  87546. __extends(AxisScaleGizmo, _super);
  87547. /**
  87548. * Creates an AxisScaleGizmo
  87549. * @param gizmoLayer The utility layer the gizmo will be added to
  87550. * @param dragAxis The axis which the gizmo will be able to scale on
  87551. * @param color The color of the gizmo
  87552. */
  87553. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87554. var _this = _super.call(this, gizmoLayer) || this;
  87555. // Create Material
  87556. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87557. coloredMaterial.disableLighting = true;
  87558. coloredMaterial.emissiveColor = color;
  87559. // Build mesh on root node
  87560. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87561. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87562. _this._rootMesh.addChild(arrowMesh);
  87563. _this._rootMesh.addChild(arrowTail);
  87564. // Position arrow pointing in its drag axis
  87565. arrowMesh.scaling.scaleInPlace(0.1);
  87566. arrowMesh.material = coloredMaterial;
  87567. arrowMesh.rotation.x = Math.PI / 2;
  87568. arrowMesh.position.z += 0.3;
  87569. arrowTail.rotation.x = Math.PI / 2;
  87570. arrowTail.material = coloredMaterial;
  87571. arrowTail.position.z += 0.2;
  87572. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87573. // Add drag behavior to handle events when the gizmo is dragged
  87574. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87575. _this._dragBehavior.moveAttached = false;
  87576. _this._rootMesh.addBehavior(_this._dragBehavior);
  87577. _this._dragBehavior.onDragObservable.add(function (event) {
  87578. if (!_this.interactionsEnabled) {
  87579. return;
  87580. }
  87581. if (_this.attachedMesh) {
  87582. _this.attachedMesh.scaling.addInPlace(event.delta);
  87583. }
  87584. });
  87585. return _this;
  87586. }
  87587. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87588. this._dragBehavior.enabled = value;
  87589. };
  87590. /**
  87591. * Disposes of the gizmo
  87592. */
  87593. AxisScaleGizmo.prototype.dispose = function () {
  87594. this._dragBehavior.detach();
  87595. _super.prototype.dispose.call(this);
  87596. };
  87597. return AxisScaleGizmo;
  87598. }(BABYLON.Gizmo));
  87599. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87600. })(BABYLON || (BABYLON = {}));
  87601. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87602. var BABYLON;
  87603. (function (BABYLON) {
  87604. /**
  87605. * Single plane rotation gizmo
  87606. */
  87607. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87608. __extends(PlaneRotationGizmo, _super);
  87609. /**
  87610. * Creates a PlaneRotationGizmo
  87611. * @param gizmoLayer The utility layer the gizmo will be added to
  87612. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87613. * @param color The color of the gizmo
  87614. */
  87615. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87616. var _this = _super.call(this, gizmoLayer) || this;
  87617. // Create Material
  87618. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87619. coloredMaterial.disableLighting = true;
  87620. coloredMaterial.emissiveColor = color;
  87621. // Build mesh on root node
  87622. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87623. _this._rootMesh.addChild(rotationMesh);
  87624. // Position arrow pointing in its drag axis
  87625. rotationMesh.scaling.scaleInPlace(0.1);
  87626. rotationMesh.material = coloredMaterial;
  87627. rotationMesh.rotation.x = Math.PI / 2;
  87628. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87629. // Add drag behavior to handle events when the gizmo is dragged
  87630. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87631. _this._dragBehavior.moveAttached = false;
  87632. _this._rootMesh.addBehavior(_this._dragBehavior);
  87633. var lastDragPosition = null;
  87634. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87635. if (!_this.interactionsEnabled) {
  87636. return;
  87637. }
  87638. lastDragPosition = e.dragPlanePoint;
  87639. });
  87640. _this._dragBehavior.onDragObservable.add(function (event) {
  87641. if (!_this.interactionsEnabled) {
  87642. return;
  87643. }
  87644. if (_this.attachedMesh && lastDragPosition) {
  87645. if (!_this.attachedMesh.rotationQuaternion) {
  87646. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87647. }
  87648. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87649. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87650. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87651. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87652. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87653. var angle = Math.atan2(cross.length(), dot);
  87654. var up = planeNormal.clone();
  87655. // Flip up vector depending on which side the camera is on
  87656. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87657. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87658. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87659. up.scaleInPlace(-1);
  87660. }
  87661. }
  87662. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87663. if (halfCircleSide)
  87664. angle = -angle;
  87665. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87666. var quaternionCoefficient = Math.sin(angle / 2);
  87667. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87668. // Rotate selected mesh quaternion over fixed axis
  87669. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87670. lastDragPosition = event.dragPlanePoint;
  87671. }
  87672. });
  87673. return _this;
  87674. }
  87675. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87676. this._dragBehavior.enabled = value;
  87677. };
  87678. /**
  87679. * Disposes of the gizmo
  87680. */
  87681. PlaneRotationGizmo.prototype.dispose = function () {
  87682. this._dragBehavior.detach();
  87683. _super.prototype.dispose.call(this);
  87684. };
  87685. return PlaneRotationGizmo;
  87686. }(BABYLON.Gizmo));
  87687. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87688. })(BABYLON || (BABYLON = {}));
  87689. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87690. var BABYLON;
  87691. (function (BABYLON) {
  87692. /**
  87693. * Gizmo that enables dragging a mesh along 3 axis
  87694. */
  87695. var PositionGizmo = /** @class */ (function (_super) {
  87696. __extends(PositionGizmo, _super);
  87697. /**
  87698. * Creates a PositionGizmo
  87699. * @param gizmoLayer The utility layer the gizmo will be added to
  87700. */
  87701. function PositionGizmo(gizmoLayer) {
  87702. var _this = _super.call(this, gizmoLayer) || this;
  87703. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87704. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87705. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87706. return _this;
  87707. }
  87708. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87709. set: function (mesh) {
  87710. this._xDrag.attachedMesh = mesh;
  87711. this._yDrag.attachedMesh = mesh;
  87712. this._zDrag.attachedMesh = mesh;
  87713. },
  87714. enumerable: true,
  87715. configurable: true
  87716. });
  87717. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87718. this._xDrag.interactionsEnabled = value;
  87719. this._yDrag.interactionsEnabled = value;
  87720. this._zDrag.interactionsEnabled = value;
  87721. };
  87722. /**
  87723. * Disposes of the gizmo
  87724. */
  87725. PositionGizmo.prototype.dispose = function () {
  87726. this._xDrag.dispose();
  87727. this._yDrag.dispose();
  87728. this._zDrag.dispose();
  87729. };
  87730. return PositionGizmo;
  87731. }(BABYLON.Gizmo));
  87732. BABYLON.PositionGizmo = PositionGizmo;
  87733. })(BABYLON || (BABYLON = {}));
  87734. //# sourceMappingURL=babylon.positionGizmo.js.map
  87735. var BABYLON;
  87736. (function (BABYLON) {
  87737. /**
  87738. * Gizmo that enables rotating a mesh along 3 axis
  87739. */
  87740. var RotationGizmo = /** @class */ (function (_super) {
  87741. __extends(RotationGizmo, _super);
  87742. /**
  87743. * Creates a RotationGizmo
  87744. * @param gizmoLayer The utility layer the gizmo will be added to
  87745. */
  87746. function RotationGizmo(gizmoLayer) {
  87747. var _this = _super.call(this, gizmoLayer) || this;
  87748. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87749. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87750. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87751. return _this;
  87752. }
  87753. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87754. set: function (mesh) {
  87755. this._xDrag.attachedMesh = mesh;
  87756. this._yDrag.attachedMesh = mesh;
  87757. this._zDrag.attachedMesh = mesh;
  87758. },
  87759. enumerable: true,
  87760. configurable: true
  87761. });
  87762. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87763. this._xDrag.interactionsEnabled = value;
  87764. this._yDrag.interactionsEnabled = value;
  87765. this._zDrag.interactionsEnabled = value;
  87766. };
  87767. /**
  87768. * Disposes of the gizmo
  87769. */
  87770. RotationGizmo.prototype.dispose = function () {
  87771. this._xDrag.dispose();
  87772. this._yDrag.dispose();
  87773. this._zDrag.dispose();
  87774. };
  87775. return RotationGizmo;
  87776. }(BABYLON.Gizmo));
  87777. BABYLON.RotationGizmo = RotationGizmo;
  87778. })(BABYLON || (BABYLON = {}));
  87779. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87780. var BABYLON;
  87781. (function (BABYLON) {
  87782. /**
  87783. * Gizmo that enables scaling a mesh along 3 axis
  87784. */
  87785. var ScaleGizmo = /** @class */ (function (_super) {
  87786. __extends(ScaleGizmo, _super);
  87787. /**
  87788. * Creates a ScaleGizmo
  87789. * @param gizmoLayer The utility layer the gizmo will be added to
  87790. */
  87791. function ScaleGizmo(gizmoLayer) {
  87792. var _this = _super.call(this, gizmoLayer) || this;
  87793. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87794. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87795. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87796. return _this;
  87797. }
  87798. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87799. set: function (mesh) {
  87800. this._xDrag.attachedMesh = mesh;
  87801. this._yDrag.attachedMesh = mesh;
  87802. this._zDrag.attachedMesh = mesh;
  87803. },
  87804. enumerable: true,
  87805. configurable: true
  87806. });
  87807. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87808. this._xDrag.interactionsEnabled = value;
  87809. this._yDrag.interactionsEnabled = value;
  87810. this._zDrag.interactionsEnabled = value;
  87811. };
  87812. /**
  87813. * Disposes of the gizmo
  87814. */
  87815. ScaleGizmo.prototype.dispose = function () {
  87816. this._xDrag.dispose();
  87817. this._yDrag.dispose();
  87818. this._zDrag.dispose();
  87819. };
  87820. return ScaleGizmo;
  87821. }(BABYLON.Gizmo));
  87822. BABYLON.ScaleGizmo = ScaleGizmo;
  87823. })(BABYLON || (BABYLON = {}));
  87824. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87825. var BABYLON;
  87826. (function (BABYLON) {
  87827. /**
  87828. * Bounding box gizmo
  87829. */
  87830. var BoundingBoxGizmo = /** @class */ (function (_super) {
  87831. __extends(BoundingBoxGizmo, _super);
  87832. /**
  87833. * Creates an BoundingBoxGizmo
  87834. * @param gizmoLayer The utility layer the gizmo will be added to
  87835. * @param color The color of the gizmo
  87836. */
  87837. function BoundingBoxGizmo(gizmoLayer, color) {
  87838. var _this = _super.call(this, gizmoLayer) || this;
  87839. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  87840. _this._renderObserver = null;
  87841. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  87842. _this._updateScale = false;
  87843. // Create Material
  87844. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87845. coloredMaterial.disableLighting = true;
  87846. coloredMaterial.emissiveColor = color;
  87847. // Build bounding box out of lines
  87848. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87849. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  87850. var lines = [];
  87851. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  87852. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87853. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87854. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87855. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87856. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87857. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87858. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87859. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87860. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87861. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87862. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87863. lines.forEach(function (l) {
  87864. l.color = color;
  87865. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  87866. l.isPickable = false;
  87867. _this._lineBoundingBox.addChild(l);
  87868. });
  87869. _this._rootMesh.addChild(_this._lineBoundingBox);
  87870. // Create rotation spheres
  87871. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87872. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  87873. var _loop_1 = function (i_1) {
  87874. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  87875. sphere.rotationQuaternion = new BABYLON.Quaternion();
  87876. sphere.material = coloredMaterial;
  87877. // Drag behavior
  87878. _dragBehavior = new BABYLON.PointerDragBehavior({});
  87879. _dragBehavior.moveAttached = false;
  87880. sphere.addBehavior(_dragBehavior);
  87881. _dragBehavior.onDragObservable.add(function (event) {
  87882. if (_this.attachedMesh) {
  87883. var worldDragDirection = sphere.forward;
  87884. // Project the world right on to the drag plane
  87885. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  87886. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  87887. // project drag delta on to the resulting drag axis and rotate based on that
  87888. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  87889. // Rotate based on axis
  87890. if (i_1 >= 8) {
  87891. _this.attachedMesh.rotation.z -= projectDist;
  87892. }
  87893. else if (i_1 >= 4) {
  87894. _this.attachedMesh.rotation.y -= projectDist;
  87895. }
  87896. else {
  87897. _this.attachedMesh.rotation.x -= projectDist;
  87898. }
  87899. }
  87900. });
  87901. // Selection/deselection
  87902. _dragBehavior.onDragStartObservable.add(function () {
  87903. _this._selectNode(sphere);
  87904. });
  87905. _dragBehavior.onDragEndObservable.add(function () {
  87906. _this._selectNode(null);
  87907. });
  87908. this_1._rotateSpheresParent.addChild(sphere);
  87909. };
  87910. var this_1 = this, _dragBehavior;
  87911. for (var i_1 = 0; i_1 < 12; i_1++) {
  87912. _loop_1(i_1);
  87913. }
  87914. _this._rootMesh.addChild(_this._rotateSpheresParent);
  87915. // Create scale cubes
  87916. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87917. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  87918. for (var i = 0; i < 2; i++) {
  87919. for (var j = 0; j < 2; j++) {
  87920. var _loop_2 = function () {
  87921. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  87922. box.material = coloredMaterial;
  87923. // Dragging logic
  87924. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  87925. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87926. _dragBehavior.moveAttached = false;
  87927. box.addBehavior(_dragBehavior);
  87928. _dragBehavior.onDragObservable.add(function (event) {
  87929. if (_this.attachedMesh) {
  87930. // Current boudning box dimensions
  87931. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  87932. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  87933. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  87934. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  87935. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  87936. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  87937. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  87938. // Update scale and position
  87939. _this.attachedMesh.scaling.addInPlace(deltaScale);
  87940. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  87941. }
  87942. });
  87943. // Selection/deselection
  87944. _dragBehavior.onDragStartObservable.add(function () {
  87945. _this._selectNode(box);
  87946. });
  87947. _dragBehavior.onDragEndObservable.add(function () {
  87948. _this._selectNode(null);
  87949. });
  87950. this_2._scaleBoxesParent.addChild(box);
  87951. };
  87952. var this_2 = this, _dragBehavior;
  87953. for (var k = 0; k < 2; k++) {
  87954. _loop_2();
  87955. }
  87956. }
  87957. }
  87958. _this._rootMesh.addChild(_this._scaleBoxesParent);
  87959. // Update bounding box positions
  87960. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  87961. _this._updateBoundingBox();
  87962. });
  87963. _this._updateBoundingBox();
  87964. return _this;
  87965. }
  87966. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  87967. this._rotateSpheresParent.getChildMeshes()
  87968. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  87969. m.isVisible = (!selectedMesh || m == selectedMesh);
  87970. });
  87971. };
  87972. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  87973. if (this.attachedMesh) {
  87974. // Update bounding dimensions/positions
  87975. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  87976. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  87977. this._boundingDimensions.copyFrom(boundBoxDimensions);
  87978. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  87979. if (!this.attachedMesh.rotationQuaternion) {
  87980. this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87981. }
  87982. this._lineBoundingBox.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  87983. this._rotateSpheresParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  87984. this._scaleBoxesParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  87985. }
  87986. // Update rotation sphere locations
  87987. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  87988. for (var i = 0; i < 3; i++) {
  87989. for (var j = 0; j < 2; j++) {
  87990. for (var k = 0; k < 2; k++) {
  87991. var index = ((i * 4) + (j * 2)) + k;
  87992. if (i == 0) {
  87993. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  87994. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  87995. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  87996. }
  87997. if (i == 1) {
  87998. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  87999. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88000. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88001. }
  88002. if (i == 2) {
  88003. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88004. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88005. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88006. }
  88007. }
  88008. }
  88009. }
  88010. // Update scale box locations
  88011. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88012. for (var i = 0; i < 2; i++) {
  88013. for (var j = 0; j < 2; j++) {
  88014. for (var k = 0; k < 2; k++) {
  88015. var index = ((i * 4) + (j * 2)) + k;
  88016. if (scaleBoxes[index]) {
  88017. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88018. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88019. }
  88020. }
  88021. }
  88022. }
  88023. };
  88024. /**
  88025. * Disposes of the gizmo
  88026. */
  88027. BoundingBoxGizmo.prototype.dispose = function () {
  88028. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88029. this._lineBoundingBox.dispose();
  88030. this._rotateSpheresParent.dispose();
  88031. this._scaleBoxesParent.dispose();
  88032. _super.prototype.dispose.call(this);
  88033. };
  88034. return BoundingBoxGizmo;
  88035. }(BABYLON.Gizmo));
  88036. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88037. })(BABYLON || (BABYLON = {}));
  88038. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88039. var BABYLON;
  88040. (function (BABYLON) {
  88041. /**
  88042. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88043. */
  88044. var GizmoManager = /** @class */ (function () {
  88045. /**
  88046. * Instatiates a gizmo manager
  88047. * @param scene the scene to overlay the gizmos on top of
  88048. * @param options If only a single gizmo should exist at one time
  88049. */
  88050. function GizmoManager(scene, options) {
  88051. var _this = this;
  88052. this.scene = scene;
  88053. // Set of gizmos that are currently in the scene for each mesh
  88054. this._gizmoSet = {};
  88055. this._pointerObserver = null;
  88056. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88057. // Options parsing
  88058. if (!options) {
  88059. options = {};
  88060. }
  88061. if (options.singleGizmo === undefined) {
  88062. options.singleGizmo = true;
  88063. }
  88064. // Instatiate/dispose gizmos based on pointer actions
  88065. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88066. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88067. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88068. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88069. if (options.singleGizmo) {
  88070. _this._clearGizmos();
  88071. }
  88072. // Enable gizmo when mesh is selected
  88073. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88074. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88075. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88076. }
  88077. else {
  88078. if (!options.singleGizmo) {
  88079. // Disable gizmo when clicked again
  88080. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88081. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88082. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88083. }
  88084. }
  88085. }
  88086. else {
  88087. if (options.singleGizmo) {
  88088. // Disable gizmo when clicked away
  88089. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88090. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88091. if (gizmoPick && !gizmoPick.hit) {
  88092. _this._clearGizmos();
  88093. }
  88094. }
  88095. }
  88096. }
  88097. }
  88098. });
  88099. }
  88100. /**
  88101. * Disposes of the gizmo manager
  88102. */
  88103. GizmoManager.prototype.dispose = function () {
  88104. this.scene.onPointerObservable.remove(this._pointerObserver);
  88105. this._clearGizmos();
  88106. this._gizmoLayer.dispose();
  88107. };
  88108. GizmoManager.prototype._clearGizmos = function () {
  88109. for (var key in this._gizmoSet) {
  88110. if (this._gizmoSet.hasOwnProperty(key)) {
  88111. this._gizmoSet[key].positionGizmo.dispose();
  88112. this._gizmoSet[key].rotationGizmo.dispose();
  88113. delete this._gizmoSet[key];
  88114. }
  88115. }
  88116. };
  88117. return GizmoManager;
  88118. }());
  88119. BABYLON.GizmoManager = GizmoManager;
  88120. })(BABYLON || (BABYLON = {}));
  88121. //# sourceMappingURL=babylon.gizmoManager.js.map
  88122. var BABYLON;
  88123. (function (BABYLON) {
  88124. /**
  88125. * Defines a target to use with MorphTargetManager
  88126. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88127. */
  88128. var MorphTarget = /** @class */ (function () {
  88129. /**
  88130. * Creates a new MorphTarget
  88131. * @param name defines the name of the target
  88132. * @param influence defines the influence to use
  88133. */
  88134. function MorphTarget(
  88135. /** defines the name of the target */
  88136. name, influence, scene) {
  88137. if (influence === void 0) { influence = 0; }
  88138. if (scene === void 0) { scene = null; }
  88139. this.name = name;
  88140. /**
  88141. * Gets or sets the list of animations
  88142. */
  88143. this.animations = new Array();
  88144. this._positions = null;
  88145. this._normals = null;
  88146. this._tangents = null;
  88147. /**
  88148. * Observable raised when the influence changes
  88149. */
  88150. this.onInfluenceChanged = new BABYLON.Observable();
  88151. this._animationPropertiesOverride = null;
  88152. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88153. this.influence = influence;
  88154. }
  88155. Object.defineProperty(MorphTarget.prototype, "influence", {
  88156. /**
  88157. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  88158. */
  88159. get: function () {
  88160. return this._influence;
  88161. },
  88162. set: function (influence) {
  88163. if (this._influence === influence) {
  88164. return;
  88165. }
  88166. var previous = this._influence;
  88167. this._influence = influence;
  88168. if (this.onInfluenceChanged.hasObservers) {
  88169. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  88170. }
  88171. },
  88172. enumerable: true,
  88173. configurable: true
  88174. });
  88175. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  88176. /**
  88177. * Gets or sets the animation properties override
  88178. */
  88179. get: function () {
  88180. if (!this._animationPropertiesOverride && this._scene) {
  88181. return this._scene.animationPropertiesOverride;
  88182. }
  88183. return this._animationPropertiesOverride;
  88184. },
  88185. set: function (value) {
  88186. this._animationPropertiesOverride = value;
  88187. },
  88188. enumerable: true,
  88189. configurable: true
  88190. });
  88191. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  88192. /**
  88193. * Gets a boolean defining if the target contains position data
  88194. */
  88195. get: function () {
  88196. return !!this._positions;
  88197. },
  88198. enumerable: true,
  88199. configurable: true
  88200. });
  88201. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88202. /**
  88203. * Gets a boolean defining if the target contains normal data
  88204. */
  88205. get: function () {
  88206. return !!this._normals;
  88207. },
  88208. enumerable: true,
  88209. configurable: true
  88210. });
  88211. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88212. /**
  88213. * Gets a boolean defining if the target contains tangent data
  88214. */
  88215. get: function () {
  88216. return !!this._tangents;
  88217. },
  88218. enumerable: true,
  88219. configurable: true
  88220. });
  88221. /**
  88222. * Affects position data to this target
  88223. * @param data defines the position data to use
  88224. */
  88225. MorphTarget.prototype.setPositions = function (data) {
  88226. this._positions = data;
  88227. };
  88228. /**
  88229. * Gets the position data stored in this target
  88230. * @returns a FloatArray containing the position data (or null if not present)
  88231. */
  88232. MorphTarget.prototype.getPositions = function () {
  88233. return this._positions;
  88234. };
  88235. /**
  88236. * Affects normal data to this target
  88237. * @param data defines the normal data to use
  88238. */
  88239. MorphTarget.prototype.setNormals = function (data) {
  88240. this._normals = data;
  88241. };
  88242. /**
  88243. * Gets the normal data stored in this target
  88244. * @returns a FloatArray containing the normal data (or null if not present)
  88245. */
  88246. MorphTarget.prototype.getNormals = function () {
  88247. return this._normals;
  88248. };
  88249. /**
  88250. * Affects tangent data to this target
  88251. * @param data defines the tangent data to use
  88252. */
  88253. MorphTarget.prototype.setTangents = function (data) {
  88254. this._tangents = data;
  88255. };
  88256. /**
  88257. * Gets the tangent data stored in this target
  88258. * @returns a FloatArray containing the tangent data (or null if not present)
  88259. */
  88260. MorphTarget.prototype.getTangents = function () {
  88261. return this._tangents;
  88262. };
  88263. /**
  88264. * Serializes the current target into a Serialization object
  88265. * @returns the serialized object
  88266. */
  88267. MorphTarget.prototype.serialize = function () {
  88268. var serializationObject = {};
  88269. serializationObject.name = this.name;
  88270. serializationObject.influence = this.influence;
  88271. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88272. if (this.hasNormals) {
  88273. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88274. }
  88275. if (this.hasTangents) {
  88276. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88277. }
  88278. // Animations
  88279. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88280. return serializationObject;
  88281. };
  88282. // Statics
  88283. /**
  88284. * Creates a new target from serialized data
  88285. * @param serializationObject defines the serialized data to use
  88286. * @returns a new MorphTarget
  88287. */
  88288. MorphTarget.Parse = function (serializationObject) {
  88289. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88290. result.setPositions(serializationObject.positions);
  88291. if (serializationObject.normals) {
  88292. result.setNormals(serializationObject.normals);
  88293. }
  88294. if (serializationObject.tangents) {
  88295. result.setTangents(serializationObject.tangents);
  88296. }
  88297. // Animations
  88298. if (serializationObject.animations) {
  88299. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88300. var parsedAnimation = serializationObject.animations[animationIndex];
  88301. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88302. }
  88303. }
  88304. return result;
  88305. };
  88306. /**
  88307. * Creates a MorphTarget from mesh data
  88308. * @param mesh defines the source mesh
  88309. * @param name defines the name to use for the new target
  88310. * @param influence defines the influence to attach to the target
  88311. * @returns a new MorphTarget
  88312. */
  88313. MorphTarget.FromMesh = function (mesh, name, influence) {
  88314. if (!name) {
  88315. name = mesh.name;
  88316. }
  88317. var result = new MorphTarget(name, influence, mesh.getScene());
  88318. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88320. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88321. }
  88322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88323. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88324. }
  88325. return result;
  88326. };
  88327. return MorphTarget;
  88328. }());
  88329. BABYLON.MorphTarget = MorphTarget;
  88330. })(BABYLON || (BABYLON = {}));
  88331. //# sourceMappingURL=babylon.morphTarget.js.map
  88332. var BABYLON;
  88333. (function (BABYLON) {
  88334. /**
  88335. * This class is used to deform meshes using morphing between different targets
  88336. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88337. */
  88338. var MorphTargetManager = /** @class */ (function () {
  88339. /**
  88340. * Creates a new MorphTargetManager
  88341. * @param scene defines the current scene
  88342. */
  88343. function MorphTargetManager(scene) {
  88344. if (scene === void 0) { scene = null; }
  88345. this._targets = new Array();
  88346. this._targetObservable = new Array();
  88347. this._activeTargets = new BABYLON.SmartArray(16);
  88348. this._supportsNormals = false;
  88349. this._supportsTangents = false;
  88350. this._vertexCount = 0;
  88351. this._uniqueId = 0;
  88352. this._tempInfluences = new Array();
  88353. if (!scene) {
  88354. scene = BABYLON.Engine.LastCreatedScene;
  88355. }
  88356. this._scene = scene;
  88357. if (this._scene) {
  88358. this._scene.morphTargetManagers.push(this);
  88359. this._uniqueId = this._scene.getUniqueId();
  88360. }
  88361. }
  88362. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88363. /**
  88364. * Gets the unique ID of this manager
  88365. */
  88366. get: function () {
  88367. return this._uniqueId;
  88368. },
  88369. enumerable: true,
  88370. configurable: true
  88371. });
  88372. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88373. /**
  88374. * Gets the number of vertices handled by this manager
  88375. */
  88376. get: function () {
  88377. return this._vertexCount;
  88378. },
  88379. enumerable: true,
  88380. configurable: true
  88381. });
  88382. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88383. /**
  88384. * Gets a boolean indicating if this manager supports morphing of normals
  88385. */
  88386. get: function () {
  88387. return this._supportsNormals;
  88388. },
  88389. enumerable: true,
  88390. configurable: true
  88391. });
  88392. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88393. /**
  88394. * Gets a boolean indicating if this manager supports morphing of tangents
  88395. */
  88396. get: function () {
  88397. return this._supportsTangents;
  88398. },
  88399. enumerable: true,
  88400. configurable: true
  88401. });
  88402. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88403. /**
  88404. * Gets the number of targets stored in this manager
  88405. */
  88406. get: function () {
  88407. return this._targets.length;
  88408. },
  88409. enumerable: true,
  88410. configurable: true
  88411. });
  88412. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88413. /**
  88414. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88415. */
  88416. get: function () {
  88417. return this._activeTargets.length;
  88418. },
  88419. enumerable: true,
  88420. configurable: true
  88421. });
  88422. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88423. /**
  88424. * Gets the list of influences (one per target)
  88425. */
  88426. get: function () {
  88427. return this._influences;
  88428. },
  88429. enumerable: true,
  88430. configurable: true
  88431. });
  88432. /**
  88433. * Gets the active target at specified index. An active target is a target with an influence > 0
  88434. * @param index defines the index to check
  88435. * @returns the requested target
  88436. */
  88437. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88438. return this._activeTargets.data[index];
  88439. };
  88440. /**
  88441. * Gets the target at specified index
  88442. * @param index defines the index to check
  88443. * @returns the requested target
  88444. */
  88445. MorphTargetManager.prototype.getTarget = function (index) {
  88446. return this._targets[index];
  88447. };
  88448. /**
  88449. * Add a new target to this manager
  88450. * @param target defines the target to add
  88451. */
  88452. MorphTargetManager.prototype.addTarget = function (target) {
  88453. var _this = this;
  88454. this._targets.push(target);
  88455. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88456. _this._syncActiveTargets(needUpdate);
  88457. }));
  88458. this._syncActiveTargets(true);
  88459. };
  88460. /**
  88461. * Removes a target from the manager
  88462. * @param target defines the target to remove
  88463. */
  88464. MorphTargetManager.prototype.removeTarget = function (target) {
  88465. var index = this._targets.indexOf(target);
  88466. if (index >= 0) {
  88467. this._targets.splice(index, 1);
  88468. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88469. this._syncActiveTargets(true);
  88470. }
  88471. };
  88472. /**
  88473. * Serializes the current manager into a Serialization object
  88474. * @returns the serialized object
  88475. */
  88476. MorphTargetManager.prototype.serialize = function () {
  88477. var serializationObject = {};
  88478. serializationObject.id = this.uniqueId;
  88479. serializationObject.targets = [];
  88480. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88481. var target = _a[_i];
  88482. serializationObject.targets.push(target.serialize());
  88483. }
  88484. return serializationObject;
  88485. };
  88486. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88487. var influenceCount = 0;
  88488. this._activeTargets.reset();
  88489. this._supportsNormals = true;
  88490. this._supportsTangents = true;
  88491. this._vertexCount = 0;
  88492. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88493. var target = _a[_i];
  88494. this._activeTargets.push(target);
  88495. this._tempInfluences[influenceCount++] = target.influence;
  88496. var positions = target.getPositions();
  88497. if (positions) {
  88498. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88499. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88500. var vertexCount = positions.length / 3;
  88501. if (this._vertexCount === 0) {
  88502. this._vertexCount = vertexCount;
  88503. }
  88504. else if (this._vertexCount !== vertexCount) {
  88505. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88506. return;
  88507. }
  88508. }
  88509. }
  88510. if (!this._influences || this._influences.length !== influenceCount) {
  88511. this._influences = new Float32Array(influenceCount);
  88512. }
  88513. for (var index = 0; index < influenceCount; index++) {
  88514. this._influences[index] = this._tempInfluences[index];
  88515. }
  88516. if (needUpdate) {
  88517. this.synchronize();
  88518. }
  88519. };
  88520. /**
  88521. * Syncrhonize the targets with all the meshes using this morph target manager
  88522. */
  88523. MorphTargetManager.prototype.synchronize = function () {
  88524. if (!this._scene) {
  88525. return;
  88526. }
  88527. // Flag meshes as dirty to resync with the active targets
  88528. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88529. var mesh = _a[_i];
  88530. if (mesh.morphTargetManager === this) {
  88531. mesh._syncGeometryWithMorphTargetManager();
  88532. }
  88533. }
  88534. };
  88535. // Statics
  88536. /**
  88537. * Creates a new MorphTargetManager from serialized data
  88538. * @param serializationObject defines the serialized data
  88539. * @param scene defines the hosting scene
  88540. * @returns the new MorphTargetManager
  88541. */
  88542. MorphTargetManager.Parse = function (serializationObject, scene) {
  88543. var result = new MorphTargetManager(scene);
  88544. result._uniqueId = serializationObject.id;
  88545. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88546. var targetData = _a[_i];
  88547. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88548. }
  88549. return result;
  88550. };
  88551. return MorphTargetManager;
  88552. }());
  88553. BABYLON.MorphTargetManager = MorphTargetManager;
  88554. })(BABYLON || (BABYLON = {}));
  88555. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88556. var BABYLON;
  88557. (function (BABYLON) {
  88558. var Octree = /** @class */ (function () {
  88559. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88560. if (maxDepth === void 0) { maxDepth = 2; }
  88561. this.maxDepth = maxDepth;
  88562. this.dynamicContent = new Array();
  88563. this._maxBlockCapacity = maxBlockCapacity || 64;
  88564. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88565. this._creationFunc = creationFunc;
  88566. }
  88567. // Methods
  88568. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88569. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88570. };
  88571. Octree.prototype.addMesh = function (entry) {
  88572. for (var index = 0; index < this.blocks.length; index++) {
  88573. var block = this.blocks[index];
  88574. block.addEntry(entry);
  88575. }
  88576. };
  88577. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88578. this._selectionContent.reset();
  88579. for (var index = 0; index < this.blocks.length; index++) {
  88580. var block = this.blocks[index];
  88581. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88582. }
  88583. if (allowDuplicate) {
  88584. this._selectionContent.concat(this.dynamicContent);
  88585. }
  88586. else {
  88587. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88588. }
  88589. return this._selectionContent;
  88590. };
  88591. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88592. this._selectionContent.reset();
  88593. for (var index = 0; index < this.blocks.length; index++) {
  88594. var block = this.blocks[index];
  88595. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88596. }
  88597. if (allowDuplicate) {
  88598. this._selectionContent.concat(this.dynamicContent);
  88599. }
  88600. else {
  88601. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88602. }
  88603. return this._selectionContent;
  88604. };
  88605. Octree.prototype.intersectsRay = function (ray) {
  88606. this._selectionContent.reset();
  88607. for (var index = 0; index < this.blocks.length; index++) {
  88608. var block = this.blocks[index];
  88609. block.intersectsRay(ray, this._selectionContent);
  88610. }
  88611. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88612. return this._selectionContent;
  88613. };
  88614. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88615. target.blocks = new Array();
  88616. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88617. // Segmenting space
  88618. for (var x = 0; x < 2; x++) {
  88619. for (var y = 0; y < 2; y++) {
  88620. for (var z = 0; z < 2; z++) {
  88621. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88622. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88623. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88624. block.addEntries(entries);
  88625. target.blocks.push(block);
  88626. }
  88627. }
  88628. }
  88629. };
  88630. Octree.CreationFuncForMeshes = function (entry, block) {
  88631. var boundingInfo = entry.getBoundingInfo();
  88632. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88633. block.entries.push(entry);
  88634. }
  88635. };
  88636. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88637. var boundingInfo = entry.getBoundingInfo();
  88638. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88639. block.entries.push(entry);
  88640. }
  88641. };
  88642. return Octree;
  88643. }());
  88644. BABYLON.Octree = Octree;
  88645. })(BABYLON || (BABYLON = {}));
  88646. //# sourceMappingURL=babylon.octree.js.map
  88647. var BABYLON;
  88648. (function (BABYLON) {
  88649. var OctreeBlock = /** @class */ (function () {
  88650. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88651. this.entries = new Array();
  88652. this._boundingVectors = new Array();
  88653. this._capacity = capacity;
  88654. this._depth = depth;
  88655. this._maxDepth = maxDepth;
  88656. this._creationFunc = creationFunc;
  88657. this._minPoint = minPoint;
  88658. this._maxPoint = maxPoint;
  88659. this._boundingVectors.push(minPoint.clone());
  88660. this._boundingVectors.push(maxPoint.clone());
  88661. this._boundingVectors.push(minPoint.clone());
  88662. this._boundingVectors[2].x = maxPoint.x;
  88663. this._boundingVectors.push(minPoint.clone());
  88664. this._boundingVectors[3].y = maxPoint.y;
  88665. this._boundingVectors.push(minPoint.clone());
  88666. this._boundingVectors[4].z = maxPoint.z;
  88667. this._boundingVectors.push(maxPoint.clone());
  88668. this._boundingVectors[5].z = minPoint.z;
  88669. this._boundingVectors.push(maxPoint.clone());
  88670. this._boundingVectors[6].x = minPoint.x;
  88671. this._boundingVectors.push(maxPoint.clone());
  88672. this._boundingVectors[7].y = minPoint.y;
  88673. }
  88674. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88675. // Property
  88676. get: function () {
  88677. return this._capacity;
  88678. },
  88679. enumerable: true,
  88680. configurable: true
  88681. });
  88682. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88683. get: function () {
  88684. return this._minPoint;
  88685. },
  88686. enumerable: true,
  88687. configurable: true
  88688. });
  88689. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88690. get: function () {
  88691. return this._maxPoint;
  88692. },
  88693. enumerable: true,
  88694. configurable: true
  88695. });
  88696. // Methods
  88697. OctreeBlock.prototype.addEntry = function (entry) {
  88698. if (this.blocks) {
  88699. for (var index = 0; index < this.blocks.length; index++) {
  88700. var block = this.blocks[index];
  88701. block.addEntry(entry);
  88702. }
  88703. return;
  88704. }
  88705. this._creationFunc(entry, this);
  88706. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88707. this.createInnerBlocks();
  88708. }
  88709. };
  88710. OctreeBlock.prototype.addEntries = function (entries) {
  88711. for (var index = 0; index < entries.length; index++) {
  88712. var mesh = entries[index];
  88713. this.addEntry(mesh);
  88714. }
  88715. };
  88716. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88717. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88718. if (this.blocks) {
  88719. for (var index = 0; index < this.blocks.length; index++) {
  88720. var block = this.blocks[index];
  88721. block.select(frustumPlanes, selection, allowDuplicate);
  88722. }
  88723. return;
  88724. }
  88725. if (allowDuplicate) {
  88726. selection.concat(this.entries);
  88727. }
  88728. else {
  88729. selection.concatWithNoDuplicate(this.entries);
  88730. }
  88731. }
  88732. };
  88733. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88734. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88735. if (this.blocks) {
  88736. for (var index = 0; index < this.blocks.length; index++) {
  88737. var block = this.blocks[index];
  88738. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88739. }
  88740. return;
  88741. }
  88742. if (allowDuplicate) {
  88743. selection.concat(this.entries);
  88744. }
  88745. else {
  88746. selection.concatWithNoDuplicate(this.entries);
  88747. }
  88748. }
  88749. };
  88750. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88751. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88752. if (this.blocks) {
  88753. for (var index = 0; index < this.blocks.length; index++) {
  88754. var block = this.blocks[index];
  88755. block.intersectsRay(ray, selection);
  88756. }
  88757. return;
  88758. }
  88759. selection.concatWithNoDuplicate(this.entries);
  88760. }
  88761. };
  88762. OctreeBlock.prototype.createInnerBlocks = function () {
  88763. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88764. };
  88765. return OctreeBlock;
  88766. }());
  88767. BABYLON.OctreeBlock = OctreeBlock;
  88768. })(BABYLON || (BABYLON = {}));
  88769. //# sourceMappingURL=babylon.octreeBlock.js.map
  88770. var BABYLON;
  88771. (function (BABYLON) {
  88772. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88773. __extends(VRDistortionCorrectionPostProcess, _super);
  88774. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88775. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88776. 'LensCenter',
  88777. 'Scale',
  88778. 'ScaleIn',
  88779. 'HmdWarpParam'
  88780. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88781. _this._isRightEye = isRightEye;
  88782. _this._distortionFactors = vrMetrics.distortionK;
  88783. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88784. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88785. _this.adaptScaleToCurrentViewport = true;
  88786. _this.onSizeChangedObservable.add(function () {
  88787. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88788. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88789. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88790. });
  88791. _this.onApplyObservable.add(function (effect) {
  88792. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88793. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88794. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88795. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88796. });
  88797. return _this;
  88798. }
  88799. return VRDistortionCorrectionPostProcess;
  88800. }(BABYLON.PostProcess));
  88801. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88802. })(BABYLON || (BABYLON = {}));
  88803. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88804. var BABYLON;
  88805. (function (BABYLON) {
  88806. /**
  88807. * Postprocess used to generate anaglyphic rendering
  88808. */
  88809. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88810. __extends(AnaglyphPostProcess, _super);
  88811. /**
  88812. * Creates a new AnaglyphPostProcess
  88813. * @param name defines postprocess name
  88814. * @param options defines creation options or target ratio scale
  88815. * @param rigCameras defines cameras using this postprocess
  88816. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88817. * @param engine defines hosting engine
  88818. * @param reusable defines if the postprocess will be reused multiple times per frame
  88819. */
  88820. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88821. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88822. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88823. _this.onApplyObservable.add(function (effect) {
  88824. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88825. });
  88826. return _this;
  88827. }
  88828. return AnaglyphPostProcess;
  88829. }(BABYLON.PostProcess));
  88830. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88831. })(BABYLON || (BABYLON = {}));
  88832. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88833. var BABYLON;
  88834. (function (BABYLON) {
  88835. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88836. __extends(StereoscopicInterlacePostProcess, _super);
  88837. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88838. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88839. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88840. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88841. _this.onSizeChangedObservable.add(function () {
  88842. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88843. });
  88844. _this.onApplyObservable.add(function (effect) {
  88845. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88846. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88847. });
  88848. return _this;
  88849. }
  88850. return StereoscopicInterlacePostProcess;
  88851. }(BABYLON.PostProcess));
  88852. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88853. })(BABYLON || (BABYLON = {}));
  88854. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88855. var BABYLON;
  88856. (function (BABYLON) {
  88857. /**
  88858. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88859. * Screen rotation is taken into account.
  88860. */
  88861. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88862. function FreeCameraDeviceOrientationInput() {
  88863. var _this = this;
  88864. this._screenOrientationAngle = 0;
  88865. this._screenQuaternion = new BABYLON.Quaternion();
  88866. this._alpha = 0;
  88867. this._beta = 0;
  88868. this._gamma = 0;
  88869. this._orientationChanged = function () {
  88870. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88871. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88872. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88873. };
  88874. this._deviceOrientation = function (evt) {
  88875. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88876. _this._beta = evt.beta !== null ? evt.beta : 0;
  88877. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88878. };
  88879. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88880. this._orientationChanged();
  88881. }
  88882. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88883. get: function () {
  88884. return this._camera;
  88885. },
  88886. set: function (camera) {
  88887. this._camera = camera;
  88888. if (this._camera != null && !this._camera.rotationQuaternion) {
  88889. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88890. }
  88891. },
  88892. enumerable: true,
  88893. configurable: true
  88894. });
  88895. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88896. window.addEventListener("orientationchange", this._orientationChanged);
  88897. window.addEventListener("deviceorientation", this._deviceOrientation);
  88898. //In certain cases, the attach control is called AFTER orientation was changed,
  88899. //So this is needed.
  88900. this._orientationChanged();
  88901. };
  88902. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88903. window.removeEventListener("orientationchange", this._orientationChanged);
  88904. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88905. };
  88906. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88907. //if no device orientation provided, don't update the rotation.
  88908. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88909. if (!this._alpha)
  88910. return;
  88911. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88912. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88913. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88914. //Mirror on XY Plane
  88915. this._camera.rotationQuaternion.z *= -1;
  88916. this._camera.rotationQuaternion.w *= -1;
  88917. };
  88918. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88919. return "FreeCameraDeviceOrientationInput";
  88920. };
  88921. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88922. return "deviceOrientation";
  88923. };
  88924. return FreeCameraDeviceOrientationInput;
  88925. }());
  88926. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88927. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88928. })(BABYLON || (BABYLON = {}));
  88929. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88930. var BABYLON;
  88931. (function (BABYLON) {
  88932. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88933. function ArcRotateCameraVRDeviceOrientationInput() {
  88934. this.alphaCorrection = 1;
  88935. this.betaCorrection = 1;
  88936. this.gammaCorrection = 1;
  88937. this._alpha = 0;
  88938. this._gamma = 0;
  88939. this._dirty = false;
  88940. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88941. }
  88942. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88943. this.camera.attachControl(element, noPreventDefault);
  88944. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88945. };
  88946. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88947. if (evt.alpha !== null) {
  88948. this._alpha = +evt.alpha | 0;
  88949. }
  88950. if (evt.gamma !== null) {
  88951. this._gamma = +evt.gamma | 0;
  88952. }
  88953. this._dirty = true;
  88954. };
  88955. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88956. if (this._dirty) {
  88957. this._dirty = false;
  88958. if (this._gamma < 0) {
  88959. this._gamma = 180 + this._gamma;
  88960. }
  88961. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88962. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88963. }
  88964. };
  88965. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88966. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88967. };
  88968. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88969. return "ArcRotateCameraVRDeviceOrientationInput";
  88970. };
  88971. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88972. return "VRDeviceOrientation";
  88973. };
  88974. return ArcRotateCameraVRDeviceOrientationInput;
  88975. }());
  88976. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88977. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88978. })(BABYLON || (BABYLON = {}));
  88979. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88980. var BABYLON;
  88981. (function (BABYLON) {
  88982. var VRCameraMetrics = /** @class */ (function () {
  88983. function VRCameraMetrics() {
  88984. this.compensateDistortion = true;
  88985. }
  88986. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88987. get: function () {
  88988. return this.hResolution / (2 * this.vResolution);
  88989. },
  88990. enumerable: true,
  88991. configurable: true
  88992. });
  88993. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88994. get: function () {
  88995. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88996. },
  88997. enumerable: true,
  88998. configurable: true
  88999. });
  89000. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89001. get: function () {
  89002. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89003. var h = (4 * meters) / this.hScreenSize;
  89004. return BABYLON.Matrix.Translation(h, 0, 0);
  89005. },
  89006. enumerable: true,
  89007. configurable: true
  89008. });
  89009. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89010. get: function () {
  89011. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89012. var h = (4 * meters) / this.hScreenSize;
  89013. return BABYLON.Matrix.Translation(-h, 0, 0);
  89014. },
  89015. enumerable: true,
  89016. configurable: true
  89017. });
  89018. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89019. get: function () {
  89020. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89021. },
  89022. enumerable: true,
  89023. configurable: true
  89024. });
  89025. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89026. get: function () {
  89027. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89028. },
  89029. enumerable: true,
  89030. configurable: true
  89031. });
  89032. VRCameraMetrics.GetDefault = function () {
  89033. var result = new VRCameraMetrics();
  89034. result.hResolution = 1280;
  89035. result.vResolution = 800;
  89036. result.hScreenSize = 0.149759993;
  89037. result.vScreenSize = 0.0935999975;
  89038. result.vScreenCenter = 0.0467999987;
  89039. result.eyeToScreenDistance = 0.0410000011;
  89040. result.lensSeparationDistance = 0.0635000020;
  89041. result.interpupillaryDistance = 0.0640000030;
  89042. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89043. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89044. result.postProcessScaleFactor = 1.714605507808412;
  89045. result.lensCenterOffset = 0.151976421;
  89046. return result;
  89047. };
  89048. return VRCameraMetrics;
  89049. }());
  89050. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89051. })(BABYLON || (BABYLON = {}));
  89052. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89053. var BABYLON;
  89054. (function (BABYLON) {
  89055. /**
  89056. * This represents a WebVR camera.
  89057. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89058. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89059. */
  89060. var WebVRFreeCamera = /** @class */ (function (_super) {
  89061. __extends(WebVRFreeCamera, _super);
  89062. /**
  89063. * Instantiates a WebVRFreeCamera.
  89064. * @param name The name of the WebVRFreeCamera
  89065. * @param position The starting anchor position for the camera
  89066. * @param scene The scene the camera belongs to
  89067. * @param webVROptions a set of customizable options for the webVRCamera
  89068. */
  89069. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89070. if (webVROptions === void 0) { webVROptions = {}; }
  89071. var _this = _super.call(this, name, position, scene) || this;
  89072. _this.webVROptions = webVROptions;
  89073. /**
  89074. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89075. */
  89076. _this._vrDevice = null;
  89077. /**
  89078. * The rawPose of the vrDevice.
  89079. */
  89080. _this.rawPose = null;
  89081. _this._specsVersion = "1.1";
  89082. _this._attached = false;
  89083. _this._descendants = [];
  89084. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89085. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89086. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89087. _this._standingMatrix = null;
  89088. /**
  89089. * Represents device position in babylon space.
  89090. */
  89091. _this.devicePosition = BABYLON.Vector3.Zero();
  89092. /**
  89093. * Represents device rotation in babylon space.
  89094. */
  89095. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89096. /**
  89097. * The scale of the device to be used when translating from device space to babylon space.
  89098. */
  89099. _this.deviceScaleFactor = 1;
  89100. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89101. _this._worldToDevice = BABYLON.Matrix.Identity();
  89102. /**
  89103. * References to the webVR controllers for the vrDevice.
  89104. */
  89105. _this.controllers = [];
  89106. /**
  89107. * Emits an event when a controller is attached.
  89108. */
  89109. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89110. /**
  89111. * Emits an event when a controller's mesh has been loaded;
  89112. */
  89113. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89114. /**
  89115. * If the rig cameras be used as parent instead of this camera.
  89116. */
  89117. _this.rigParenting = true;
  89118. _this._defaultHeight = undefined;
  89119. _this._workingVector = BABYLON.Vector3.Zero();
  89120. _this._oneVector = BABYLON.Vector3.One();
  89121. _this._workingMatrix = BABYLON.Matrix.Identity();
  89122. _this._cache.position = BABYLON.Vector3.Zero();
  89123. if (webVROptions.defaultHeight) {
  89124. _this._defaultHeight = webVROptions.defaultHeight;
  89125. _this.position.y = _this._defaultHeight;
  89126. }
  89127. _this.minZ = 0.1;
  89128. //legacy support - the compensation boolean was removed.
  89129. if (arguments.length === 5) {
  89130. _this.webVROptions = arguments[4];
  89131. }
  89132. // default webVR options
  89133. if (_this.webVROptions.trackPosition == undefined) {
  89134. _this.webVROptions.trackPosition = true;
  89135. }
  89136. if (_this.webVROptions.controllerMeshes == undefined) {
  89137. _this.webVROptions.controllerMeshes = true;
  89138. }
  89139. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  89140. _this.webVROptions.defaultLightingOnControllers = true;
  89141. }
  89142. _this.rotationQuaternion = new BABYLON.Quaternion();
  89143. if (_this.webVROptions && _this.webVROptions.positionScale) {
  89144. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  89145. }
  89146. //enable VR
  89147. var engine = _this.getEngine();
  89148. _this._onVREnabled = function (success) { if (success) {
  89149. _this.initControllers();
  89150. } };
  89151. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  89152. engine.initWebVR().add(function (event) {
  89153. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  89154. return;
  89155. }
  89156. _this._vrDevice = event.vrDisplay;
  89157. //reset the rig parameters.
  89158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  89159. if (_this._attached) {
  89160. _this.getEngine().enableVR();
  89161. }
  89162. });
  89163. if (typeof (VRFrameData) !== "undefined")
  89164. _this._frameData = new VRFrameData();
  89165. /**
  89166. * The idea behind the following lines:
  89167. * objects that have the camera as parent should actually have the rig cameras as a parent.
  89168. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  89169. * the second will not show it correctly.
  89170. *
  89171. * To solve this - each object that has the camera as parent will be added to a protected array.
  89172. * When the rig camera renders, it will take this array and set all of those to be its children.
  89173. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  89174. * Amazing!
  89175. */
  89176. scene.onBeforeCameraRenderObservable.add(function (camera) {
  89177. if (camera.parent === _this && _this.rigParenting) {
  89178. _this._descendants = _this.getDescendants(true, function (n) {
  89179. // don't take the cameras or the controllers!
  89180. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  89181. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  89182. return !isController && !isRigCamera;
  89183. });
  89184. _this._descendants.forEach(function (node) {
  89185. node.parent = camera;
  89186. });
  89187. }
  89188. });
  89189. scene.onAfterCameraRenderObservable.add(function (camera) {
  89190. if (camera.parent === _this && _this.rigParenting) {
  89191. _this._descendants.forEach(function (node) {
  89192. node.parent = _this;
  89193. });
  89194. }
  89195. });
  89196. return _this;
  89197. }
  89198. /**
  89199. * Gets the device distance from the ground in meters.
  89200. * @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.
  89201. */
  89202. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89203. if (this._standingMatrix) {
  89204. // Add standing matrix offset to get real offset from ground in room
  89205. this._standingMatrix.getTranslationToRef(this._workingVector);
  89206. return this._deviceRoomPosition.y + this._workingVector.y;
  89207. }
  89208. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89209. return this._defaultHeight || 0;
  89210. };
  89211. /**
  89212. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89213. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89214. */
  89215. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89216. var _this = this;
  89217. if (callback === void 0) { callback = function (bool) { }; }
  89218. // Use standing matrix if available
  89219. this.getEngine().initWebVRAsync().then(function (result) {
  89220. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89221. callback(false);
  89222. }
  89223. else {
  89224. _this._standingMatrix = new BABYLON.Matrix();
  89225. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89226. if (!_this.getScene().useRightHandedSystem) {
  89227. [2, 6, 8, 9, 14].forEach(function (num) {
  89228. if (_this._standingMatrix) {
  89229. _this._standingMatrix.m[num] *= -1;
  89230. }
  89231. });
  89232. }
  89233. callback(true);
  89234. }
  89235. });
  89236. };
  89237. /**
  89238. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89239. * @returns A promise with a boolean set to if the standing matrix is supported.
  89240. */
  89241. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89242. var _this = this;
  89243. return new Promise(function (res, rej) {
  89244. _this.useStandingMatrix(function (supported) {
  89245. res(supported);
  89246. });
  89247. });
  89248. };
  89249. /**
  89250. * Disposes the camera
  89251. */
  89252. WebVRFreeCamera.prototype.dispose = function () {
  89253. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89254. _super.prototype.dispose.call(this);
  89255. };
  89256. /**
  89257. * Gets a vrController by name.
  89258. * @param name The name of the controller to retreive
  89259. * @returns the controller matching the name specified or null if not found
  89260. */
  89261. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89262. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89263. var gp = _a[_i];
  89264. if (gp.hand === name) {
  89265. return gp;
  89266. }
  89267. }
  89268. return null;
  89269. };
  89270. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89271. /**
  89272. * The controller corrisponding to the users left hand.
  89273. */
  89274. get: function () {
  89275. if (!this._leftController) {
  89276. this._leftController = this.getControllerByName("left");
  89277. }
  89278. return this._leftController;
  89279. },
  89280. enumerable: true,
  89281. configurable: true
  89282. });
  89283. ;
  89284. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89285. /**
  89286. * The controller corrisponding to the users right hand.
  89287. */
  89288. get: function () {
  89289. if (!this._rightController) {
  89290. this._rightController = this.getControllerByName("right");
  89291. }
  89292. return this._rightController;
  89293. },
  89294. enumerable: true,
  89295. configurable: true
  89296. });
  89297. ;
  89298. /**
  89299. * Casts a ray forward from the vrCamera's gaze.
  89300. * @param length Length of the ray (default: 100)
  89301. * @returns the ray corrisponding to the gaze
  89302. */
  89303. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89304. if (length === void 0) { length = 100; }
  89305. if (this.leftCamera) {
  89306. // Use left eye to avoid computation to compute center on every call
  89307. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89308. }
  89309. else {
  89310. return _super.prototype.getForwardRay.call(this, length);
  89311. }
  89312. };
  89313. /**
  89314. * Updates the camera based on device's frame data
  89315. */
  89316. WebVRFreeCamera.prototype._checkInputs = function () {
  89317. if (this._vrDevice && this._vrDevice.isPresenting) {
  89318. this._vrDevice.getFrameData(this._frameData);
  89319. this.updateFromDevice(this._frameData.pose);
  89320. }
  89321. _super.prototype._checkInputs.call(this);
  89322. };
  89323. /**
  89324. * Updates the poseControlled values based on the input device pose.
  89325. * @param poseData Pose coming from the device
  89326. */
  89327. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89328. if (poseData && poseData.orientation) {
  89329. this.rawPose = poseData;
  89330. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89331. if (this.getScene().useRightHandedSystem) {
  89332. this._deviceRoomRotationQuaternion.z *= -1;
  89333. this._deviceRoomRotationQuaternion.w *= -1;
  89334. }
  89335. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89336. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89337. if (this.getScene().useRightHandedSystem) {
  89338. this._deviceRoomPosition.z *= -1;
  89339. }
  89340. }
  89341. }
  89342. };
  89343. /**
  89344. * WebVR's attach control will start broadcasting frames to the device.
  89345. * Note that in certain browsers (chrome for example) this function must be called
  89346. * within a user-interaction callback. Example:
  89347. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89348. *
  89349. * @param element html element to attach the vrDevice to
  89350. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89351. */
  89352. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89353. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89354. this._attached = true;
  89355. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89356. if (this._vrDevice) {
  89357. this.getEngine().enableVR();
  89358. }
  89359. };
  89360. /**
  89361. * Detaches the camera from the html element and disables VR
  89362. *
  89363. * @param element html element to detach from
  89364. */
  89365. WebVRFreeCamera.prototype.detachControl = function (element) {
  89366. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89367. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89368. _super.prototype.detachControl.call(this, element);
  89369. this._attached = false;
  89370. this.getEngine().disableVR();
  89371. };
  89372. /**
  89373. * @returns the name of this class
  89374. */
  89375. WebVRFreeCamera.prototype.getClassName = function () {
  89376. return "WebVRFreeCamera";
  89377. };
  89378. /**
  89379. * Calls resetPose on the vrDisplay
  89380. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89381. */
  89382. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89383. //uses the vrDisplay's "resetPose()".
  89384. //pitch and roll won't be affected.
  89385. this._vrDevice.resetPose();
  89386. };
  89387. /**
  89388. * Updates the rig cameras (left and right eye)
  89389. */
  89390. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89391. var camLeft = this._rigCameras[0];
  89392. var camRight = this._rigCameras[1];
  89393. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89394. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89395. camLeft.position.copyFrom(this._deviceRoomPosition);
  89396. camRight.position.copyFrom(this._deviceRoomPosition);
  89397. };
  89398. /**
  89399. * Updates the cached values of the camera
  89400. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89401. */
  89402. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89403. var _this = this;
  89404. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89405. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89406. if (!this.updateCacheCalled) {
  89407. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89408. this.updateCacheCalled = true;
  89409. this.update();
  89410. }
  89411. // Set working vector to the device position in room space rotated by the new rotation
  89412. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89413. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89414. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89415. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89416. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89417. // Add translation from anchor position
  89418. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89419. this._workingVector.addInPlace(this.position);
  89420. this._workingVector.subtractInPlace(this._cache.position);
  89421. this._deviceToWorld.setTranslation(this._workingVector);
  89422. // Set an inverted matrix to be used when updating the camera
  89423. this._deviceToWorld.invertToRef(this._worldToDevice);
  89424. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89425. this.controllers.forEach(function (controller) {
  89426. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89427. controller.update();
  89428. });
  89429. }
  89430. if (!ignoreParentClass) {
  89431. _super.prototype._updateCache.call(this);
  89432. }
  89433. this.updateCacheCalled = false;
  89434. };
  89435. /**
  89436. * Updates the current device position and rotation in the babylon world
  89437. */
  89438. WebVRFreeCamera.prototype.update = function () {
  89439. // Get current device position in babylon world
  89440. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89441. // Get current device rotation in babylon world
  89442. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89443. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89444. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89445. _super.prototype.update.call(this);
  89446. };
  89447. /**
  89448. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89449. * @returns an identity matrix
  89450. */
  89451. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89452. return BABYLON.Matrix.Identity();
  89453. };
  89454. /**
  89455. * This function is called by the two RIG cameras.
  89456. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89457. */
  89458. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89459. var _this = this;
  89460. // Update the parent camera prior to using a child camera to avoid desynchronization
  89461. var parentCamera = this._cameraRigParams["parentCamera"];
  89462. parentCamera._updateCache();
  89463. //WebVR 1.1
  89464. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89465. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89466. if (!this.getScene().useRightHandedSystem) {
  89467. [2, 6, 8, 9, 14].forEach(function (num) {
  89468. _this._webvrViewMatrix.m[num] *= -1;
  89469. });
  89470. }
  89471. // update the camera rotation matrix
  89472. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89473. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89474. // Computing target and final matrix
  89475. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89476. // should the view matrix be updated with scale and position offset?
  89477. if (parentCamera.deviceScaleFactor !== 1) {
  89478. this._webvrViewMatrix.invert();
  89479. // scale the position, if set
  89480. if (parentCamera.deviceScaleFactor) {
  89481. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89482. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89483. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89484. }
  89485. this._webvrViewMatrix.invert();
  89486. }
  89487. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89488. // Compute global position
  89489. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89490. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89491. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89492. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89493. this._markSyncedWithParent();
  89494. return this._webvrViewMatrix;
  89495. };
  89496. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89497. var _this = this;
  89498. var parentCamera = this.parent;
  89499. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89500. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89501. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89502. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89503. //babylon compatible matrix
  89504. if (!this.getScene().useRightHandedSystem) {
  89505. [8, 9, 10, 11].forEach(function (num) {
  89506. _this._projectionMatrix.m[num] *= -1;
  89507. });
  89508. }
  89509. return this._projectionMatrix;
  89510. };
  89511. /**
  89512. * Initializes the controllers and their meshes
  89513. */
  89514. WebVRFreeCamera.prototype.initControllers = function () {
  89515. var _this = this;
  89516. this.controllers = [];
  89517. var manager = this.getScene().gamepadManager;
  89518. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89519. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89520. var webVrController = gamepad;
  89521. if (webVrController.defaultModel) {
  89522. webVrController.defaultModel.setEnabled(false);
  89523. }
  89524. if (webVrController.hand === "right") {
  89525. _this._rightController = null;
  89526. }
  89527. if (webVrController.hand === "left") {
  89528. _this._leftController = null;
  89529. }
  89530. var controllerIndex = _this.controllers.indexOf(webVrController);
  89531. if (controllerIndex !== -1) {
  89532. _this.controllers.splice(controllerIndex, 1);
  89533. }
  89534. }
  89535. });
  89536. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89537. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89538. var webVrController_1 = gamepad;
  89539. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89540. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89541. if (_this.webVROptions.controllerMeshes) {
  89542. if (webVrController_1.defaultModel) {
  89543. webVrController_1.defaultModel.setEnabled(true);
  89544. }
  89545. else {
  89546. // Load the meshes
  89547. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89548. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89549. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89550. if (_this.webVROptions.defaultLightingOnControllers) {
  89551. if (!_this._lightOnControllers) {
  89552. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89553. }
  89554. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89555. var children = mesh.getChildren();
  89556. if (children.length !== 0) {
  89557. children.forEach(function (mesh) {
  89558. light.includedOnlyMeshes.push(mesh);
  89559. activateLightOnSubMeshes_1(mesh, light);
  89560. });
  89561. }
  89562. };
  89563. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89564. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89565. }
  89566. });
  89567. }
  89568. }
  89569. webVrController_1.attachToPoseControlledCamera(_this);
  89570. // since this is async - sanity check. Is the controller already stored?
  89571. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89572. //add to the controllers array
  89573. _this.controllers.push(webVrController_1);
  89574. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89575. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89576. // So we're overriding setting left & right manually to be sure
  89577. var firstViveWandDetected = false;
  89578. for (var i = 0; i < _this.controllers.length; i++) {
  89579. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89580. if (!firstViveWandDetected) {
  89581. firstViveWandDetected = true;
  89582. _this.controllers[i].hand = "left";
  89583. }
  89584. else {
  89585. _this.controllers[i].hand = "right";
  89586. }
  89587. }
  89588. }
  89589. //did we find enough controllers? Great! let the developer know.
  89590. if (_this.controllers.length >= 2) {
  89591. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89592. }
  89593. }
  89594. }
  89595. });
  89596. };
  89597. return WebVRFreeCamera;
  89598. }(BABYLON.FreeCamera));
  89599. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89600. })(BABYLON || (BABYLON = {}));
  89601. //# sourceMappingURL=babylon.webVRCamera.js.map
  89602. var BABYLON;
  89603. (function (BABYLON) {
  89604. // We're mainly based on the logic defined into the FreeCamera code
  89605. /**
  89606. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89607. * being tilted forward or back and left or right.
  89608. */
  89609. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89610. __extends(DeviceOrientationCamera, _super);
  89611. /**
  89612. * Creates a new device orientation camera
  89613. * @param name The name of the camera
  89614. * @param position The start position camera
  89615. * @param scene The scene the camera belongs to
  89616. */
  89617. function DeviceOrientationCamera(name, position, scene) {
  89618. var _this = _super.call(this, name, position, scene) || this;
  89619. _this._quaternionCache = new BABYLON.Quaternion();
  89620. _this.inputs.addDeviceOrientation();
  89621. return _this;
  89622. }
  89623. /**
  89624. * Gets the current instance class name ("DeviceOrientationCamera").
  89625. * This helps avoiding instanceof at run time.
  89626. * @returns the class name
  89627. */
  89628. DeviceOrientationCamera.prototype.getClassName = function () {
  89629. return "DeviceOrientationCamera";
  89630. };
  89631. /**
  89632. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89633. */
  89634. DeviceOrientationCamera.prototype._checkInputs = function () {
  89635. _super.prototype._checkInputs.call(this);
  89636. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89637. if (this._initialQuaternion) {
  89638. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89639. }
  89640. };
  89641. /**
  89642. * Reset the camera to its default orientation on the specified axis only.
  89643. * @param axis The axis to reset
  89644. */
  89645. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89646. var _this = this;
  89647. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89648. //can only work if this camera has a rotation quaternion already.
  89649. if (!this.rotationQuaternion)
  89650. return;
  89651. if (!this._initialQuaternion) {
  89652. this._initialQuaternion = new BABYLON.Quaternion();
  89653. }
  89654. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89655. ['x', 'y', 'z'].forEach(function (axisName) {
  89656. if (!axis[axisName]) {
  89657. _this._initialQuaternion[axisName] = 0;
  89658. }
  89659. else {
  89660. _this._initialQuaternion[axisName] *= -1;
  89661. }
  89662. });
  89663. this._initialQuaternion.normalize();
  89664. //force rotation update
  89665. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89666. };
  89667. return DeviceOrientationCamera;
  89668. }(BABYLON.FreeCamera));
  89669. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89670. })(BABYLON || (BABYLON = {}));
  89671. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89672. var BABYLON;
  89673. (function (BABYLON) {
  89674. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89675. __extends(VRDeviceOrientationFreeCamera, _super);
  89676. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89677. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89678. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89679. var _this = _super.call(this, name, position, scene) || this;
  89680. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89681. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89682. return _this;
  89683. }
  89684. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89685. return "VRDeviceOrientationFreeCamera";
  89686. };
  89687. return VRDeviceOrientationFreeCamera;
  89688. }(BABYLON.DeviceOrientationCamera));
  89689. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89690. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89691. __extends(VRDeviceOrientationGamepadCamera, _super);
  89692. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89693. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89694. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89695. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89696. _this.inputs.addGamepad();
  89697. return _this;
  89698. }
  89699. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89700. return "VRDeviceOrientationGamepadCamera";
  89701. };
  89702. return VRDeviceOrientationGamepadCamera;
  89703. }(VRDeviceOrientationFreeCamera));
  89704. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89705. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89706. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89707. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89708. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89709. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89710. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89711. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89712. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89713. _this.inputs.addVRDeviceOrientation();
  89714. return _this;
  89715. }
  89716. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89717. return "VRDeviceOrientationArcRotateCamera";
  89718. };
  89719. return VRDeviceOrientationArcRotateCamera;
  89720. }(BABYLON.ArcRotateCamera));
  89721. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89722. })(BABYLON || (BABYLON = {}));
  89723. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89724. var BABYLON;
  89725. (function (BABYLON) {
  89726. /**
  89727. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89728. */
  89729. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89730. __extends(AnaglyphFreeCamera, _super);
  89731. /**
  89732. * Creates a new AnaglyphFreeCamera
  89733. * @param name defines camera name
  89734. * @param position defines initial position
  89735. * @param interaxialDistance defines distance between each color axis
  89736. * @param scene defines the hosting scene
  89737. */
  89738. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89739. var _this = _super.call(this, name, position, scene) || this;
  89740. _this.interaxialDistance = interaxialDistance;
  89741. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89742. return _this;
  89743. }
  89744. /**
  89745. * Gets camera class name
  89746. * @returns AnaglyphFreeCamera
  89747. */
  89748. AnaglyphFreeCamera.prototype.getClassName = function () {
  89749. return "AnaglyphFreeCamera";
  89750. };
  89751. return AnaglyphFreeCamera;
  89752. }(BABYLON.FreeCamera));
  89753. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89754. /**
  89755. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89756. */
  89757. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89758. __extends(AnaglyphArcRotateCamera, _super);
  89759. /**
  89760. * Creates a new AnaglyphArcRotateCamera
  89761. * @param name defines camera name
  89762. * @param alpha defines alpha angle (in radians)
  89763. * @param beta defines beta angle (in radians)
  89764. * @param radius defines radius
  89765. * @param target defines camera target
  89766. * @param interaxialDistance defines distance between each color axis
  89767. * @param scene defines the hosting scene
  89768. */
  89769. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89770. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89771. _this.interaxialDistance = interaxialDistance;
  89772. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89773. return _this;
  89774. }
  89775. /**
  89776. * Gets camera class name
  89777. * @returns AnaglyphArcRotateCamera
  89778. */
  89779. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89780. return "AnaglyphArcRotateCamera";
  89781. };
  89782. return AnaglyphArcRotateCamera;
  89783. }(BABYLON.ArcRotateCamera));
  89784. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89785. /**
  89786. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89787. */
  89788. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89789. __extends(AnaglyphGamepadCamera, _super);
  89790. /**
  89791. * Creates a new AnaglyphGamepadCamera
  89792. * @param name defines camera name
  89793. * @param position defines initial position
  89794. * @param interaxialDistance defines distance between each color axis
  89795. * @param scene defines the hosting scene
  89796. */
  89797. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89798. var _this = _super.call(this, name, position, scene) || this;
  89799. _this.interaxialDistance = interaxialDistance;
  89800. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89801. return _this;
  89802. }
  89803. /**
  89804. * Gets camera class name
  89805. * @returns AnaglyphGamepadCamera
  89806. */
  89807. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89808. return "AnaglyphGamepadCamera";
  89809. };
  89810. return AnaglyphGamepadCamera;
  89811. }(BABYLON.GamepadCamera));
  89812. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89813. /**
  89814. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89815. */
  89816. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89817. __extends(AnaglyphUniversalCamera, _super);
  89818. /**
  89819. * Creates a new AnaglyphUniversalCamera
  89820. * @param name defines camera name
  89821. * @param position defines initial position
  89822. * @param interaxialDistance defines distance between each color axis
  89823. * @param scene defines the hosting scene
  89824. */
  89825. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89826. var _this = _super.call(this, name, position, scene) || this;
  89827. _this.interaxialDistance = interaxialDistance;
  89828. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89829. return _this;
  89830. }
  89831. /**
  89832. * Gets camera class name
  89833. * @returns AnaglyphUniversalCamera
  89834. */
  89835. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89836. return "AnaglyphUniversalCamera";
  89837. };
  89838. return AnaglyphUniversalCamera;
  89839. }(BABYLON.UniversalCamera));
  89840. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89841. /**
  89842. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89843. */
  89844. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89845. __extends(StereoscopicFreeCamera, _super);
  89846. /**
  89847. * Creates a new StereoscopicFreeCamera
  89848. * @param name defines camera name
  89849. * @param position defines initial position
  89850. * @param interaxialDistance defines distance between each color axis
  89851. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89852. * @param scene defines the hosting scene
  89853. */
  89854. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89855. var _this = _super.call(this, name, position, scene) || this;
  89856. _this.interaxialDistance = interaxialDistance;
  89857. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89858. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89859. return _this;
  89860. }
  89861. /**
  89862. * Gets camera class name
  89863. * @returns StereoscopicFreeCamera
  89864. */
  89865. StereoscopicFreeCamera.prototype.getClassName = function () {
  89866. return "StereoscopicFreeCamera";
  89867. };
  89868. return StereoscopicFreeCamera;
  89869. }(BABYLON.FreeCamera));
  89870. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89871. /**
  89872. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89873. */
  89874. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89875. __extends(StereoscopicArcRotateCamera, _super);
  89876. /**
  89877. * Creates a new StereoscopicArcRotateCamera
  89878. * @param name defines camera name
  89879. * @param alpha defines alpha angle (in radians)
  89880. * @param beta defines beta angle (in radians)
  89881. * @param radius defines radius
  89882. * @param target defines camera target
  89883. * @param interaxialDistance defines distance between each color axis
  89884. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89885. * @param scene defines the hosting scene
  89886. */
  89887. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89888. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89889. _this.interaxialDistance = interaxialDistance;
  89890. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89891. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89892. return _this;
  89893. }
  89894. /**
  89895. * Gets camera class name
  89896. * @returns StereoscopicArcRotateCamera
  89897. */
  89898. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89899. return "StereoscopicArcRotateCamera";
  89900. };
  89901. return StereoscopicArcRotateCamera;
  89902. }(BABYLON.ArcRotateCamera));
  89903. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89904. /**
  89905. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89906. */
  89907. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89908. __extends(StereoscopicGamepadCamera, _super);
  89909. /**
  89910. * Creates a new StereoscopicGamepadCamera
  89911. * @param name defines camera name
  89912. * @param position defines initial position
  89913. * @param interaxialDistance defines distance between each color axis
  89914. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89915. * @param scene defines the hosting scene
  89916. */
  89917. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89918. var _this = _super.call(this, name, position, scene) || this;
  89919. _this.interaxialDistance = interaxialDistance;
  89920. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89921. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89922. return _this;
  89923. }
  89924. /**
  89925. * Gets camera class name
  89926. * @returns StereoscopicGamepadCamera
  89927. */
  89928. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89929. return "StereoscopicGamepadCamera";
  89930. };
  89931. return StereoscopicGamepadCamera;
  89932. }(BABYLON.GamepadCamera));
  89933. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89934. /**
  89935. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89936. */
  89937. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89938. __extends(StereoscopicUniversalCamera, _super);
  89939. /**
  89940. * Creates a new StereoscopicUniversalCamera
  89941. * @param name defines camera name
  89942. * @param position defines initial position
  89943. * @param interaxialDistance defines distance between each color axis
  89944. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89945. * @param scene defines the hosting scene
  89946. */
  89947. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89948. var _this = _super.call(this, name, position, scene) || this;
  89949. _this.interaxialDistance = interaxialDistance;
  89950. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89951. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89952. return _this;
  89953. }
  89954. /**
  89955. * Gets camera class name
  89956. * @returns StereoscopicUniversalCamera
  89957. */
  89958. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89959. return "StereoscopicUniversalCamera";
  89960. };
  89961. return StereoscopicUniversalCamera;
  89962. }(BABYLON.UniversalCamera));
  89963. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89964. })(BABYLON || (BABYLON = {}));
  89965. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89966. var BABYLON;
  89967. (function (BABYLON) {
  89968. var VRExperienceHelperGazer = /** @class */ (function () {
  89969. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89970. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89971. this.scene = scene;
  89972. this._pointerDownOnMeshAsked = false;
  89973. this._isActionableMesh = false;
  89974. this._teleportationRequestInitiated = false;
  89975. this._teleportationBackRequestInitiated = false;
  89976. this._rotationRightAsked = false;
  89977. this._rotationLeftAsked = false;
  89978. this._dpadPressed = true;
  89979. this._activePointer = false;
  89980. this._id = VRExperienceHelperGazer._idCounter++;
  89981. // Gaze tracker
  89982. if (!gazeTrackerToClone) {
  89983. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89984. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89985. this._gazeTracker.isPickable = false;
  89986. this._gazeTracker.isVisible = false;
  89987. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89988. targetMat.specularColor = BABYLON.Color3.Black();
  89989. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89990. targetMat.backFaceCulling = false;
  89991. this._gazeTracker.material = targetMat;
  89992. }
  89993. else {
  89994. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89995. }
  89996. }
  89997. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89998. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89999. };
  90000. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90001. this._pointerDownOnMeshAsked = true;
  90002. if (this._currentHit) {
  90003. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90004. }
  90005. };
  90006. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90007. if (this._currentHit) {
  90008. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90009. }
  90010. this._pointerDownOnMeshAsked = false;
  90011. };
  90012. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90013. this._activePointer = true;
  90014. };
  90015. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90016. this._activePointer = false;
  90017. };
  90018. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90019. if (distance === void 0) { distance = 100; }
  90020. };
  90021. VRExperienceHelperGazer.prototype.dispose = function () {
  90022. this._interactionsEnabled = false;
  90023. this._teleportationEnabled = false;
  90024. if (this._gazeTracker) {
  90025. this._gazeTracker.dispose();
  90026. }
  90027. };
  90028. VRExperienceHelperGazer._idCounter = 0;
  90029. return VRExperienceHelperGazer;
  90030. }());
  90031. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90032. __extends(VRExperienceHelperControllerGazer, _super);
  90033. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90034. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90035. _this.webVRController = webVRController;
  90036. // Laser pointer
  90037. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90038. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90039. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90040. laserPointerMaterial.alpha = 0.6;
  90041. _this._laserPointer.material = laserPointerMaterial;
  90042. _this._laserPointer.rotation.x = Math.PI / 2;
  90043. _this._laserPointer.position.z = -0.5;
  90044. _this._laserPointer.isVisible = false;
  90045. if (!webVRController.mesh) {
  90046. // Create an empty mesh that is used prior to loading the high quality model
  90047. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90048. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90049. preloadPointerPose.rotation.x = -0.7;
  90050. preloadMesh.addChild(preloadPointerPose);
  90051. webVRController.attachToMesh(preloadMesh);
  90052. }
  90053. _this._setLaserPointerParent(webVRController.mesh);
  90054. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90055. _this._setLaserPointerParent(mesh);
  90056. });
  90057. return _this;
  90058. }
  90059. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90060. return this.webVRController.getForwardRay(length);
  90061. };
  90062. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90063. _super.prototype._activatePointer.call(this);
  90064. this._laserPointer.isVisible = true;
  90065. };
  90066. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90067. _super.prototype._deactivatePointer.call(this);
  90068. this._laserPointer.isVisible = false;
  90069. };
  90070. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90071. this._laserPointer.material.emissiveColor = color;
  90072. };
  90073. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90074. var makeNotPick = function (root) {
  90075. root.name += " laserPointer";
  90076. root.getChildMeshes().forEach(function (c) {
  90077. makeNotPick(c);
  90078. });
  90079. };
  90080. makeNotPick(mesh);
  90081. var childMeshes = mesh.getChildMeshes();
  90082. this.webVRController._pointingPoseNode = null;
  90083. for (var i = 0; i < childMeshes.length; i++) {
  90084. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90085. mesh = childMeshes[i];
  90086. this.webVRController._pointingPoseNode = mesh;
  90087. break;
  90088. }
  90089. }
  90090. this._laserPointer.parent = mesh;
  90091. };
  90092. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90093. if (distance === void 0) { distance = 100; }
  90094. this._laserPointer.scaling.y = distance;
  90095. this._laserPointer.position.z = -distance / 2;
  90096. };
  90097. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90098. _super.prototype.dispose.call(this);
  90099. this._laserPointer.dispose();
  90100. if (this._meshAttachedObserver) {
  90101. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90102. }
  90103. };
  90104. return VRExperienceHelperControllerGazer;
  90105. }(VRExperienceHelperGazer));
  90106. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90107. __extends(VRExperienceHelperCameraGazer, _super);
  90108. function VRExperienceHelperCameraGazer(getCamera, scene) {
  90109. var _this = _super.call(this, scene) || this;
  90110. _this.getCamera = getCamera;
  90111. return _this;
  90112. }
  90113. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  90114. var camera = this.getCamera();
  90115. if (camera) {
  90116. return camera.getForwardRay(length);
  90117. }
  90118. else {
  90119. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  90120. }
  90121. };
  90122. return VRExperienceHelperCameraGazer;
  90123. }(VRExperienceHelperGazer));
  90124. /**
  90125. * Helps to quickly add VR support to an existing scene.
  90126. * See http://doc.babylonjs.com/how_to/webvr_helper
  90127. */
  90128. var VRExperienceHelper = /** @class */ (function () {
  90129. /**
  90130. * Instantiates a VRExperienceHelper.
  90131. * Helps to quickly add VR support to an existing scene.
  90132. * @param scene The scene the VRExperienceHelper belongs to.
  90133. * @param webVROptions Options to modify the vr experience helper's behavior.
  90134. */
  90135. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  90136. if (webVROptions === void 0) { webVROptions = {}; }
  90137. var _this = this;
  90138. this.webVROptions = webVROptions;
  90139. // Can the system support WebVR, even if a headset isn't plugged in?
  90140. this._webVRsupported = false;
  90141. // If WebVR is supported, is a headset plugged in and are we ready to present?
  90142. this._webVRready = false;
  90143. // Are we waiting for the requestPresent callback to complete?
  90144. this._webVRrequesting = false;
  90145. // Are we presenting to the headset right now?
  90146. this._webVRpresenting = false;
  90147. // Are we presenting in the fullscreen fallback?
  90148. this._fullscreenVRpresenting = false;
  90149. /**
  90150. * Observable raised when entering VR.
  90151. */
  90152. this.onEnteringVRObservable = new BABYLON.Observable();
  90153. /**
  90154. * Observable raised when exiting VR.
  90155. */
  90156. this.onExitingVRObservable = new BABYLON.Observable();
  90157. /**
  90158. * Observable raised when controller mesh is loaded.
  90159. */
  90160. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90161. this._useCustomVRButton = false;
  90162. this._teleportationRequested = false;
  90163. this._teleportActive = false;
  90164. this._floorMeshesCollection = [];
  90165. this._rotationAllowed = true;
  90166. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  90167. this._isDefaultTeleportationTarget = true;
  90168. this._teleportationFillColor = "#444444";
  90169. this._teleportationBorderColor = "#FFFFFF";
  90170. this._rotationAngle = 0;
  90171. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  90172. this._padSensibilityUp = 0.65;
  90173. this._padSensibilityDown = 0.35;
  90174. this.leftController = null;
  90175. this.rightController = null;
  90176. /**
  90177. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  90178. */
  90179. this.onNewMeshSelected = new BABYLON.Observable();
  90180. /**
  90181. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  90182. */
  90183. this.onNewMeshPicked = new BABYLON.Observable();
  90184. /**
  90185. * Observable raised before camera teleportation
  90186. */
  90187. this.onBeforeCameraTeleport = new BABYLON.Observable();
  90188. /**
  90189. * Observable raised after camera teleportation
  90190. */
  90191. this.onAfterCameraTeleport = new BABYLON.Observable();
  90192. /**
  90193. * Observable raised when current selected mesh gets unselected
  90194. */
  90195. this.onSelectedMeshUnselected = new BABYLON.Observable();
  90196. /**
  90197. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90198. */
  90199. this.teleportationEnabled = true;
  90200. this._teleportationInitialized = false;
  90201. this._interactionsEnabled = false;
  90202. this._interactionsRequested = false;
  90203. this._displayGaze = true;
  90204. this._displayLaserPointer = true;
  90205. this._onResize = function () {
  90206. _this.moveButtonToBottomRight();
  90207. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90208. _this.exitVR();
  90209. }
  90210. };
  90211. this._onFullscreenChange = function () {
  90212. if (document.fullscreen !== undefined) {
  90213. _this._fullscreenVRpresenting = document.fullscreen;
  90214. }
  90215. else if (document.mozFullScreen !== undefined) {
  90216. _this._fullscreenVRpresenting = document.mozFullScreen;
  90217. }
  90218. else if (document.webkitIsFullScreen !== undefined) {
  90219. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90220. }
  90221. else if (document.msIsFullScreen !== undefined) {
  90222. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90223. }
  90224. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90225. _this.exitVR();
  90226. if (!_this._useCustomVRButton) {
  90227. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90228. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90229. }
  90230. }
  90231. };
  90232. this.beforeRender = function () {
  90233. if (_this.leftController && _this.leftController._activePointer) {
  90234. _this._castRayAndSelectObject(_this.leftController);
  90235. }
  90236. if (_this.rightController && _this.rightController._activePointer) {
  90237. _this._castRayAndSelectObject(_this.rightController);
  90238. }
  90239. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  90240. _this._castRayAndSelectObject(_this._cameraGazer);
  90241. }
  90242. else {
  90243. _this._cameraGazer._gazeTracker.isVisible = false;
  90244. }
  90245. };
  90246. this._onNewGamepadConnected = function (gamepad) {
  90247. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90248. if (gamepad.leftStick) {
  90249. gamepad.onleftstickchanged(function (stickValues) {
  90250. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90251. // Listening to classic/xbox gamepad only if no VR controller is active
  90252. if ((!_this.leftController && !_this.rightController) ||
  90253. ((_this.leftController && !_this.leftController._activePointer) &&
  90254. (_this.rightController && !_this.rightController._activePointer))) {
  90255. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90256. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90257. }
  90258. }
  90259. });
  90260. }
  90261. if (gamepad.rightStick) {
  90262. gamepad.onrightstickchanged(function (stickValues) {
  90263. if (_this._teleportationInitialized) {
  90264. _this._checkRotate(stickValues, _this._cameraGazer);
  90265. }
  90266. });
  90267. }
  90268. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90269. gamepad.onbuttondown(function (buttonPressed) {
  90270. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90271. _this._cameraGazer._selectionPointerDown();
  90272. }
  90273. });
  90274. gamepad.onbuttonup(function (buttonPressed) {
  90275. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90276. _this._cameraGazer._selectionPointerUp();
  90277. }
  90278. });
  90279. }
  90280. }
  90281. else {
  90282. var webVRController = gamepad;
  90283. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90284. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90285. _this.rightController = controller;
  90286. }
  90287. else {
  90288. _this.leftController = controller;
  90289. }
  90290. _this._tryEnableInteractionOnController(controller);
  90291. }
  90292. };
  90293. // 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
  90294. this._tryEnableInteractionOnController = function (controller) {
  90295. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90296. _this._enableInteractionOnController(controller);
  90297. }
  90298. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90299. _this._enableTeleportationOnController(controller);
  90300. }
  90301. };
  90302. this._onNewGamepadDisconnected = function (gamepad) {
  90303. if (gamepad instanceof BABYLON.WebVRController) {
  90304. if (gamepad.hand === "left" && _this.leftController != null) {
  90305. _this.leftController.dispose();
  90306. _this.leftController = null;
  90307. }
  90308. if (gamepad.hand === "right" && _this.rightController != null) {
  90309. _this.rightController.dispose();
  90310. _this.rightController = null;
  90311. }
  90312. }
  90313. };
  90314. this._workingVector = BABYLON.Vector3.Zero();
  90315. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90316. this._workingMatrix = BABYLON.Matrix.Identity();
  90317. this._scene = scene;
  90318. this._canvas = scene.getEngine().getRenderingCanvas();
  90319. // Parse options
  90320. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90321. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90322. }
  90323. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90324. webVROptions.createDeviceOrientationCamera = true;
  90325. }
  90326. if (webVROptions.laserToggle === undefined) {
  90327. webVROptions.laserToggle = true;
  90328. }
  90329. if (webVROptions.defaultHeight === undefined) {
  90330. webVROptions.defaultHeight = 1.7;
  90331. }
  90332. if (webVROptions.useCustomVRButton) {
  90333. this._useCustomVRButton = true;
  90334. if (webVROptions.customVRButton) {
  90335. this._btnVR = webVROptions.customVRButton;
  90336. }
  90337. }
  90338. if (webVROptions.rayLength) {
  90339. this._rayLength = webVROptions.rayLength;
  90340. }
  90341. this._defaultHeight = webVROptions.defaultHeight;
  90342. if (webVROptions.positionScale) {
  90343. this._rayLength *= webVROptions.positionScale;
  90344. this._defaultHeight *= webVROptions.positionScale;
  90345. }
  90346. // Set position
  90347. if (this._scene.activeCamera) {
  90348. this._position = this._scene.activeCamera.position.clone();
  90349. }
  90350. else {
  90351. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90352. }
  90353. // Set non-vr camera
  90354. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90355. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90356. // Copy data from existing camera
  90357. if (this._scene.activeCamera) {
  90358. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90359. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90360. // Set rotation from previous camera
  90361. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90362. var targetCamera = this._scene.activeCamera;
  90363. if (targetCamera.rotationQuaternion) {
  90364. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90365. }
  90366. else {
  90367. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90368. }
  90369. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90370. }
  90371. }
  90372. this._scene.activeCamera = this._deviceOrientationCamera;
  90373. if (this._canvas) {
  90374. this._scene.activeCamera.attachControl(this._canvas);
  90375. }
  90376. }
  90377. else {
  90378. this._existingCamera = this._scene.activeCamera;
  90379. }
  90380. // Create VR cameras
  90381. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90382. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90383. }
  90384. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90385. this._webVRCamera.useStandingMatrix();
  90386. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90387. // Create default button
  90388. if (!this._useCustomVRButton) {
  90389. this._btnVR = document.createElement("BUTTON");
  90390. this._btnVR.className = "babylonVRicon";
  90391. this._btnVR.id = "babylonVRiconbtn";
  90392. this._btnVR.title = "Click to switch to VR";
  90393. 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) }";
  90394. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90395. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90396. // css += ".babylonVRicon.vrdisplaysupported { }";
  90397. // css += ".babylonVRicon.vrdisplayready { }";
  90398. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90399. var style = document.createElement('style');
  90400. style.appendChild(document.createTextNode(css));
  90401. document.getElementsByTagName('head')[0].appendChild(style);
  90402. this.moveButtonToBottomRight();
  90403. }
  90404. // VR button click event
  90405. if (this._btnVR) {
  90406. this._btnVR.addEventListener("click", function () {
  90407. if (!_this.isInVRMode) {
  90408. _this.enterVR();
  90409. }
  90410. else {
  90411. _this.exitVR();
  90412. }
  90413. });
  90414. }
  90415. // Window events
  90416. window.addEventListener("resize", this._onResize);
  90417. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90418. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90419. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90420. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90421. // Display vr button when headset is connected
  90422. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90423. this.displayVRButton();
  90424. }
  90425. else {
  90426. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90427. if (e.vrDisplay) {
  90428. _this.displayVRButton();
  90429. }
  90430. });
  90431. }
  90432. // Exiting VR mode using 'ESC' key on desktop
  90433. this._onKeyDown = function (event) {
  90434. if (event.keyCode === 27 && _this.isInVRMode) {
  90435. _this.exitVR();
  90436. }
  90437. };
  90438. document.addEventListener("keydown", this._onKeyDown);
  90439. // Exiting VR mode double tapping the touch screen
  90440. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90441. if (_this.isInVRMode) {
  90442. _this.exitVR();
  90443. if (_this._fullscreenVRpresenting) {
  90444. _this._scene.getEngine().switchFullscreen(true);
  90445. }
  90446. }
  90447. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90448. // Listen for WebVR display changes
  90449. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90450. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90451. this._onVRRequestPresentStart = function () {
  90452. _this._webVRrequesting = true;
  90453. _this.updateButtonVisibility();
  90454. };
  90455. this._onVRRequestPresentComplete = function (success) {
  90456. _this._webVRrequesting = false;
  90457. _this.updateButtonVisibility();
  90458. };
  90459. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90460. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90461. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90462. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90463. scene.onDisposeObservable.add(function () {
  90464. _this.dispose();
  90465. });
  90466. // Gamepad connection events
  90467. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90468. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90469. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90470. this.updateButtonVisibility();
  90471. //create easing functions
  90472. this._circleEase = new BABYLON.CircleEase();
  90473. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90474. if (this.webVROptions.floorMeshes) {
  90475. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90476. }
  90477. }
  90478. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90479. /** Return this.onEnteringVRObservable
  90480. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90481. */
  90482. get: function () {
  90483. return this.onEnteringVRObservable;
  90484. },
  90485. enumerable: true,
  90486. configurable: true
  90487. });
  90488. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90489. /** Return this.onExitingVRObservable
  90490. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90491. */
  90492. get: function () {
  90493. return this.onExitingVRObservable;
  90494. },
  90495. enumerable: true,
  90496. configurable: true
  90497. });
  90498. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90499. /** Return this.onControllerMeshLoadedObservable
  90500. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90501. */
  90502. get: function () {
  90503. return this.onControllerMeshLoadedObservable;
  90504. },
  90505. enumerable: true,
  90506. configurable: true
  90507. });
  90508. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90509. /**
  90510. * The mesh used to display where the user is going to teleport.
  90511. */
  90512. get: function () {
  90513. return this._teleportationTarget;
  90514. },
  90515. /**
  90516. * Sets the mesh to be used to display where the user is going to teleport.
  90517. */
  90518. set: function (value) {
  90519. if (value) {
  90520. value.name = "teleportationTarget";
  90521. this._isDefaultTeleportationTarget = false;
  90522. this._teleportationTarget = value;
  90523. }
  90524. },
  90525. enumerable: true,
  90526. configurable: true
  90527. });
  90528. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90529. /**
  90530. * The mesh used to display where the user is selecting,
  90531. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90532. * See http://doc.babylonjs.com/resources/baking_transformations
  90533. */
  90534. get: function () {
  90535. return this._cameraGazer._gazeTracker;
  90536. },
  90537. set: function (value) {
  90538. if (value) {
  90539. this._cameraGazer._gazeTracker = value;
  90540. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90541. this._cameraGazer._gazeTracker.isPickable = false;
  90542. this._cameraGazer._gazeTracker.isVisible = false;
  90543. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90544. if (this.leftController) {
  90545. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90546. }
  90547. if (this.rightController) {
  90548. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90549. }
  90550. }
  90551. },
  90552. enumerable: true,
  90553. configurable: true
  90554. });
  90555. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90556. /**
  90557. * If the ray of the gaze should be displayed.
  90558. */
  90559. get: function () {
  90560. return this._displayGaze;
  90561. },
  90562. /**
  90563. * Sets if the ray of the gaze should be displayed.
  90564. */
  90565. set: function (value) {
  90566. this._displayGaze = value;
  90567. if (!value) {
  90568. this._cameraGazer._gazeTracker.isVisible = false;
  90569. if (this.leftController) {
  90570. this.leftController._gazeTracker.isVisible = false;
  90571. }
  90572. if (this.rightController) {
  90573. this.rightController._gazeTracker.isVisible = false;
  90574. }
  90575. }
  90576. },
  90577. enumerable: true,
  90578. configurable: true
  90579. });
  90580. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90581. /**
  90582. * If the ray of the LaserPointer should be displayed.
  90583. */
  90584. get: function () {
  90585. return this._displayLaserPointer;
  90586. },
  90587. /**
  90588. * Sets if the ray of the LaserPointer should be displayed.
  90589. */
  90590. set: function (value) {
  90591. this._displayLaserPointer = value;
  90592. if (!value) {
  90593. if (this.rightController) {
  90594. this.rightController._deactivatePointer();
  90595. this.rightController._gazeTracker.isVisible = false;
  90596. }
  90597. if (this.leftController) {
  90598. this.leftController._deactivatePointer();
  90599. this.leftController._gazeTracker.isVisible = false;
  90600. }
  90601. }
  90602. else {
  90603. if (this.rightController) {
  90604. this.rightController._activatePointer();
  90605. }
  90606. if (this.leftController) {
  90607. this.leftController._activatePointer();
  90608. }
  90609. }
  90610. },
  90611. enumerable: true,
  90612. configurable: true
  90613. });
  90614. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90615. /**
  90616. * The deviceOrientationCamera used as the camera when not in VR.
  90617. */
  90618. get: function () {
  90619. return this._deviceOrientationCamera;
  90620. },
  90621. enumerable: true,
  90622. configurable: true
  90623. });
  90624. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90625. /**
  90626. * Based on the current WebVR support, returns the current VR camera used.
  90627. */
  90628. get: function () {
  90629. if (this._webVRready) {
  90630. return this._webVRCamera;
  90631. }
  90632. else {
  90633. return this._scene.activeCamera;
  90634. }
  90635. },
  90636. enumerable: true,
  90637. configurable: true
  90638. });
  90639. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90640. /**
  90641. * The webVRCamera which is used when in VR.
  90642. */
  90643. get: function () {
  90644. return this._webVRCamera;
  90645. },
  90646. enumerable: true,
  90647. configurable: true
  90648. });
  90649. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90650. /**
  90651. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90652. */
  90653. get: function () {
  90654. return this._vrDeviceOrientationCamera;
  90655. },
  90656. enumerable: true,
  90657. configurable: true
  90658. });
  90659. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90660. get: function () {
  90661. var result = this._cameraGazer._teleportationRequestInitiated
  90662. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90663. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90664. return result;
  90665. },
  90666. enumerable: true,
  90667. configurable: true
  90668. });
  90669. // Raised when one of the controller has loaded successfully its associated default mesh
  90670. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90671. if (this.leftController && this.leftController.webVRController == webVRController) {
  90672. if (webVRController.mesh) {
  90673. this.leftController._setLaserPointerParent(webVRController.mesh);
  90674. }
  90675. }
  90676. if (this.rightController && this.rightController.webVRController == webVRController) {
  90677. if (webVRController.mesh) {
  90678. this.rightController._setLaserPointerParent(webVRController.mesh);
  90679. }
  90680. }
  90681. try {
  90682. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90683. }
  90684. catch (err) {
  90685. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90686. }
  90687. };
  90688. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90689. /**
  90690. * Gets a value indicating if we are currently in VR mode.
  90691. */
  90692. get: function () {
  90693. return this._webVRpresenting || this._fullscreenVRpresenting;
  90694. },
  90695. enumerable: true,
  90696. configurable: true
  90697. });
  90698. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90699. var vrDisplay = this._scene.getEngine().getVRDevice();
  90700. if (vrDisplay) {
  90701. var wasPresenting = this._webVRpresenting;
  90702. // A VR display is connected
  90703. this._webVRpresenting = vrDisplay.isPresenting;
  90704. if (wasPresenting && !this._webVRpresenting)
  90705. this.exitVR();
  90706. }
  90707. else {
  90708. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90709. }
  90710. this.updateButtonVisibility();
  90711. };
  90712. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90713. this._webVRsupported = eventArgs.vrSupported;
  90714. this._webVRready = !!eventArgs.vrDisplay;
  90715. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90716. this.updateButtonVisibility();
  90717. };
  90718. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90719. if (this._canvas && !this._useCustomVRButton) {
  90720. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90721. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90722. }
  90723. };
  90724. VRExperienceHelper.prototype.displayVRButton = function () {
  90725. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90726. document.body.appendChild(this._btnVR);
  90727. this._btnVRDisplayed = true;
  90728. }
  90729. };
  90730. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90731. if (!this._btnVR || this._useCustomVRButton) {
  90732. return;
  90733. }
  90734. this._btnVR.className = "babylonVRicon";
  90735. if (this.isInVRMode) {
  90736. this._btnVR.className += " vrdisplaypresenting";
  90737. }
  90738. else {
  90739. if (this._webVRready)
  90740. this._btnVR.className += " vrdisplayready";
  90741. if (this._webVRsupported)
  90742. this._btnVR.className += " vrdisplaysupported";
  90743. if (this._webVRrequesting)
  90744. this._btnVR.className += " vrdisplayrequesting";
  90745. }
  90746. };
  90747. /**
  90748. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90749. * Otherwise, will use the fullscreen API.
  90750. */
  90751. VRExperienceHelper.prototype.enterVR = function () {
  90752. if (this.onEnteringVRObservable) {
  90753. try {
  90754. this.onEnteringVRObservable.notifyObservers(this);
  90755. }
  90756. catch (err) {
  90757. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90758. }
  90759. }
  90760. if (this._scene.activeCamera) {
  90761. this._position = this._scene.activeCamera.position.clone();
  90762. // make sure that we return to the last active camera
  90763. this._existingCamera = this._scene.activeCamera;
  90764. }
  90765. if (this._webVRrequesting)
  90766. return;
  90767. // If WebVR is supported and a headset is connected
  90768. if (this._webVRready) {
  90769. if (!this._webVRpresenting) {
  90770. this._webVRCamera.position = this._position;
  90771. this._scene.activeCamera = this._webVRCamera;
  90772. }
  90773. }
  90774. else if (this._vrDeviceOrientationCamera) {
  90775. this._vrDeviceOrientationCamera.position = this._position;
  90776. if (this._scene.activeCamera) {
  90777. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90778. }
  90779. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90780. this._scene.getEngine().switchFullscreen(true);
  90781. this.updateButtonVisibility();
  90782. }
  90783. if (this._scene.activeCamera && this._canvas) {
  90784. this._scene.activeCamera.attachControl(this._canvas);
  90785. }
  90786. if (this._interactionsEnabled) {
  90787. this._scene.registerBeforeRender(this.beforeRender);
  90788. }
  90789. };
  90790. /**
  90791. * Attempt to exit VR, or fullscreen.
  90792. */
  90793. VRExperienceHelper.prototype.exitVR = function () {
  90794. if (this.onExitingVRObservable) {
  90795. try {
  90796. this.onExitingVRObservable.notifyObservers(this);
  90797. }
  90798. catch (err) {
  90799. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90800. }
  90801. }
  90802. if (this._webVRpresenting) {
  90803. this._scene.getEngine().disableVR();
  90804. }
  90805. if (this._scene.activeCamera) {
  90806. this._position = this._scene.activeCamera.position.clone();
  90807. }
  90808. if (this._deviceOrientationCamera) {
  90809. this._deviceOrientationCamera.position = this._position;
  90810. this._scene.activeCamera = this._deviceOrientationCamera;
  90811. if (this._canvas) {
  90812. this._scene.activeCamera.attachControl(this._canvas);
  90813. }
  90814. }
  90815. else if (this._existingCamera) {
  90816. this._existingCamera.position = this._position;
  90817. this._scene.activeCamera = this._existingCamera;
  90818. }
  90819. this.updateButtonVisibility();
  90820. if (this._interactionsEnabled) {
  90821. this._scene.unregisterBeforeRender(this.beforeRender);
  90822. }
  90823. // resize to update width and height when exiting vr exits fullscreen
  90824. this._scene.getEngine().resize();
  90825. };
  90826. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90827. /**
  90828. * The position of the vr experience helper.
  90829. */
  90830. get: function () {
  90831. return this._position;
  90832. },
  90833. /**
  90834. * Sets the position of the vr experience helper.
  90835. */
  90836. set: function (value) {
  90837. this._position = value;
  90838. if (this._scene.activeCamera) {
  90839. this._scene.activeCamera.position = value;
  90840. }
  90841. },
  90842. enumerable: true,
  90843. configurable: true
  90844. });
  90845. /**
  90846. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90847. */
  90848. VRExperienceHelper.prototype.enableInteractions = function () {
  90849. var _this = this;
  90850. if (!this._interactionsEnabled) {
  90851. this._interactionsRequested = true;
  90852. if (this.leftController) {
  90853. this._enableInteractionOnController(this.leftController);
  90854. }
  90855. if (this.rightController) {
  90856. this._enableInteractionOnController(this.rightController);
  90857. }
  90858. this.raySelectionPredicate = function (mesh) {
  90859. return mesh.isVisible;
  90860. };
  90861. this.meshSelectionPredicate = function (mesh) {
  90862. return true;
  90863. };
  90864. this._raySelectionPredicate = function (mesh) {
  90865. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90866. && mesh.name.indexOf("teleportationTarget") === -1
  90867. && mesh.name.indexOf("torusTeleportation") === -1
  90868. && mesh.name.indexOf("laserPointer") === -1)) {
  90869. return _this.raySelectionPredicate(mesh);
  90870. }
  90871. return false;
  90872. };
  90873. this._interactionsEnabled = true;
  90874. }
  90875. };
  90876. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90877. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90878. if (this._floorMeshesCollection[i].id === mesh.id) {
  90879. return true;
  90880. }
  90881. }
  90882. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90883. return true;
  90884. }
  90885. return false;
  90886. };
  90887. /**
  90888. * Adds a floor mesh to be used for teleportation.
  90889. * @param floorMesh the mesh to be used for teleportation.
  90890. */
  90891. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90892. if (!this._floorMeshesCollection) {
  90893. return;
  90894. }
  90895. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90896. return;
  90897. }
  90898. this._floorMeshesCollection.push(floorMesh);
  90899. };
  90900. /**
  90901. * Removes a floor mesh from being used for teleportation.
  90902. * @param floorMesh the mesh to be removed.
  90903. */
  90904. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90905. if (!this._floorMeshesCollection) {
  90906. return;
  90907. }
  90908. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90909. if (meshIndex !== -1) {
  90910. this._floorMeshesCollection.splice(meshIndex, 1);
  90911. }
  90912. };
  90913. /**
  90914. * Enables interactions and teleportation using the VR controllers and gaze.
  90915. * @param vrTeleportationOptions options to modify teleportation behavior.
  90916. */
  90917. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90918. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90919. if (!this._teleportationInitialized) {
  90920. this._teleportationRequested = true;
  90921. this.enableInteractions();
  90922. if (vrTeleportationOptions.floorMeshName) {
  90923. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90924. }
  90925. if (vrTeleportationOptions.floorMeshes) {
  90926. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90927. }
  90928. if (this.leftController != null) {
  90929. this._enableTeleportationOnController(this.leftController);
  90930. }
  90931. if (this.rightController != null) {
  90932. this._enableTeleportationOnController(this.rightController);
  90933. }
  90934. // Creates an image processing post process for the vignette not relying
  90935. // on the main scene configuration for image processing to reduce setup and spaces
  90936. // (gamma/linear) conflicts.
  90937. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90938. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90939. imageProcessingConfiguration.vignetteEnabled = true;
  90940. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90941. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90942. this._teleportationInitialized = true;
  90943. if (this._isDefaultTeleportationTarget) {
  90944. this._createTeleportationCircles();
  90945. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90946. }
  90947. }
  90948. };
  90949. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90950. var _this = this;
  90951. var controllerMesh = controller.webVRController.mesh;
  90952. if (controllerMesh) {
  90953. controller._interactionsEnabled = true;
  90954. controller._activatePointer();
  90955. if (this.webVROptions.laserToggle) {
  90956. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90957. // Enabling / disabling laserPointer
  90958. if (_this._displayLaserPointer && stateObject.value === 1) {
  90959. if (controller._activePointer) {
  90960. controller._deactivatePointer();
  90961. }
  90962. else {
  90963. controller._activatePointer();
  90964. }
  90965. if (_this.displayGaze) {
  90966. controller._gazeTracker.isVisible = controller._activePointer;
  90967. }
  90968. }
  90969. });
  90970. }
  90971. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90972. if (!controller._pointerDownOnMeshAsked) {
  90973. if (stateObject.value > _this._padSensibilityUp) {
  90974. controller._selectionPointerDown();
  90975. }
  90976. }
  90977. else if (stateObject.value < _this._padSensibilityDown) {
  90978. controller._selectionPointerUp();
  90979. }
  90980. });
  90981. }
  90982. };
  90983. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90984. // Dont teleport if another gaze already requested teleportation
  90985. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90986. return;
  90987. }
  90988. if (!gazer._teleportationRequestInitiated) {
  90989. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90990. gazer._activatePointer();
  90991. gazer._teleportationRequestInitiated = true;
  90992. }
  90993. }
  90994. else {
  90995. // Listening to the proper controller values changes to confirm teleportation
  90996. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90997. if (this._teleportActive) {
  90998. this._teleportCamera(this._haloCenter);
  90999. }
  91000. gazer._teleportationRequestInitiated = false;
  91001. }
  91002. }
  91003. };
  91004. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91005. // Only rotate when user is not currently selecting a teleportation location
  91006. if (gazer._teleportationRequestInitiated) {
  91007. return;
  91008. }
  91009. if (!gazer._rotationLeftAsked) {
  91010. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91011. gazer._rotationLeftAsked = true;
  91012. if (this._rotationAllowed) {
  91013. this._rotateCamera(false);
  91014. }
  91015. }
  91016. }
  91017. else {
  91018. if (stateObject.x > -this._padSensibilityDown) {
  91019. gazer._rotationLeftAsked = false;
  91020. }
  91021. }
  91022. if (!gazer._rotationRightAsked) {
  91023. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91024. gazer._rotationRightAsked = true;
  91025. if (this._rotationAllowed) {
  91026. this._rotateCamera(true);
  91027. }
  91028. }
  91029. }
  91030. else {
  91031. if (stateObject.x < this._padSensibilityDown) {
  91032. gazer._rotationRightAsked = false;
  91033. }
  91034. }
  91035. };
  91036. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91037. // Only teleport backwards when user is not currently selecting a teleportation location
  91038. if (gazer._teleportationRequestInitiated) {
  91039. return;
  91040. }
  91041. // Teleport backwards
  91042. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91043. if (!gazer._teleportationBackRequestInitiated) {
  91044. if (!this.currentVRCamera) {
  91045. return;
  91046. }
  91047. // Get rotation and position of the current camera
  91048. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91049. var position = this.currentVRCamera.position;
  91050. // If the camera has device position, use that instead
  91051. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91052. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91053. position = this.currentVRCamera.devicePosition;
  91054. }
  91055. // Get matrix with only the y rotation of the device rotation
  91056. rotation.toEulerAnglesToRef(this._workingVector);
  91057. this._workingVector.z = 0;
  91058. this._workingVector.x = 0;
  91059. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91060. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91061. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91062. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91063. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91064. var ray = new BABYLON.Ray(position, this._workingVector);
  91065. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91066. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91067. this._teleportCamera(hit.pickedPoint);
  91068. }
  91069. gazer._teleportationBackRequestInitiated = true;
  91070. }
  91071. }
  91072. else {
  91073. gazer._teleportationBackRequestInitiated = false;
  91074. }
  91075. };
  91076. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91077. var _this = this;
  91078. var controllerMesh = controller.webVRController.mesh;
  91079. if (controllerMesh) {
  91080. if (!controller._interactionsEnabled) {
  91081. this._enableInteractionOnController(controller);
  91082. }
  91083. controller._interactionsEnabled = true;
  91084. controller._teleportationEnabled = true;
  91085. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91086. controller._dpadPressed = false;
  91087. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91088. controller._dpadPressed = stateObject.pressed;
  91089. if (!controller._dpadPressed) {
  91090. controller._rotationLeftAsked = false;
  91091. controller._rotationRightAsked = false;
  91092. controller._teleportationBackRequestInitiated = false;
  91093. }
  91094. });
  91095. }
  91096. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91097. if (_this.teleportationEnabled) {
  91098. _this._checkTeleportBackwards(stateObject, controller);
  91099. _this._checkTeleportWithRay(stateObject, controller);
  91100. }
  91101. _this._checkRotate(stateObject, controller);
  91102. });
  91103. }
  91104. };
  91105. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  91106. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  91107. this._teleportationTarget.isPickable = false;
  91108. var length = 512;
  91109. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  91110. dynamicTexture.hasAlpha = true;
  91111. var context = dynamicTexture.getContext();
  91112. var centerX = length / 2;
  91113. var centerY = length / 2;
  91114. var radius = 200;
  91115. context.beginPath();
  91116. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  91117. context.fillStyle = this._teleportationFillColor;
  91118. context.fill();
  91119. context.lineWidth = 10;
  91120. context.strokeStyle = this._teleportationBorderColor;
  91121. context.stroke();
  91122. context.closePath();
  91123. dynamicTexture.update();
  91124. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  91125. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  91126. this._teleportationTarget.material = teleportationCircleMaterial;
  91127. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  91128. torus.isPickable = false;
  91129. torus.parent = this._teleportationTarget;
  91130. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91131. var keys = [];
  91132. keys.push({
  91133. frame: 0,
  91134. value: 0
  91135. });
  91136. keys.push({
  91137. frame: 30,
  91138. value: 0.4
  91139. });
  91140. keys.push({
  91141. frame: 60,
  91142. value: 0
  91143. });
  91144. animationInnerCircle.setKeys(keys);
  91145. var easingFunction = new BABYLON.SineEase();
  91146. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91147. animationInnerCircle.setEasingFunction(easingFunction);
  91148. torus.animations = [];
  91149. torus.animations.push(animationInnerCircle);
  91150. this._scene.beginAnimation(torus, 0, 60, true);
  91151. this._hideTeleportationTarget();
  91152. };
  91153. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  91154. this._teleportActive = true;
  91155. if (this._teleportationInitialized) {
  91156. this._teleportationTarget.isVisible = true;
  91157. if (this._isDefaultTeleportationTarget) {
  91158. this._teleportationTarget.getChildren()[0].isVisible = true;
  91159. }
  91160. }
  91161. };
  91162. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  91163. this._teleportActive = false;
  91164. if (this._teleportationInitialized) {
  91165. this._teleportationTarget.isVisible = false;
  91166. if (this._isDefaultTeleportationTarget) {
  91167. this._teleportationTarget.getChildren()[0].isVisible = false;
  91168. }
  91169. }
  91170. };
  91171. VRExperienceHelper.prototype._rotateCamera = function (right) {
  91172. var _this = this;
  91173. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91174. return;
  91175. }
  91176. if (right) {
  91177. this._rotationAngle++;
  91178. }
  91179. else {
  91180. this._rotationAngle--;
  91181. }
  91182. this.currentVRCamera.animations = [];
  91183. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  91184. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91185. var animationRotationKeys = [];
  91186. animationRotationKeys.push({
  91187. frame: 0,
  91188. value: this.currentVRCamera.rotationQuaternion
  91189. });
  91190. animationRotationKeys.push({
  91191. frame: 6,
  91192. value: target
  91193. });
  91194. animationRotation.setKeys(animationRotationKeys);
  91195. animationRotation.setEasingFunction(this._circleEase);
  91196. this.currentVRCamera.animations.push(animationRotation);
  91197. this._postProcessMove.animations = [];
  91198. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91199. var vignetteWeightKeys = [];
  91200. vignetteWeightKeys.push({
  91201. frame: 0,
  91202. value: 0
  91203. });
  91204. vignetteWeightKeys.push({
  91205. frame: 3,
  91206. value: 4
  91207. });
  91208. vignetteWeightKeys.push({
  91209. frame: 6,
  91210. value: 0
  91211. });
  91212. animationPP.setKeys(vignetteWeightKeys);
  91213. animationPP.setEasingFunction(this._circleEase);
  91214. this._postProcessMove.animations.push(animationPP);
  91215. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91216. var vignetteStretchKeys = [];
  91217. vignetteStretchKeys.push({
  91218. frame: 0,
  91219. value: 0
  91220. });
  91221. vignetteStretchKeys.push({
  91222. frame: 3,
  91223. value: 10
  91224. });
  91225. vignetteStretchKeys.push({
  91226. frame: 6,
  91227. value: 0
  91228. });
  91229. animationPP2.setKeys(vignetteStretchKeys);
  91230. animationPP2.setEasingFunction(this._circleEase);
  91231. this._postProcessMove.animations.push(animationPP2);
  91232. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91233. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91234. this._postProcessMove.samples = 4;
  91235. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91236. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91237. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91238. });
  91239. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91240. };
  91241. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91242. if (hit.pickedPoint) {
  91243. if (gazer._teleportationRequestInitiated) {
  91244. this._displayTeleportationTarget();
  91245. this._haloCenter.copyFrom(hit.pickedPoint);
  91246. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91247. }
  91248. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91249. if (pickNormal) {
  91250. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91251. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91252. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91253. }
  91254. this._teleportationTarget.position.y += 0.1;
  91255. }
  91256. };
  91257. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91258. var _this = this;
  91259. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91260. return;
  91261. }
  91262. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91263. // offset of the headset from the anchor.
  91264. if (this.webVRCamera.leftCamera) {
  91265. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91266. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91267. location.subtractToRef(this._workingVector, this._workingVector);
  91268. }
  91269. else {
  91270. this._workingVector.copyFrom(location);
  91271. }
  91272. // Add height to account for user's height offset
  91273. if (this.isInVRMode) {
  91274. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  91275. }
  91276. else {
  91277. this._workingVector.y += this._defaultHeight;
  91278. }
  91279. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91280. // Create animation from the camera's position to the new location
  91281. this.currentVRCamera.animations = [];
  91282. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91283. var animationCameraTeleportationKeys = [{
  91284. frame: 0,
  91285. value: this.currentVRCamera.position
  91286. },
  91287. {
  91288. frame: 11,
  91289. value: this._workingVector
  91290. }
  91291. ];
  91292. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91293. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91294. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91295. this._postProcessMove.animations = [];
  91296. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91297. var vignetteWeightKeys = [];
  91298. vignetteWeightKeys.push({
  91299. frame: 0,
  91300. value: 0
  91301. });
  91302. vignetteWeightKeys.push({
  91303. frame: 5,
  91304. value: 8
  91305. });
  91306. vignetteWeightKeys.push({
  91307. frame: 11,
  91308. value: 0
  91309. });
  91310. animationPP.setKeys(vignetteWeightKeys);
  91311. this._postProcessMove.animations.push(animationPP);
  91312. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91313. var vignetteStretchKeys = [];
  91314. vignetteStretchKeys.push({
  91315. frame: 0,
  91316. value: 0
  91317. });
  91318. vignetteStretchKeys.push({
  91319. frame: 5,
  91320. value: 10
  91321. });
  91322. vignetteStretchKeys.push({
  91323. frame: 11,
  91324. value: 0
  91325. });
  91326. animationPP2.setKeys(vignetteStretchKeys);
  91327. this._postProcessMove.animations.push(animationPP2);
  91328. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91329. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91330. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91331. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91332. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91333. });
  91334. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91335. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91336. });
  91337. this._hideTeleportationTarget();
  91338. };
  91339. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91340. if (normal) {
  91341. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91342. if (angle < Math.PI / 2) {
  91343. normal.scaleInPlace(-1);
  91344. }
  91345. }
  91346. return normal;
  91347. };
  91348. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91349. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91350. return;
  91351. }
  91352. var ray = gazer._getForwardRay(this._rayLength);
  91353. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91354. if (hit) {
  91355. // Populate the contrllers mesh that can be used for drag/drop
  91356. if (gazer._laserPointer) {
  91357. hit.originMesh = gazer._laserPointer.parent;
  91358. }
  91359. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91360. }
  91361. gazer._currentHit = hit;
  91362. // Moving the gazeTracker on the mesh face targetted
  91363. if (hit && hit.pickedPoint) {
  91364. if (this._displayGaze) {
  91365. var multiplier = 1;
  91366. gazer._gazeTracker.isVisible = true;
  91367. if (gazer._isActionableMesh) {
  91368. multiplier = 3;
  91369. }
  91370. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91371. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91372. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91373. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91374. // To avoid z-fighting
  91375. var deltaFighting = 0.002;
  91376. if (pickNormal) {
  91377. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91378. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91379. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91380. }
  91381. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91382. if (gazer._gazeTracker.position.x < 0) {
  91383. gazer._gazeTracker.position.x += deltaFighting;
  91384. }
  91385. else {
  91386. gazer._gazeTracker.position.x -= deltaFighting;
  91387. }
  91388. if (gazer._gazeTracker.position.y < 0) {
  91389. gazer._gazeTracker.position.y += deltaFighting;
  91390. }
  91391. else {
  91392. gazer._gazeTracker.position.y -= deltaFighting;
  91393. }
  91394. if (gazer._gazeTracker.position.z < 0) {
  91395. gazer._gazeTracker.position.z += deltaFighting;
  91396. }
  91397. else {
  91398. gazer._gazeTracker.position.z -= deltaFighting;
  91399. }
  91400. }
  91401. // Changing the size of the laser pointer based on the distance from the targetted point
  91402. gazer._updatePointerDistance(hit.distance);
  91403. }
  91404. else {
  91405. gazer._updatePointerDistance();
  91406. gazer._gazeTracker.isVisible = false;
  91407. }
  91408. if (hit && hit.pickedMesh) {
  91409. // The object selected is the floor, we're in a teleportation scenario
  91410. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91411. // Moving the teleportation area to this targetted point
  91412. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91413. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91414. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91415. }
  91416. gazer._currentMeshSelected = null;
  91417. if (gazer._teleportationRequestInitiated) {
  91418. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91419. }
  91420. return;
  91421. }
  91422. // If not, we're in a selection scenario
  91423. //this._teleportationAllowed = false;
  91424. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91425. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91426. this.onNewMeshPicked.notifyObservers(hit);
  91427. gazer._currentMeshSelected = hit.pickedMesh;
  91428. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91429. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91430. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91431. gazer._isActionableMesh = true;
  91432. }
  91433. else {
  91434. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91435. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91436. gazer._isActionableMesh = false;
  91437. }
  91438. try {
  91439. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91440. }
  91441. catch (err) {
  91442. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91443. }
  91444. }
  91445. else {
  91446. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91447. gazer._currentMeshSelected = null;
  91448. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91449. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91450. }
  91451. }
  91452. }
  91453. else {
  91454. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91455. gazer._currentMeshSelected = null;
  91456. //this._teleportationAllowed = false;
  91457. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91458. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91459. }
  91460. };
  91461. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91462. if (mesh) {
  91463. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91464. }
  91465. };
  91466. /**
  91467. * Sets the color of the laser ray from the vr controllers.
  91468. * @param color new color for the ray.
  91469. */
  91470. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91471. if (this.leftController) {
  91472. this.leftController._setLaserPointerColor(color);
  91473. }
  91474. if (this.rightController) {
  91475. this.rightController._setLaserPointerColor(color);
  91476. }
  91477. };
  91478. /**
  91479. * Sets the color of the ray from the vr headsets gaze.
  91480. * @param color new color for the ray.
  91481. */
  91482. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91483. if (!this._cameraGazer._gazeTracker.material) {
  91484. return;
  91485. }
  91486. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91487. if (this.leftController) {
  91488. this.leftController._gazeTracker.material.emissiveColor = color;
  91489. }
  91490. if (this.rightController) {
  91491. this.rightController._gazeTracker.material.emissiveColor = color;
  91492. }
  91493. };
  91494. /**
  91495. * Exits VR and disposes of the vr experience helper
  91496. */
  91497. VRExperienceHelper.prototype.dispose = function () {
  91498. if (this.isInVRMode) {
  91499. this.exitVR();
  91500. }
  91501. if (this._postProcessMove) {
  91502. this._postProcessMove.dispose();
  91503. }
  91504. if (this._webVRCamera) {
  91505. this._webVRCamera.dispose();
  91506. }
  91507. if (this._vrDeviceOrientationCamera) {
  91508. this._vrDeviceOrientationCamera.dispose();
  91509. }
  91510. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91511. document.body.removeChild(this._btnVR);
  91512. }
  91513. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91514. this._deviceOrientationCamera.dispose();
  91515. }
  91516. if (this._cameraGazer) {
  91517. this._cameraGazer.dispose();
  91518. }
  91519. if (this.leftController) {
  91520. this.leftController.dispose();
  91521. }
  91522. if (this.rightController) {
  91523. this.rightController.dispose();
  91524. }
  91525. if (this._teleportationTarget) {
  91526. this._teleportationTarget.dispose();
  91527. }
  91528. this._floorMeshesCollection = [];
  91529. document.removeEventListener("keydown", this._onKeyDown);
  91530. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91531. window.removeEventListener("resize", this._onResize);
  91532. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91533. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91534. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91535. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91536. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91537. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91538. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91539. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91540. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91541. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91542. this._scene.unregisterBeforeRender(this.beforeRender);
  91543. };
  91544. /**
  91545. * Gets the name of the VRExperienceHelper class
  91546. * @returns "VRExperienceHelper"
  91547. */
  91548. VRExperienceHelper.prototype.getClassName = function () {
  91549. return "VRExperienceHelper";
  91550. };
  91551. return VRExperienceHelper;
  91552. }());
  91553. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91554. })(BABYLON || (BABYLON = {}));
  91555. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91556. // Mainly based on these 2 articles :
  91557. // 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
  91558. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91559. var BABYLON;
  91560. (function (BABYLON) {
  91561. /**
  91562. * Defines the potential axis of a Joystick
  91563. */
  91564. var JoystickAxis;
  91565. (function (JoystickAxis) {
  91566. /** X axis */
  91567. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91568. /** Y axis */
  91569. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91570. /** Z axis */
  91571. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91572. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91573. /**
  91574. * Class used to define virtual joystick (used in touch mode)
  91575. */
  91576. var VirtualJoystick = /** @class */ (function () {
  91577. /**
  91578. * Creates a new virtual joystick
  91579. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91580. */
  91581. function VirtualJoystick(leftJoystick) {
  91582. var _this = this;
  91583. if (leftJoystick) {
  91584. this._leftJoystick = true;
  91585. }
  91586. else {
  91587. this._leftJoystick = false;
  91588. }
  91589. VirtualJoystick._globalJoystickIndex++;
  91590. // By default left & right arrow keys are moving the X
  91591. // and up & down keys are moving the Y
  91592. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91593. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91594. this.reverseLeftRight = false;
  91595. this.reverseUpDown = false;
  91596. // collections of pointers
  91597. this._touches = new BABYLON.StringDictionary();
  91598. this.deltaPosition = BABYLON.Vector3.Zero();
  91599. this._joystickSensibility = 25;
  91600. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91601. this._onResize = function (evt) {
  91602. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91603. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91604. if (VirtualJoystick.vjCanvas) {
  91605. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91606. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91607. }
  91608. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91609. };
  91610. // injecting a canvas element on top of the canvas 3D game
  91611. if (!VirtualJoystick.vjCanvas) {
  91612. window.addEventListener("resize", this._onResize, false);
  91613. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91614. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91615. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91616. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91617. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91618. VirtualJoystick.vjCanvas.style.width = "100%";
  91619. VirtualJoystick.vjCanvas.style.height = "100%";
  91620. VirtualJoystick.vjCanvas.style.position = "absolute";
  91621. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91622. VirtualJoystick.vjCanvas.style.top = "0px";
  91623. VirtualJoystick.vjCanvas.style.left = "0px";
  91624. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91625. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91626. // Support for jQuery PEP polyfill
  91627. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91628. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91629. if (!context) {
  91630. throw new Error("Unable to create canvas for virtual joystick");
  91631. }
  91632. VirtualJoystick.vjCanvasContext = context;
  91633. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91634. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91635. document.body.appendChild(VirtualJoystick.vjCanvas);
  91636. }
  91637. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91638. this.pressed = false;
  91639. // default joystick color
  91640. this._joystickColor = "cyan";
  91641. this._joystickPointerID = -1;
  91642. // current joystick position
  91643. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91644. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91645. // origin joystick position
  91646. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91647. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91648. this._onPointerDownHandlerRef = function (evt) {
  91649. _this._onPointerDown(evt);
  91650. };
  91651. this._onPointerMoveHandlerRef = function (evt) {
  91652. _this._onPointerMove(evt);
  91653. };
  91654. this._onPointerUpHandlerRef = function (evt) {
  91655. _this._onPointerUp(evt);
  91656. };
  91657. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91658. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91659. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91660. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91661. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91662. evt.preventDefault(); // Disables system menu
  91663. }, false);
  91664. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91665. }
  91666. /**
  91667. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91668. * @param newJoystickSensibility defines the new sensibility
  91669. */
  91670. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91671. this._joystickSensibility = newJoystickSensibility;
  91672. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91673. };
  91674. VirtualJoystick.prototype._onPointerDown = function (e) {
  91675. var positionOnScreenCondition;
  91676. e.preventDefault();
  91677. if (this._leftJoystick === true) {
  91678. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91679. }
  91680. else {
  91681. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91682. }
  91683. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91684. // First contact will be dedicated to the virtual joystick
  91685. this._joystickPointerID = e.pointerId;
  91686. this._joystickPointerStartPos.x = e.clientX;
  91687. this._joystickPointerStartPos.y = e.clientY;
  91688. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91689. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91690. this._deltaJoystickVector.x = 0;
  91691. this._deltaJoystickVector.y = 0;
  91692. this.pressed = true;
  91693. this._touches.add(e.pointerId.toString(), e);
  91694. }
  91695. else {
  91696. // You can only trigger the action buttons with a joystick declared
  91697. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91698. this._action();
  91699. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91700. }
  91701. }
  91702. };
  91703. VirtualJoystick.prototype._onPointerMove = function (e) {
  91704. // If the current pointer is the one associated to the joystick (first touch contact)
  91705. if (this._joystickPointerID == e.pointerId) {
  91706. this._joystickPointerPos.x = e.clientX;
  91707. this._joystickPointerPos.y = e.clientY;
  91708. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91709. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91710. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91711. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91712. switch (this._axisTargetedByLeftAndRight) {
  91713. case JoystickAxis.X:
  91714. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91715. break;
  91716. case JoystickAxis.Y:
  91717. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91718. break;
  91719. case JoystickAxis.Z:
  91720. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91721. break;
  91722. }
  91723. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91724. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91725. switch (this._axisTargetedByUpAndDown) {
  91726. case JoystickAxis.X:
  91727. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91728. break;
  91729. case JoystickAxis.Y:
  91730. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91731. break;
  91732. case JoystickAxis.Z:
  91733. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91734. break;
  91735. }
  91736. }
  91737. else {
  91738. var data = this._touches.get(e.pointerId.toString());
  91739. if (data) {
  91740. data.x = e.clientX;
  91741. data.y = e.clientY;
  91742. }
  91743. }
  91744. };
  91745. VirtualJoystick.prototype._onPointerUp = function (e) {
  91746. if (this._joystickPointerID == e.pointerId) {
  91747. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91748. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91749. this._joystickPointerID = -1;
  91750. this.pressed = false;
  91751. }
  91752. else {
  91753. var touch = this._touches.get(e.pointerId.toString());
  91754. if (touch) {
  91755. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91756. }
  91757. }
  91758. this._deltaJoystickVector.x = 0;
  91759. this._deltaJoystickVector.y = 0;
  91760. this._touches.remove(e.pointerId.toString());
  91761. };
  91762. /**
  91763. * Change the color of the virtual joystick
  91764. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91765. */
  91766. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91767. this._joystickColor = newColor;
  91768. };
  91769. /**
  91770. * Defines a callback to call when the joystick is touched
  91771. * @param action defines the callback
  91772. */
  91773. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91774. this._action = action;
  91775. };
  91776. /**
  91777. * Defines which axis you'd like to control for left & right
  91778. * @param axis defines the axis to use
  91779. */
  91780. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91781. switch (axis) {
  91782. case JoystickAxis.X:
  91783. case JoystickAxis.Y:
  91784. case JoystickAxis.Z:
  91785. this._axisTargetedByLeftAndRight = axis;
  91786. break;
  91787. default:
  91788. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91789. break;
  91790. }
  91791. };
  91792. /**
  91793. * Defines which axis you'd like to control for up & down
  91794. * @param axis defines the axis to use
  91795. */
  91796. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91797. switch (axis) {
  91798. case JoystickAxis.X:
  91799. case JoystickAxis.Y:
  91800. case JoystickAxis.Z:
  91801. this._axisTargetedByUpAndDown = axis;
  91802. break;
  91803. default:
  91804. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91805. break;
  91806. }
  91807. };
  91808. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91809. var _this = this;
  91810. if (this.pressed) {
  91811. this._touches.forEach(function (key, touch) {
  91812. if (touch.pointerId === _this._joystickPointerID) {
  91813. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91814. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91815. VirtualJoystick.vjCanvasContext.beginPath();
  91816. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91817. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91818. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91819. VirtualJoystick.vjCanvasContext.stroke();
  91820. VirtualJoystick.vjCanvasContext.closePath();
  91821. VirtualJoystick.vjCanvasContext.beginPath();
  91822. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91823. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91824. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91825. VirtualJoystick.vjCanvasContext.stroke();
  91826. VirtualJoystick.vjCanvasContext.closePath();
  91827. VirtualJoystick.vjCanvasContext.beginPath();
  91828. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91829. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91830. VirtualJoystick.vjCanvasContext.stroke();
  91831. VirtualJoystick.vjCanvasContext.closePath();
  91832. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91833. }
  91834. else {
  91835. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91836. VirtualJoystick.vjCanvasContext.beginPath();
  91837. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91838. VirtualJoystick.vjCanvasContext.beginPath();
  91839. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91840. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91841. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91842. VirtualJoystick.vjCanvasContext.stroke();
  91843. VirtualJoystick.vjCanvasContext.closePath();
  91844. touch.prevX = touch.x;
  91845. touch.prevY = touch.y;
  91846. }
  91847. ;
  91848. });
  91849. }
  91850. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91851. };
  91852. /**
  91853. * Release internal HTML canvas
  91854. */
  91855. VirtualJoystick.prototype.releaseCanvas = function () {
  91856. if (VirtualJoystick.vjCanvas) {
  91857. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91858. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91859. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91860. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91861. window.removeEventListener("resize", this._onResize);
  91862. document.body.removeChild(VirtualJoystick.vjCanvas);
  91863. VirtualJoystick.vjCanvas = null;
  91864. }
  91865. };
  91866. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91867. VirtualJoystick._globalJoystickIndex = 0;
  91868. return VirtualJoystick;
  91869. }());
  91870. BABYLON.VirtualJoystick = VirtualJoystick;
  91871. })(BABYLON || (BABYLON = {}));
  91872. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91873. var BABYLON;
  91874. (function (BABYLON) {
  91875. // We're mainly based on the logic defined into the FreeCamera code
  91876. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91877. __extends(VirtualJoysticksCamera, _super);
  91878. function VirtualJoysticksCamera(name, position, scene) {
  91879. var _this = _super.call(this, name, position, scene) || this;
  91880. _this.inputs.addVirtualJoystick();
  91881. return _this;
  91882. }
  91883. VirtualJoysticksCamera.prototype.getClassName = function () {
  91884. return "VirtualJoysticksCamera";
  91885. };
  91886. return VirtualJoysticksCamera;
  91887. }(BABYLON.FreeCamera));
  91888. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91889. })(BABYLON || (BABYLON = {}));
  91890. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91891. var BABYLON;
  91892. (function (BABYLON) {
  91893. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91894. function FreeCameraVirtualJoystickInput() {
  91895. }
  91896. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91897. return this._leftjoystick;
  91898. };
  91899. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91900. return this._rightjoystick;
  91901. };
  91902. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91903. if (this._leftjoystick) {
  91904. var camera = this.camera;
  91905. var speed = camera._computeLocalCameraSpeed() * 50;
  91906. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91907. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91908. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91909. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91910. if (!this._leftjoystick.pressed) {
  91911. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91912. }
  91913. if (!this._rightjoystick.pressed) {
  91914. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91915. }
  91916. }
  91917. };
  91918. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91919. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91920. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91921. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91922. this._leftjoystick.setJoystickSensibility(0.15);
  91923. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91924. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91925. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91926. this._rightjoystick.reverseUpDown = true;
  91927. this._rightjoystick.setJoystickSensibility(0.05);
  91928. this._rightjoystick.setJoystickColor("yellow");
  91929. };
  91930. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91931. this._leftjoystick.releaseCanvas();
  91932. this._rightjoystick.releaseCanvas();
  91933. };
  91934. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91935. return "FreeCameraVirtualJoystickInput";
  91936. };
  91937. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91938. return "virtualJoystick";
  91939. };
  91940. return FreeCameraVirtualJoystickInput;
  91941. }());
  91942. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91943. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91944. })(BABYLON || (BABYLON = {}));
  91945. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91946. var BABYLON;
  91947. (function (BABYLON) {
  91948. var SimplificationSettings = /** @class */ (function () {
  91949. function SimplificationSettings(quality, distance, optimizeMesh) {
  91950. this.quality = quality;
  91951. this.distance = distance;
  91952. this.optimizeMesh = optimizeMesh;
  91953. }
  91954. return SimplificationSettings;
  91955. }());
  91956. BABYLON.SimplificationSettings = SimplificationSettings;
  91957. var SimplificationQueue = /** @class */ (function () {
  91958. function SimplificationQueue() {
  91959. this.running = false;
  91960. this._simplificationArray = [];
  91961. }
  91962. SimplificationQueue.prototype.addTask = function (task) {
  91963. this._simplificationArray.push(task);
  91964. };
  91965. SimplificationQueue.prototype.executeNext = function () {
  91966. var task = this._simplificationArray.pop();
  91967. if (task) {
  91968. this.running = true;
  91969. this.runSimplification(task);
  91970. }
  91971. else {
  91972. this.running = false;
  91973. }
  91974. };
  91975. SimplificationQueue.prototype.runSimplification = function (task) {
  91976. var _this = this;
  91977. if (task.parallelProcessing) {
  91978. //parallel simplifier
  91979. task.settings.forEach(function (setting) {
  91980. var simplifier = _this.getSimplifier(task);
  91981. simplifier.simplify(setting, function (newMesh) {
  91982. task.mesh.addLODLevel(setting.distance, newMesh);
  91983. newMesh.isVisible = true;
  91984. //check if it is the last
  91985. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91986. //all done, run the success callback.
  91987. task.successCallback();
  91988. }
  91989. _this.executeNext();
  91990. });
  91991. });
  91992. }
  91993. else {
  91994. //single simplifier.
  91995. var simplifier = this.getSimplifier(task);
  91996. var runDecimation = function (setting, callback) {
  91997. simplifier.simplify(setting, function (newMesh) {
  91998. task.mesh.addLODLevel(setting.distance, newMesh);
  91999. newMesh.isVisible = true;
  92000. //run the next quality level
  92001. callback();
  92002. });
  92003. };
  92004. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92005. runDecimation(task.settings[loop.index], function () {
  92006. loop.executeNext();
  92007. });
  92008. }, function () {
  92009. //execution ended, run the success callback.
  92010. if (task.successCallback) {
  92011. task.successCallback();
  92012. }
  92013. _this.executeNext();
  92014. });
  92015. }
  92016. };
  92017. SimplificationQueue.prototype.getSimplifier = function (task) {
  92018. switch (task.simplificationType) {
  92019. case SimplificationType.QUADRATIC:
  92020. default:
  92021. return new QuadraticErrorSimplification(task.mesh);
  92022. }
  92023. };
  92024. return SimplificationQueue;
  92025. }());
  92026. BABYLON.SimplificationQueue = SimplificationQueue;
  92027. /**
  92028. * The implemented types of simplification
  92029. * At the moment only Quadratic Error Decimation is implemented
  92030. */
  92031. var SimplificationType;
  92032. (function (SimplificationType) {
  92033. /** Quadratic error decimation */
  92034. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92035. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92036. var DecimationTriangle = /** @class */ (function () {
  92037. function DecimationTriangle(vertices) {
  92038. this.vertices = vertices;
  92039. this.error = new Array(4);
  92040. this.deleted = false;
  92041. this.isDirty = false;
  92042. this.deletePending = false;
  92043. this.borderFactor = 0;
  92044. }
  92045. return DecimationTriangle;
  92046. }());
  92047. BABYLON.DecimationTriangle = DecimationTriangle;
  92048. var DecimationVertex = /** @class */ (function () {
  92049. function DecimationVertex(position, id) {
  92050. this.position = position;
  92051. this.id = id;
  92052. this.isBorder = true;
  92053. this.q = new QuadraticMatrix();
  92054. this.triangleCount = 0;
  92055. this.triangleStart = 0;
  92056. this.originalOffsets = [];
  92057. }
  92058. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92059. this.position.copyFrom(newPosition);
  92060. };
  92061. return DecimationVertex;
  92062. }());
  92063. BABYLON.DecimationVertex = DecimationVertex;
  92064. var QuadraticMatrix = /** @class */ (function () {
  92065. function QuadraticMatrix(data) {
  92066. this.data = new Array(10);
  92067. for (var i = 0; i < 10; ++i) {
  92068. if (data && data[i]) {
  92069. this.data[i] = data[i];
  92070. }
  92071. else {
  92072. this.data[i] = 0;
  92073. }
  92074. }
  92075. }
  92076. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92077. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92078. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92079. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92080. return det;
  92081. };
  92082. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92083. for (var i = 0; i < 10; ++i) {
  92084. this.data[i] += matrix.data[i];
  92085. }
  92086. };
  92087. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92088. for (var i = 0; i < 10; ++i) {
  92089. this.data[i] += data[i];
  92090. }
  92091. };
  92092. QuadraticMatrix.prototype.add = function (matrix) {
  92093. var m = new QuadraticMatrix();
  92094. for (var i = 0; i < 10; ++i) {
  92095. m.data[i] = this.data[i] + matrix.data[i];
  92096. }
  92097. return m;
  92098. };
  92099. QuadraticMatrix.FromData = function (a, b, c, d) {
  92100. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  92101. };
  92102. //returning an array to avoid garbage collection
  92103. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  92104. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  92105. };
  92106. return QuadraticMatrix;
  92107. }());
  92108. BABYLON.QuadraticMatrix = QuadraticMatrix;
  92109. var Reference = /** @class */ (function () {
  92110. function Reference(vertexId, triangleId) {
  92111. this.vertexId = vertexId;
  92112. this.triangleId = triangleId;
  92113. }
  92114. return Reference;
  92115. }());
  92116. BABYLON.Reference = Reference;
  92117. /**
  92118. * An implementation of the Quadratic Error simplification algorithm.
  92119. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  92120. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  92121. * @author RaananW
  92122. */
  92123. var QuadraticErrorSimplification = /** @class */ (function () {
  92124. function QuadraticErrorSimplification(_mesh) {
  92125. this._mesh = _mesh;
  92126. this.syncIterations = 5000;
  92127. this.aggressiveness = 7;
  92128. this.decimationIterations = 100;
  92129. this.boundingBoxEpsilon = BABYLON.Epsilon;
  92130. }
  92131. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  92132. var _this = this;
  92133. this.initDecimatedMesh();
  92134. //iterating through the submeshes array, one after the other.
  92135. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  92136. _this.initWithMesh(loop.index, function () {
  92137. _this.runDecimation(settings, loop.index, function () {
  92138. loop.executeNext();
  92139. });
  92140. }, settings.optimizeMesh);
  92141. }, function () {
  92142. setTimeout(function () {
  92143. successCallback(_this._reconstructedMesh);
  92144. }, 0);
  92145. });
  92146. };
  92147. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  92148. var _this = this;
  92149. var targetCount = ~~(this.triangles.length * settings.quality);
  92150. var deletedTriangles = 0;
  92151. var triangleCount = this.triangles.length;
  92152. var iterationFunction = function (iteration, callback) {
  92153. setTimeout(function () {
  92154. if (iteration % 5 === 0) {
  92155. _this.updateMesh(iteration === 0);
  92156. }
  92157. for (var i = 0; i < _this.triangles.length; ++i) {
  92158. _this.triangles[i].isDirty = false;
  92159. }
  92160. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  92161. var trianglesIterator = function (i) {
  92162. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  92163. var t = _this.triangles[tIdx];
  92164. if (!t)
  92165. return;
  92166. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  92167. return;
  92168. }
  92169. for (var j = 0; j < 3; ++j) {
  92170. if (t.error[j] < threshold) {
  92171. var deleted0 = [];
  92172. var deleted1 = [];
  92173. var v0 = t.vertices[j];
  92174. var v1 = t.vertices[(j + 1) % 3];
  92175. if (v0.isBorder || v1.isBorder)
  92176. continue;
  92177. var p = BABYLON.Vector3.Zero();
  92178. var n = BABYLON.Vector3.Zero();
  92179. var uv = BABYLON.Vector2.Zero();
  92180. var color = new BABYLON.Color4(0, 0, 0, 1);
  92181. _this.calculateError(v0, v1, p, n, uv, color);
  92182. var delTr = new Array();
  92183. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  92184. continue;
  92185. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  92186. continue;
  92187. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  92188. continue;
  92189. var uniqueArray = new Array();
  92190. delTr.forEach(function (deletedT) {
  92191. if (uniqueArray.indexOf(deletedT) === -1) {
  92192. deletedT.deletePending = true;
  92193. uniqueArray.push(deletedT);
  92194. }
  92195. });
  92196. if (uniqueArray.length % 2 !== 0) {
  92197. continue;
  92198. }
  92199. v0.q = v1.q.add(v0.q);
  92200. v0.updatePosition(p);
  92201. var tStart = _this.references.length;
  92202. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92203. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92204. var tCount = _this.references.length - tStart;
  92205. if (tCount <= v0.triangleCount) {
  92206. if (tCount) {
  92207. for (var c = 0; c < tCount; c++) {
  92208. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92209. }
  92210. }
  92211. }
  92212. else {
  92213. v0.triangleStart = tStart;
  92214. }
  92215. v0.triangleCount = tCount;
  92216. break;
  92217. }
  92218. }
  92219. };
  92220. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92221. }, 0);
  92222. };
  92223. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92224. if (triangleCount - deletedTriangles <= targetCount)
  92225. loop.breakLoop();
  92226. else {
  92227. iterationFunction(loop.index, function () {
  92228. loop.executeNext();
  92229. });
  92230. }
  92231. }, function () {
  92232. setTimeout(function () {
  92233. //reconstruct this part of the mesh
  92234. _this.reconstructMesh(submeshIndex);
  92235. successCallback();
  92236. }, 0);
  92237. });
  92238. };
  92239. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92240. var _this = this;
  92241. this.vertices = [];
  92242. this.triangles = [];
  92243. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92244. var indices = this._mesh.getIndices();
  92245. var submesh = this._mesh.subMeshes[submeshIndex];
  92246. var findInVertices = function (positionToSearch) {
  92247. if (optimizeMesh) {
  92248. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92249. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92250. return _this.vertices[ii];
  92251. }
  92252. }
  92253. }
  92254. return null;
  92255. };
  92256. var vertexReferences = [];
  92257. var vertexInit = function (i) {
  92258. if (!positionData) {
  92259. return;
  92260. }
  92261. var offset = i + submesh.verticesStart;
  92262. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92263. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92264. vertex.originalOffsets.push(offset);
  92265. if (vertex.id === _this.vertices.length) {
  92266. _this.vertices.push(vertex);
  92267. }
  92268. vertexReferences.push(vertex.id);
  92269. };
  92270. //var totalVertices = mesh.getTotalVertices();
  92271. var totalVertices = submesh.verticesCount;
  92272. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  92273. var indicesInit = function (i) {
  92274. if (!indices) {
  92275. return;
  92276. }
  92277. var offset = (submesh.indexStart / 3) + i;
  92278. var pos = (offset * 3);
  92279. var i0 = indices[pos + 0];
  92280. var i1 = indices[pos + 1];
  92281. var i2 = indices[pos + 2];
  92282. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92283. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92284. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92285. var triangle = new DecimationTriangle([v0, v1, v2]);
  92286. triangle.originalOffset = pos;
  92287. _this.triangles.push(triangle);
  92288. };
  92289. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92290. _this.init(callback);
  92291. });
  92292. });
  92293. };
  92294. QuadraticErrorSimplification.prototype.init = function (callback) {
  92295. var _this = this;
  92296. var triangleInit1 = function (i) {
  92297. var t = _this.triangles[i];
  92298. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92299. for (var j = 0; j < 3; j++) {
  92300. 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))));
  92301. }
  92302. };
  92303. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92304. var triangleInit2 = function (i) {
  92305. var t = _this.triangles[i];
  92306. for (var j = 0; j < 3; ++j) {
  92307. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92308. }
  92309. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92310. };
  92311. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92312. callback();
  92313. });
  92314. });
  92315. };
  92316. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92317. var newTriangles = [];
  92318. var i;
  92319. for (i = 0; i < this.vertices.length; ++i) {
  92320. this.vertices[i].triangleCount = 0;
  92321. }
  92322. var t;
  92323. var j;
  92324. for (i = 0; i < this.triangles.length; ++i) {
  92325. if (!this.triangles[i].deleted) {
  92326. t = this.triangles[i];
  92327. for (j = 0; j < 3; ++j) {
  92328. t.vertices[j].triangleCount = 1;
  92329. }
  92330. newTriangles.push(t);
  92331. }
  92332. }
  92333. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92334. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92335. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92336. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92337. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92338. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92339. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92340. var vertexCount = 0;
  92341. for (i = 0; i < this.vertices.length; ++i) {
  92342. var vertex = this.vertices[i];
  92343. vertex.id = vertexCount;
  92344. if (vertex.triangleCount) {
  92345. vertex.originalOffsets.forEach(function (originalOffset) {
  92346. if (!normalData) {
  92347. return;
  92348. }
  92349. newPositionData.push(vertex.position.x);
  92350. newPositionData.push(vertex.position.y);
  92351. newPositionData.push(vertex.position.z);
  92352. newNormalData.push(normalData[originalOffset * 3]);
  92353. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92354. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92355. if (uvs && uvs.length) {
  92356. newUVsData.push(uvs[(originalOffset * 2)]);
  92357. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92358. }
  92359. else if (colorsData && colorsData.length) {
  92360. newColorsData.push(colorsData[(originalOffset * 4)]);
  92361. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92362. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92363. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92364. }
  92365. ++vertexCount;
  92366. });
  92367. }
  92368. }
  92369. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92370. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92371. var submeshesArray = this._reconstructedMesh.subMeshes;
  92372. this._reconstructedMesh.subMeshes = [];
  92373. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92374. var originalIndices = this._mesh.getIndices();
  92375. for (i = 0; i < newTriangles.length; ++i) {
  92376. t = newTriangles[i]; //now get the new referencing point for each vertex
  92377. [0, 1, 2].forEach(function (idx) {
  92378. var id = originalIndices[t.originalOffset + idx];
  92379. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92380. if (offset < 0)
  92381. offset = 0;
  92382. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92383. });
  92384. }
  92385. //overwriting the old vertex buffers and indices.
  92386. this._reconstructedMesh.setIndices(newIndicesArray);
  92387. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92388. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92389. if (newUVsData.length > 0)
  92390. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92391. if (newColorsData.length > 0)
  92392. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92393. //create submesh
  92394. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92395. if (submeshIndex > 0) {
  92396. this._reconstructedMesh.subMeshes = [];
  92397. submeshesArray.forEach(function (submesh) {
  92398. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92399. });
  92400. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92401. }
  92402. };
  92403. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92404. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92405. this._reconstructedMesh.material = this._mesh.material;
  92406. this._reconstructedMesh.parent = this._mesh.parent;
  92407. this._reconstructedMesh.isVisible = false;
  92408. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92409. };
  92410. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92411. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92412. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92413. if (t.deleted)
  92414. continue;
  92415. var s = this.references[vertex1.triangleStart + i].vertexId;
  92416. var v1 = t.vertices[(s + 1) % 3];
  92417. var v2 = t.vertices[(s + 2) % 3];
  92418. if ((v1 === vertex2 || v2 === vertex2)) {
  92419. deletedArray[i] = true;
  92420. delTr.push(t);
  92421. continue;
  92422. }
  92423. var d1 = v1.position.subtract(point);
  92424. d1 = d1.normalize();
  92425. var d2 = v2.position.subtract(point);
  92426. d2 = d2.normalize();
  92427. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92428. return true;
  92429. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92430. deletedArray[i] = false;
  92431. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92432. return true;
  92433. }
  92434. return false;
  92435. };
  92436. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92437. var newDeleted = deletedTriangles;
  92438. for (var i = 0; i < vertex.triangleCount; ++i) {
  92439. var ref = this.references[vertex.triangleStart + i];
  92440. var t = this.triangles[ref.triangleId];
  92441. if (t.deleted)
  92442. continue;
  92443. if (deletedArray[i] && t.deletePending) {
  92444. t.deleted = true;
  92445. newDeleted++;
  92446. continue;
  92447. }
  92448. t.vertices[ref.vertexId] = origVertex;
  92449. t.isDirty = true;
  92450. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92451. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92452. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92453. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92454. this.references.push(ref);
  92455. }
  92456. return newDeleted;
  92457. };
  92458. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92459. for (var i = 0; i < this.vertices.length; ++i) {
  92460. var vCount = [];
  92461. var vId = [];
  92462. var v = this.vertices[i];
  92463. var j;
  92464. for (j = 0; j < v.triangleCount; ++j) {
  92465. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92466. for (var ii = 0; ii < 3; ii++) {
  92467. var ofs = 0;
  92468. var vv = triangle.vertices[ii];
  92469. while (ofs < vCount.length) {
  92470. if (vId[ofs] === vv.id)
  92471. break;
  92472. ++ofs;
  92473. }
  92474. if (ofs === vCount.length) {
  92475. vCount.push(1);
  92476. vId.push(vv.id);
  92477. }
  92478. else {
  92479. vCount[ofs]++;
  92480. }
  92481. }
  92482. }
  92483. for (j = 0; j < vCount.length; ++j) {
  92484. if (vCount[j] === 1) {
  92485. this.vertices[vId[j]].isBorder = true;
  92486. }
  92487. else {
  92488. this.vertices[vId[j]].isBorder = false;
  92489. }
  92490. }
  92491. }
  92492. };
  92493. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92494. if (identifyBorders === void 0) { identifyBorders = false; }
  92495. var i;
  92496. if (!identifyBorders) {
  92497. var newTrianglesVector = [];
  92498. for (i = 0; i < this.triangles.length; ++i) {
  92499. if (!this.triangles[i].deleted) {
  92500. newTrianglesVector.push(this.triangles[i]);
  92501. }
  92502. }
  92503. this.triangles = newTrianglesVector;
  92504. }
  92505. for (i = 0; i < this.vertices.length; ++i) {
  92506. this.vertices[i].triangleCount = 0;
  92507. this.vertices[i].triangleStart = 0;
  92508. }
  92509. var t;
  92510. var j;
  92511. var v;
  92512. for (i = 0; i < this.triangles.length; ++i) {
  92513. t = this.triangles[i];
  92514. for (j = 0; j < 3; ++j) {
  92515. v = t.vertices[j];
  92516. v.triangleCount++;
  92517. }
  92518. }
  92519. var tStart = 0;
  92520. for (i = 0; i < this.vertices.length; ++i) {
  92521. this.vertices[i].triangleStart = tStart;
  92522. tStart += this.vertices[i].triangleCount;
  92523. this.vertices[i].triangleCount = 0;
  92524. }
  92525. var newReferences = new Array(this.triangles.length * 3);
  92526. for (i = 0; i < this.triangles.length; ++i) {
  92527. t = this.triangles[i];
  92528. for (j = 0; j < 3; ++j) {
  92529. v = t.vertices[j];
  92530. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92531. v.triangleCount++;
  92532. }
  92533. }
  92534. this.references = newReferences;
  92535. if (identifyBorders) {
  92536. this.identifyBorder();
  92537. }
  92538. };
  92539. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92540. var x = point.x;
  92541. var y = point.y;
  92542. var z = point.z;
  92543. 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
  92544. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92545. };
  92546. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92547. var q = vertex1.q.add(vertex2.q);
  92548. var border = vertex1.isBorder && vertex2.isBorder;
  92549. var error = 0;
  92550. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92551. if (qDet !== 0 && !border) {
  92552. if (!pointResult) {
  92553. pointResult = BABYLON.Vector3.Zero();
  92554. }
  92555. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92556. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92557. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92558. error = this.vertexError(q, pointResult);
  92559. }
  92560. else {
  92561. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92562. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92563. var error1 = this.vertexError(q, vertex1.position);
  92564. var error2 = this.vertexError(q, vertex2.position);
  92565. var error3 = this.vertexError(q, p3);
  92566. error = Math.min(error1, error2, error3);
  92567. if (error === error1) {
  92568. if (pointResult) {
  92569. pointResult.copyFrom(vertex1.position);
  92570. }
  92571. }
  92572. else if (error === error2) {
  92573. if (pointResult) {
  92574. pointResult.copyFrom(vertex2.position);
  92575. }
  92576. }
  92577. else {
  92578. if (pointResult) {
  92579. pointResult.copyFrom(p3);
  92580. }
  92581. }
  92582. }
  92583. return error;
  92584. };
  92585. return QuadraticErrorSimplification;
  92586. }());
  92587. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92588. })(BABYLON || (BABYLON = {}));
  92589. //# sourceMappingURL=babylon.meshSimplification.js.map
  92590. var BABYLON;
  92591. (function (BABYLON) {
  92592. var MeshLODLevel = /** @class */ (function () {
  92593. function MeshLODLevel(distance, mesh) {
  92594. this.distance = distance;
  92595. this.mesh = mesh;
  92596. }
  92597. return MeshLODLevel;
  92598. }());
  92599. BABYLON.MeshLODLevel = MeshLODLevel;
  92600. })(BABYLON || (BABYLON = {}));
  92601. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92602. var BABYLON;
  92603. (function (BABYLON) {
  92604. /**
  92605. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92607. */
  92608. var SceneOptimization = /** @class */ (function () {
  92609. /**
  92610. * Creates the SceneOptimization object
  92611. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92612. * @param desc defines the description associated with the optimization
  92613. */
  92614. function SceneOptimization(
  92615. /**
  92616. * Defines the priority of this optimization (0 by default which means first in the list)
  92617. */
  92618. priority) {
  92619. if (priority === void 0) { priority = 0; }
  92620. this.priority = priority;
  92621. }
  92622. /**
  92623. * Gets a string describing the action executed by the current optimization
  92624. * @returns description string
  92625. */
  92626. SceneOptimization.prototype.getDescription = function () {
  92627. return "";
  92628. };
  92629. /**
  92630. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92631. * @param scene defines the current scene where to apply this optimization
  92632. * @param optimizer defines the current optimizer
  92633. * @returns true if everything that can be done was applied
  92634. */
  92635. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92636. return true;
  92637. };
  92638. ;
  92639. return SceneOptimization;
  92640. }());
  92641. BABYLON.SceneOptimization = SceneOptimization;
  92642. /**
  92643. * Defines an optimization used to reduce the size of render target textures
  92644. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92645. */
  92646. var TextureOptimization = /** @class */ (function (_super) {
  92647. __extends(TextureOptimization, _super);
  92648. /**
  92649. * Creates the TextureOptimization object
  92650. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92651. * @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
  92652. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92653. */
  92654. function TextureOptimization(
  92655. /**
  92656. * Defines the priority of this optimization (0 by default which means first in the list)
  92657. */
  92658. priority,
  92659. /**
  92660. * 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
  92661. */
  92662. maximumSize,
  92663. /**
  92664. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92665. */
  92666. step) {
  92667. if (priority === void 0) { priority = 0; }
  92668. if (maximumSize === void 0) { maximumSize = 1024; }
  92669. if (step === void 0) { step = 0.5; }
  92670. var _this = _super.call(this, priority) || this;
  92671. _this.priority = priority;
  92672. _this.maximumSize = maximumSize;
  92673. _this.step = step;
  92674. return _this;
  92675. }
  92676. /**
  92677. * Gets a string describing the action executed by the current optimization
  92678. * @returns description string
  92679. */
  92680. TextureOptimization.prototype.getDescription = function () {
  92681. return "Reducing render target texture size to " + this.maximumSize;
  92682. };
  92683. /**
  92684. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92685. * @param scene defines the current scene where to apply this optimization
  92686. * @param optimizer defines the current optimizer
  92687. * @returns true if everything that can be done was applied
  92688. */
  92689. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92690. var allDone = true;
  92691. for (var index = 0; index < scene.textures.length; index++) {
  92692. var texture = scene.textures[index];
  92693. if (!texture.canRescale || texture.getContext) {
  92694. continue;
  92695. }
  92696. var currentSize = texture.getSize();
  92697. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92698. if (maxDimension > this.maximumSize) {
  92699. texture.scale(this.step);
  92700. allDone = false;
  92701. }
  92702. }
  92703. return allDone;
  92704. };
  92705. return TextureOptimization;
  92706. }(SceneOptimization));
  92707. BABYLON.TextureOptimization = TextureOptimization;
  92708. /**
  92709. * Defines an optimization used to increase or decrease the rendering resolution
  92710. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92711. */
  92712. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92713. __extends(HardwareScalingOptimization, _super);
  92714. /**
  92715. * Creates the HardwareScalingOptimization object
  92716. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92717. * @param maximumScale defines the maximum scale to use (2 by default)
  92718. * @param step defines the step to use between two passes (0.5 by default)
  92719. */
  92720. function HardwareScalingOptimization(
  92721. /**
  92722. * Defines the priority of this optimization (0 by default which means first in the list)
  92723. */
  92724. priority,
  92725. /**
  92726. * Defines the maximum scale to use (2 by default)
  92727. */
  92728. maximumScale,
  92729. /**
  92730. * Defines the step to use between two passes (0.5 by default)
  92731. */
  92732. step) {
  92733. if (priority === void 0) { priority = 0; }
  92734. if (maximumScale === void 0) { maximumScale = 2; }
  92735. if (step === void 0) { step = 0.25; }
  92736. var _this = _super.call(this, priority) || this;
  92737. _this.priority = priority;
  92738. _this.maximumScale = maximumScale;
  92739. _this.step = step;
  92740. _this._currentScale = -1;
  92741. _this._directionOffset = 1;
  92742. return _this;
  92743. }
  92744. /**
  92745. * Gets a string describing the action executed by the current optimization
  92746. * @return description string
  92747. */
  92748. HardwareScalingOptimization.prototype.getDescription = function () {
  92749. return "Setting hardware scaling level to " + this._currentScale;
  92750. };
  92751. /**
  92752. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92753. * @param scene defines the current scene where to apply this optimization
  92754. * @param optimizer defines the current optimizer
  92755. * @returns true if everything that can be done was applied
  92756. */
  92757. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92758. if (this._currentScale === -1) {
  92759. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92760. if (this._currentScale > this.maximumScale) {
  92761. this._directionOffset = -1;
  92762. }
  92763. }
  92764. this._currentScale += this._directionOffset * this.step;
  92765. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92766. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92767. };
  92768. ;
  92769. return HardwareScalingOptimization;
  92770. }(SceneOptimization));
  92771. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92772. /**
  92773. * Defines an optimization used to remove shadows
  92774. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92775. */
  92776. var ShadowsOptimization = /** @class */ (function (_super) {
  92777. __extends(ShadowsOptimization, _super);
  92778. function ShadowsOptimization() {
  92779. return _super !== null && _super.apply(this, arguments) || this;
  92780. }
  92781. /**
  92782. * Gets a string describing the action executed by the current optimization
  92783. * @return description string
  92784. */
  92785. ShadowsOptimization.prototype.getDescription = function () {
  92786. return "Turning shadows on/off";
  92787. };
  92788. /**
  92789. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92790. * @param scene defines the current scene where to apply this optimization
  92791. * @param optimizer defines the current optimizer
  92792. * @returns true if everything that can be done was applied
  92793. */
  92794. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92795. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92796. return true;
  92797. };
  92798. ;
  92799. return ShadowsOptimization;
  92800. }(SceneOptimization));
  92801. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92802. /**
  92803. * Defines an optimization used to turn post-processes off
  92804. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92805. */
  92806. var PostProcessesOptimization = /** @class */ (function (_super) {
  92807. __extends(PostProcessesOptimization, _super);
  92808. function PostProcessesOptimization() {
  92809. return _super !== null && _super.apply(this, arguments) || this;
  92810. }
  92811. /**
  92812. * Gets a string describing the action executed by the current optimization
  92813. * @return description string
  92814. */
  92815. PostProcessesOptimization.prototype.getDescription = function () {
  92816. return "Turning post-processes on/off";
  92817. };
  92818. /**
  92819. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92820. * @param scene defines the current scene where to apply this optimization
  92821. * @param optimizer defines the current optimizer
  92822. * @returns true if everything that can be done was applied
  92823. */
  92824. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92825. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92826. return true;
  92827. };
  92828. ;
  92829. return PostProcessesOptimization;
  92830. }(SceneOptimization));
  92831. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92832. /**
  92833. * Defines an optimization used to turn lens flares off
  92834. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92835. */
  92836. var LensFlaresOptimization = /** @class */ (function (_super) {
  92837. __extends(LensFlaresOptimization, _super);
  92838. function LensFlaresOptimization() {
  92839. return _super !== null && _super.apply(this, arguments) || this;
  92840. }
  92841. /**
  92842. * Gets a string describing the action executed by the current optimization
  92843. * @return description string
  92844. */
  92845. LensFlaresOptimization.prototype.getDescription = function () {
  92846. return "Turning lens flares on/off";
  92847. };
  92848. /**
  92849. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92850. * @param scene defines the current scene where to apply this optimization
  92851. * @param optimizer defines the current optimizer
  92852. * @returns true if everything that can be done was applied
  92853. */
  92854. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92855. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92856. return true;
  92857. };
  92858. ;
  92859. return LensFlaresOptimization;
  92860. }(SceneOptimization));
  92861. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92862. /**
  92863. * Defines an optimization based on user defined callback.
  92864. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92865. */
  92866. var CustomOptimization = /** @class */ (function (_super) {
  92867. __extends(CustomOptimization, _super);
  92868. function CustomOptimization() {
  92869. return _super !== null && _super.apply(this, arguments) || this;
  92870. }
  92871. /**
  92872. * Gets a string describing the action executed by the current optimization
  92873. * @returns description string
  92874. */
  92875. CustomOptimization.prototype.getDescription = function () {
  92876. if (this.onGetDescription) {
  92877. return this.onGetDescription();
  92878. }
  92879. return "Running user defined callback";
  92880. };
  92881. /**
  92882. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92883. * @param scene defines the current scene where to apply this optimization
  92884. * @param optimizer defines the current optimizer
  92885. * @returns true if everything that can be done was applied
  92886. */
  92887. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92888. if (this.onApply) {
  92889. return this.onApply(scene, optimizer);
  92890. }
  92891. return true;
  92892. };
  92893. ;
  92894. return CustomOptimization;
  92895. }(SceneOptimization));
  92896. BABYLON.CustomOptimization = CustomOptimization;
  92897. /**
  92898. * Defines an optimization used to turn particles off
  92899. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92900. */
  92901. var ParticlesOptimization = /** @class */ (function (_super) {
  92902. __extends(ParticlesOptimization, _super);
  92903. function ParticlesOptimization() {
  92904. return _super !== null && _super.apply(this, arguments) || this;
  92905. }
  92906. /**
  92907. * Gets a string describing the action executed by the current optimization
  92908. * @return description string
  92909. */
  92910. ParticlesOptimization.prototype.getDescription = function () {
  92911. return "Turning particles on/off";
  92912. };
  92913. /**
  92914. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92915. * @param scene defines the current scene where to apply this optimization
  92916. * @param optimizer defines the current optimizer
  92917. * @returns true if everything that can be done was applied
  92918. */
  92919. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92920. scene.particlesEnabled = optimizer.isInImprovementMode;
  92921. return true;
  92922. };
  92923. ;
  92924. return ParticlesOptimization;
  92925. }(SceneOptimization));
  92926. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92927. /**
  92928. * Defines an optimization used to turn render targets off
  92929. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92930. */
  92931. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92932. __extends(RenderTargetsOptimization, _super);
  92933. function RenderTargetsOptimization() {
  92934. return _super !== null && _super.apply(this, arguments) || this;
  92935. }
  92936. /**
  92937. * Gets a string describing the action executed by the current optimization
  92938. * @return description string
  92939. */
  92940. RenderTargetsOptimization.prototype.getDescription = function () {
  92941. return "Turning render targets off";
  92942. };
  92943. /**
  92944. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92945. * @param scene defines the current scene where to apply this optimization
  92946. * @param optimizer defines the current optimizer
  92947. * @returns true if everything that can be done was applied
  92948. */
  92949. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92950. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92951. return true;
  92952. };
  92953. ;
  92954. return RenderTargetsOptimization;
  92955. }(SceneOptimization));
  92956. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92957. /**
  92958. * Defines an optimization used to merge meshes with compatible materials
  92959. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92960. */
  92961. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92962. __extends(MergeMeshesOptimization, _super);
  92963. function MergeMeshesOptimization() {
  92964. var _this = _super !== null && _super.apply(this, arguments) || this;
  92965. _this._canBeMerged = function (abstractMesh) {
  92966. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92967. return false;
  92968. }
  92969. var mesh = abstractMesh;
  92970. if (!mesh.isVisible || !mesh.isEnabled()) {
  92971. return false;
  92972. }
  92973. if (mesh.instances.length > 0) {
  92974. return false;
  92975. }
  92976. if (mesh.skeleton || mesh.hasLODLevels) {
  92977. return false;
  92978. }
  92979. if (mesh.parent) {
  92980. return false;
  92981. }
  92982. return true;
  92983. };
  92984. return _this;
  92985. }
  92986. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92987. /**
  92988. * Gets or sets a boolean which defines if optimization octree has to be updated
  92989. */
  92990. get: function () {
  92991. return MergeMeshesOptimization._UpdateSelectionTree;
  92992. },
  92993. /**
  92994. * Gets or sets a boolean which defines if optimization octree has to be updated
  92995. */
  92996. set: function (value) {
  92997. MergeMeshesOptimization._UpdateSelectionTree = value;
  92998. },
  92999. enumerable: true,
  93000. configurable: true
  93001. });
  93002. /**
  93003. * Gets a string describing the action executed by the current optimization
  93004. * @return description string
  93005. */
  93006. MergeMeshesOptimization.prototype.getDescription = function () {
  93007. return "Merging similar meshes together";
  93008. };
  93009. /**
  93010. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93011. * @param scene defines the current scene where to apply this optimization
  93012. * @param optimizer defines the current optimizer
  93013. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93014. * @returns true if everything that can be done was applied
  93015. */
  93016. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93017. var globalPool = scene.meshes.slice(0);
  93018. var globalLength = globalPool.length;
  93019. for (var index = 0; index < globalLength; index++) {
  93020. var currentPool = new Array();
  93021. var current = globalPool[index];
  93022. // Checks
  93023. if (!this._canBeMerged(current)) {
  93024. continue;
  93025. }
  93026. currentPool.push(current);
  93027. // Find compatible meshes
  93028. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93029. var otherMesh = globalPool[subIndex];
  93030. if (!this._canBeMerged(otherMesh)) {
  93031. continue;
  93032. }
  93033. if (otherMesh.material !== current.material) {
  93034. continue;
  93035. }
  93036. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93037. continue;
  93038. }
  93039. currentPool.push(otherMesh);
  93040. globalLength--;
  93041. globalPool.splice(subIndex, 1);
  93042. subIndex--;
  93043. }
  93044. if (currentPool.length < 2) {
  93045. continue;
  93046. }
  93047. // Merge meshes
  93048. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93049. }
  93050. if (updateSelectionTree != undefined) {
  93051. if (updateSelectionTree) {
  93052. scene.createOrUpdateSelectionOctree();
  93053. }
  93054. }
  93055. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93056. scene.createOrUpdateSelectionOctree();
  93057. }
  93058. return true;
  93059. };
  93060. ;
  93061. MergeMeshesOptimization._UpdateSelectionTree = false;
  93062. return MergeMeshesOptimization;
  93063. }(SceneOptimization));
  93064. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93065. /**
  93066. * Defines a list of options used by SceneOptimizer
  93067. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93068. */
  93069. var SceneOptimizerOptions = /** @class */ (function () {
  93070. /**
  93071. * Creates a new list of options used by SceneOptimizer
  93072. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93073. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93074. */
  93075. function SceneOptimizerOptions(
  93076. /**
  93077. * Defines the target frame rate to reach (60 by default)
  93078. */
  93079. targetFrameRate,
  93080. /**
  93081. * Defines the interval between two checkes (2000ms by default)
  93082. */
  93083. trackerDuration) {
  93084. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93085. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93086. this.targetFrameRate = targetFrameRate;
  93087. this.trackerDuration = trackerDuration;
  93088. /**
  93089. * Gets the list of optimizations to apply
  93090. */
  93091. this.optimizations = new Array();
  93092. }
  93093. /**
  93094. * Add a new optimization
  93095. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93096. * @returns the current SceneOptimizerOptions
  93097. */
  93098. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  93099. this.optimizations.push(optimization);
  93100. return this;
  93101. };
  93102. /**
  93103. * Add a new custom optimization
  93104. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  93105. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  93106. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93107. * @returns the current SceneOptimizerOptions
  93108. */
  93109. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  93110. if (priority === void 0) { priority = 0; }
  93111. var optimization = new CustomOptimization(priority);
  93112. optimization.onApply = onApply;
  93113. optimization.onGetDescription = onGetDescription;
  93114. this.optimizations.push(optimization);
  93115. return this;
  93116. };
  93117. /**
  93118. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  93119. * @param targetFrameRate defines the target frame rate (60 by default)
  93120. * @returns a SceneOptimizerOptions object
  93121. */
  93122. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  93123. var result = new SceneOptimizerOptions(targetFrameRate);
  93124. var priority = 0;
  93125. result.addOptimization(new MergeMeshesOptimization(priority));
  93126. result.addOptimization(new ShadowsOptimization(priority));
  93127. result.addOptimization(new LensFlaresOptimization(priority));
  93128. // Next priority
  93129. priority++;
  93130. result.addOptimization(new PostProcessesOptimization(priority));
  93131. result.addOptimization(new ParticlesOptimization(priority));
  93132. // Next priority
  93133. priority++;
  93134. result.addOptimization(new TextureOptimization(priority, 1024));
  93135. return result;
  93136. };
  93137. /**
  93138. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  93139. * @param targetFrameRate defines the target frame rate (60 by default)
  93140. * @returns a SceneOptimizerOptions object
  93141. */
  93142. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  93143. var result = new SceneOptimizerOptions(targetFrameRate);
  93144. var priority = 0;
  93145. result.addOptimization(new MergeMeshesOptimization(priority));
  93146. result.addOptimization(new ShadowsOptimization(priority));
  93147. result.addOptimization(new LensFlaresOptimization(priority));
  93148. // Next priority
  93149. priority++;
  93150. result.addOptimization(new PostProcessesOptimization(priority));
  93151. result.addOptimization(new ParticlesOptimization(priority));
  93152. // Next priority
  93153. priority++;
  93154. result.addOptimization(new TextureOptimization(priority, 512));
  93155. // Next priority
  93156. priority++;
  93157. result.addOptimization(new RenderTargetsOptimization(priority));
  93158. // Next priority
  93159. priority++;
  93160. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  93161. return result;
  93162. };
  93163. /**
  93164. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  93165. * @param targetFrameRate defines the target frame rate (60 by default)
  93166. * @returns a SceneOptimizerOptions object
  93167. */
  93168. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  93169. var result = new SceneOptimizerOptions(targetFrameRate);
  93170. var priority = 0;
  93171. result.addOptimization(new MergeMeshesOptimization(priority));
  93172. result.addOptimization(new ShadowsOptimization(priority));
  93173. result.addOptimization(new LensFlaresOptimization(priority));
  93174. // Next priority
  93175. priority++;
  93176. result.addOptimization(new PostProcessesOptimization(priority));
  93177. result.addOptimization(new ParticlesOptimization(priority));
  93178. // Next priority
  93179. priority++;
  93180. result.addOptimization(new TextureOptimization(priority, 256));
  93181. // Next priority
  93182. priority++;
  93183. result.addOptimization(new RenderTargetsOptimization(priority));
  93184. // Next priority
  93185. priority++;
  93186. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  93187. return result;
  93188. };
  93189. return SceneOptimizerOptions;
  93190. }());
  93191. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  93192. /**
  93193. * Class used to run optimizations in order to reach a target frame rate
  93194. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93195. */
  93196. var SceneOptimizer = /** @class */ (function () {
  93197. /**
  93198. * Creates a new SceneOptimizer
  93199. * @param scene defines the scene to work on
  93200. * @param options defines the options to use with the SceneOptimizer
  93201. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93202. * @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)
  93203. */
  93204. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93205. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93206. if (improvementMode === void 0) { improvementMode = false; }
  93207. var _this = this;
  93208. this._isRunning = false;
  93209. this._currentPriorityLevel = 0;
  93210. this._targetFrameRate = 60;
  93211. this._trackerDuration = 2000;
  93212. this._currentFrameRate = 0;
  93213. this._improvementMode = false;
  93214. /**
  93215. * Defines an observable called when the optimizer reaches the target frame rate
  93216. */
  93217. this.onSuccessObservable = new BABYLON.Observable();
  93218. /**
  93219. * Defines an observable called when the optimizer enables an optimization
  93220. */
  93221. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93222. /**
  93223. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93224. */
  93225. this.onFailureObservable = new BABYLON.Observable();
  93226. if (!options) {
  93227. this._options = new SceneOptimizerOptions();
  93228. }
  93229. else {
  93230. this._options = options;
  93231. }
  93232. if (this._options.targetFrameRate) {
  93233. this._targetFrameRate = this._options.targetFrameRate;
  93234. }
  93235. if (this._options.trackerDuration) {
  93236. this._trackerDuration = this._options.trackerDuration;
  93237. }
  93238. if (autoGeneratePriorities) {
  93239. var priority = 0;
  93240. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93241. var optim = _a[_i];
  93242. optim.priority = priority++;
  93243. }
  93244. }
  93245. this._improvementMode = improvementMode;
  93246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93247. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93248. _this._sceneDisposeObserver = null;
  93249. _this.dispose();
  93250. });
  93251. }
  93252. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93253. /**
  93254. * Gets a boolean indicating if the optimizer is in improvement mode
  93255. */
  93256. get: function () {
  93257. return this._improvementMode;
  93258. },
  93259. enumerable: true,
  93260. configurable: true
  93261. });
  93262. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93263. /**
  93264. * Gets the current priority level (0 at start)
  93265. */
  93266. get: function () {
  93267. return this._currentPriorityLevel;
  93268. },
  93269. enumerable: true,
  93270. configurable: true
  93271. });
  93272. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  93273. /**
  93274. * Gets the current frame rate checked by the SceneOptimizer
  93275. */
  93276. get: function () {
  93277. return this._currentFrameRate;
  93278. },
  93279. enumerable: true,
  93280. configurable: true
  93281. });
  93282. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93283. /**
  93284. * Gets or sets the current target frame rate (60 by default)
  93285. */
  93286. get: function () {
  93287. return this._targetFrameRate;
  93288. },
  93289. /**
  93290. * Gets or sets the current target frame rate (60 by default)
  93291. */
  93292. set: function (value) {
  93293. this._targetFrameRate = value;
  93294. },
  93295. enumerable: true,
  93296. configurable: true
  93297. });
  93298. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93299. /**
  93300. * Gets or sets the current interval between two checks (every 2000ms by default)
  93301. */
  93302. get: function () {
  93303. return this._trackerDuration;
  93304. },
  93305. /**
  93306. * Gets or sets the current interval between two checks (every 2000ms by default)
  93307. */
  93308. set: function (value) {
  93309. this._trackerDuration = value;
  93310. },
  93311. enumerable: true,
  93312. configurable: true
  93313. });
  93314. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93315. /**
  93316. * Gets the list of active optimizations
  93317. */
  93318. get: function () {
  93319. return this._options.optimizations;
  93320. },
  93321. enumerable: true,
  93322. configurable: true
  93323. });
  93324. /**
  93325. * Stops the current optimizer
  93326. */
  93327. SceneOptimizer.prototype.stop = function () {
  93328. this._isRunning = false;
  93329. };
  93330. /**
  93331. * Reset the optimizer to initial step (current priority level = 0)
  93332. */
  93333. SceneOptimizer.prototype.reset = function () {
  93334. this._currentPriorityLevel = 0;
  93335. };
  93336. /**
  93337. * Start the optimizer. By default it will try to reach a specific framerate
  93338. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93339. */
  93340. SceneOptimizer.prototype.start = function () {
  93341. var _this = this;
  93342. if (this._isRunning) {
  93343. return;
  93344. }
  93345. this._isRunning = true;
  93346. // Let's wait for the scene to be ready before running our check
  93347. this._scene.executeWhenReady(function () {
  93348. setTimeout(function () {
  93349. _this._checkCurrentState();
  93350. }, _this._trackerDuration);
  93351. });
  93352. };
  93353. SceneOptimizer.prototype._checkCurrentState = function () {
  93354. var _this = this;
  93355. if (!this._isRunning) {
  93356. return;
  93357. }
  93358. var scene = this._scene;
  93359. var options = this._options;
  93360. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93361. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93362. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93363. this._isRunning = false;
  93364. this.onSuccessObservable.notifyObservers(this);
  93365. return;
  93366. }
  93367. // Apply current level of optimizations
  93368. var allDone = true;
  93369. var noOptimizationApplied = true;
  93370. for (var index = 0; index < options.optimizations.length; index++) {
  93371. var optimization = options.optimizations[index];
  93372. if (optimization.priority === this._currentPriorityLevel) {
  93373. noOptimizationApplied = false;
  93374. allDone = allDone && optimization.apply(scene, this);
  93375. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93376. }
  93377. }
  93378. // If no optimization was applied, this is a failure :(
  93379. if (noOptimizationApplied) {
  93380. this._isRunning = false;
  93381. this.onFailureObservable.notifyObservers(this);
  93382. return;
  93383. }
  93384. // If all optimizations were done, move to next level
  93385. if (allDone) {
  93386. this._currentPriorityLevel++;
  93387. }
  93388. // Let's the system running for a specific amount of time before checking FPS
  93389. scene.executeWhenReady(function () {
  93390. setTimeout(function () {
  93391. _this._checkCurrentState();
  93392. }, _this._trackerDuration);
  93393. });
  93394. };
  93395. /**
  93396. * Release all resources
  93397. */
  93398. SceneOptimizer.prototype.dispose = function () {
  93399. this.stop();
  93400. this.onSuccessObservable.clear();
  93401. this.onFailureObservable.clear();
  93402. this.onNewOptimizationAppliedObservable.clear();
  93403. if (this._sceneDisposeObserver) {
  93404. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93405. }
  93406. };
  93407. /**
  93408. * Helper function to create a SceneOptimizer with one single line of code
  93409. * @param scene defines the scene to work on
  93410. * @param options defines the options to use with the SceneOptimizer
  93411. * @param onSuccess defines a callback to call on success
  93412. * @param onFailure defines a callback to call on failure
  93413. * @returns the new SceneOptimizer object
  93414. */
  93415. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93416. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93417. if (onSuccess) {
  93418. optimizer.onSuccessObservable.add(function () {
  93419. onSuccess();
  93420. });
  93421. }
  93422. if (onFailure) {
  93423. optimizer.onFailureObservable.add(function () {
  93424. onFailure();
  93425. });
  93426. }
  93427. optimizer.start();
  93428. return optimizer;
  93429. };
  93430. return SceneOptimizer;
  93431. }());
  93432. BABYLON.SceneOptimizer = SceneOptimizer;
  93433. })(BABYLON || (BABYLON = {}));
  93434. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93435. var BABYLON;
  93436. (function (BABYLON) {
  93437. var OutlineRenderer = /** @class */ (function () {
  93438. function OutlineRenderer(scene) {
  93439. this.zOffset = 1;
  93440. this._scene = scene;
  93441. }
  93442. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93443. var _this = this;
  93444. if (useOverlay === void 0) { useOverlay = false; }
  93445. var scene = this._scene;
  93446. var engine = this._scene.getEngine();
  93447. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93448. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93449. return;
  93450. }
  93451. var mesh = subMesh.getRenderingMesh();
  93452. var material = subMesh.getMaterial();
  93453. if (!material || !scene.activeCamera) {
  93454. return;
  93455. }
  93456. engine.enableEffect(this._effect);
  93457. // Logarithmic depth
  93458. if (material.useLogarithmicDepth) {
  93459. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93460. }
  93461. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93462. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93463. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93464. // Bones
  93465. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93466. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93467. }
  93468. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93469. // Alpha test
  93470. if (material && material.needAlphaTesting()) {
  93471. var alphaTexture = material.getAlphaTestTexture();
  93472. if (alphaTexture) {
  93473. this._effect.setTexture("diffuseSampler", alphaTexture);
  93474. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93475. }
  93476. }
  93477. engine.setZOffset(-this.zOffset);
  93478. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93479. engine.setZOffset(0);
  93480. };
  93481. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93482. var defines = [];
  93483. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93484. var mesh = subMesh.getMesh();
  93485. var material = subMesh.getMaterial();
  93486. if (material) {
  93487. // Alpha test
  93488. if (material.needAlphaTesting()) {
  93489. defines.push("#define ALPHATEST");
  93490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93491. attribs.push(BABYLON.VertexBuffer.UVKind);
  93492. defines.push("#define UV1");
  93493. }
  93494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93496. defines.push("#define UV2");
  93497. }
  93498. }
  93499. //Logarithmic depth
  93500. if (material.useLogarithmicDepth) {
  93501. defines.push("#define LOGARITHMICDEPTH");
  93502. }
  93503. }
  93504. // Bones
  93505. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93506. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93507. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93508. if (mesh.numBoneInfluencers > 4) {
  93509. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93510. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93511. }
  93512. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93513. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93514. }
  93515. else {
  93516. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93517. }
  93518. // Instances
  93519. if (useInstances) {
  93520. defines.push("#define INSTANCES");
  93521. attribs.push("world0");
  93522. attribs.push("world1");
  93523. attribs.push("world2");
  93524. attribs.push("world3");
  93525. }
  93526. // Get correct effect
  93527. var join = defines.join("\n");
  93528. if (this._cachedDefines !== join) {
  93529. this._cachedDefines = join;
  93530. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93531. }
  93532. return this._effect.isReady();
  93533. };
  93534. return OutlineRenderer;
  93535. }());
  93536. BABYLON.OutlineRenderer = OutlineRenderer;
  93537. })(BABYLON || (BABYLON = {}));
  93538. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93539. var BABYLON;
  93540. (function (BABYLON) {
  93541. var FaceAdjacencies = /** @class */ (function () {
  93542. function FaceAdjacencies() {
  93543. this.edges = new Array();
  93544. this.edgesConnectedCount = 0;
  93545. }
  93546. return FaceAdjacencies;
  93547. }());
  93548. var EdgesRenderer = /** @class */ (function () {
  93549. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93550. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93551. if (epsilon === void 0) { epsilon = 0.95; }
  93552. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93553. this.edgesWidthScalerForOrthographic = 1000.0;
  93554. this.edgesWidthScalerForPerspective = 50.0;
  93555. this._linesPositions = new Array();
  93556. this._linesNormals = new Array();
  93557. this._linesIndices = new Array();
  93558. this._buffers = {};
  93559. this._checkVerticesInsteadOfIndices = false;
  93560. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93561. this.isEnabled = true;
  93562. this._source = source;
  93563. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93564. this._epsilon = epsilon;
  93565. this._prepareRessources();
  93566. this._generateEdgesLines();
  93567. }
  93568. EdgesRenderer.prototype._prepareRessources = function () {
  93569. if (this._lineShader) {
  93570. return;
  93571. }
  93572. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93573. attributes: ["position", "normal"],
  93574. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93575. });
  93576. this._lineShader.disableDepthWrite = true;
  93577. this._lineShader.backFaceCulling = false;
  93578. };
  93579. EdgesRenderer.prototype._rebuild = function () {
  93580. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93581. if (buffer) {
  93582. buffer._rebuild();
  93583. }
  93584. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93585. if (buffer) {
  93586. buffer._rebuild();
  93587. }
  93588. var scene = this._source.getScene();
  93589. var engine = scene.getEngine();
  93590. this._ib = engine.createIndexBuffer(this._linesIndices);
  93591. };
  93592. EdgesRenderer.prototype.dispose = function () {
  93593. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93594. if (buffer) {
  93595. buffer.dispose();
  93596. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93597. }
  93598. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93599. if (buffer) {
  93600. buffer.dispose();
  93601. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93602. }
  93603. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93604. this._lineShader.dispose();
  93605. };
  93606. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93607. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93608. return 0;
  93609. }
  93610. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93611. return 1;
  93612. }
  93613. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93614. return 2;
  93615. }
  93616. return -1;
  93617. };
  93618. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93619. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93620. return 0;
  93621. }
  93622. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93623. return 1;
  93624. }
  93625. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93626. return 2;
  93627. }
  93628. return -1;
  93629. };
  93630. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93631. var needToCreateLine;
  93632. if (edge === undefined) {
  93633. needToCreateLine = true;
  93634. }
  93635. else {
  93636. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93637. needToCreateLine = dotProduct < this._epsilon;
  93638. }
  93639. if (needToCreateLine) {
  93640. var offset = this._linesPositions.length / 3;
  93641. var normal = p0.subtract(p1);
  93642. normal.normalize();
  93643. // Positions
  93644. this._linesPositions.push(p0.x);
  93645. this._linesPositions.push(p0.y);
  93646. this._linesPositions.push(p0.z);
  93647. this._linesPositions.push(p0.x);
  93648. this._linesPositions.push(p0.y);
  93649. this._linesPositions.push(p0.z);
  93650. this._linesPositions.push(p1.x);
  93651. this._linesPositions.push(p1.y);
  93652. this._linesPositions.push(p1.z);
  93653. this._linesPositions.push(p1.x);
  93654. this._linesPositions.push(p1.y);
  93655. this._linesPositions.push(p1.z);
  93656. // Normals
  93657. this._linesNormals.push(p1.x);
  93658. this._linesNormals.push(p1.y);
  93659. this._linesNormals.push(p1.z);
  93660. this._linesNormals.push(-1);
  93661. this._linesNormals.push(p1.x);
  93662. this._linesNormals.push(p1.y);
  93663. this._linesNormals.push(p1.z);
  93664. this._linesNormals.push(1);
  93665. this._linesNormals.push(p0.x);
  93666. this._linesNormals.push(p0.y);
  93667. this._linesNormals.push(p0.z);
  93668. this._linesNormals.push(-1);
  93669. this._linesNormals.push(p0.x);
  93670. this._linesNormals.push(p0.y);
  93671. this._linesNormals.push(p0.z);
  93672. this._linesNormals.push(1);
  93673. // Indices
  93674. this._linesIndices.push(offset);
  93675. this._linesIndices.push(offset + 1);
  93676. this._linesIndices.push(offset + 2);
  93677. this._linesIndices.push(offset);
  93678. this._linesIndices.push(offset + 2);
  93679. this._linesIndices.push(offset + 3);
  93680. }
  93681. };
  93682. EdgesRenderer.prototype._generateEdgesLines = function () {
  93683. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93684. var indices = this._source.getIndices();
  93685. if (!indices || !positions) {
  93686. return;
  93687. }
  93688. // First let's find adjacencies
  93689. var adjacencies = new Array();
  93690. var faceNormals = new Array();
  93691. var index;
  93692. var faceAdjacencies;
  93693. // Prepare faces
  93694. for (index = 0; index < indices.length; index += 3) {
  93695. faceAdjacencies = new FaceAdjacencies();
  93696. var p0Index = indices[index];
  93697. var p1Index = indices[index + 1];
  93698. var p2Index = indices[index + 2];
  93699. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93700. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93701. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93702. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93703. faceNormal.normalize();
  93704. faceNormals.push(faceNormal);
  93705. adjacencies.push(faceAdjacencies);
  93706. }
  93707. // Scan
  93708. for (index = 0; index < adjacencies.length; index++) {
  93709. faceAdjacencies = adjacencies[index];
  93710. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93711. var otherFaceAdjacencies = adjacencies[otherIndex];
  93712. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93713. break;
  93714. }
  93715. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93716. continue;
  93717. }
  93718. var otherP0 = indices[otherIndex * 3];
  93719. var otherP1 = indices[otherIndex * 3 + 1];
  93720. var otherP2 = indices[otherIndex * 3 + 2];
  93721. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93722. var otherEdgeIndex = 0;
  93723. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93724. continue;
  93725. }
  93726. switch (edgeIndex) {
  93727. case 0:
  93728. if (this._checkVerticesInsteadOfIndices) {
  93729. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93730. }
  93731. else {
  93732. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93733. }
  93734. break;
  93735. case 1:
  93736. if (this._checkVerticesInsteadOfIndices) {
  93737. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93738. }
  93739. else {
  93740. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93741. }
  93742. break;
  93743. case 2:
  93744. if (this._checkVerticesInsteadOfIndices) {
  93745. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93746. }
  93747. else {
  93748. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93749. }
  93750. break;
  93751. }
  93752. if (otherEdgeIndex === -1) {
  93753. continue;
  93754. }
  93755. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93756. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93757. faceAdjacencies.edgesConnectedCount++;
  93758. otherFaceAdjacencies.edgesConnectedCount++;
  93759. if (faceAdjacencies.edgesConnectedCount === 3) {
  93760. break;
  93761. }
  93762. }
  93763. }
  93764. }
  93765. // Create lines
  93766. for (index = 0; index < adjacencies.length; index++) {
  93767. // 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
  93768. var current = adjacencies[index];
  93769. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93770. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93771. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93772. }
  93773. // Merge into a single mesh
  93774. var engine = this._source.getScene().getEngine();
  93775. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93776. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93777. this._ib = engine.createIndexBuffer(this._linesIndices);
  93778. this._indicesCount = this._linesIndices.length;
  93779. };
  93780. EdgesRenderer.prototype.render = function () {
  93781. var scene = this._source.getScene();
  93782. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93783. return;
  93784. }
  93785. var engine = scene.getEngine();
  93786. this._lineShader._preBind();
  93787. // VBOs
  93788. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93789. scene.resetCachedMaterial();
  93790. this._lineShader.setColor4("color", this._source.edgesColor);
  93791. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93792. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93793. }
  93794. else {
  93795. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93796. }
  93797. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93798. this._lineShader.bind(this._source.getWorldMatrix());
  93799. // Draw order
  93800. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93801. this._lineShader.unbind();
  93802. engine.setDepthWrite(true);
  93803. };
  93804. return EdgesRenderer;
  93805. }());
  93806. BABYLON.EdgesRenderer = EdgesRenderer;
  93807. })(BABYLON || (BABYLON = {}));
  93808. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93809. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93810. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93811. s = arguments[i];
  93812. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93813. t[p] = s[p];
  93814. }
  93815. return t;
  93816. };
  93817. var BABYLON;
  93818. (function (BABYLON) {
  93819. /**
  93820. * The effect layer Helps adding post process effect blended with the main pass.
  93821. *
  93822. * This can be for instance use to generate glow or higlight effects on the scene.
  93823. *
  93824. * The effect layer class can not be used directly and is intented to inherited from to be
  93825. * customized per effects.
  93826. */
  93827. var EffectLayer = /** @class */ (function () {
  93828. /**
  93829. * Instantiates a new effect Layer and references it in the scene.
  93830. * @param name The name of the layer
  93831. * @param scene The scene to use the layer in
  93832. */
  93833. function EffectLayer(
  93834. /** The Friendly of the effect in the scene */
  93835. name, scene) {
  93836. this._vertexBuffers = {};
  93837. this._maxSize = 0;
  93838. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93839. this._shouldRender = true;
  93840. this._postProcesses = [];
  93841. this._textures = [];
  93842. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93843. /**
  93844. * The clear color of the texture used to generate the glow map.
  93845. */
  93846. this.neutralColor = new BABYLON.Color4();
  93847. /**
  93848. * Specifies wether the highlight layer is enabled or not.
  93849. */
  93850. this.isEnabled = true;
  93851. /**
  93852. * An event triggered when the effect layer has been disposed.
  93853. */
  93854. this.onDisposeObservable = new BABYLON.Observable();
  93855. /**
  93856. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93857. */
  93858. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93859. /**
  93860. * An event triggered when the generated texture is being merged in the scene.
  93861. */
  93862. this.onBeforeComposeObservable = new BABYLON.Observable();
  93863. /**
  93864. * An event triggered when the generated texture has been merged in the scene.
  93865. */
  93866. this.onAfterComposeObservable = new BABYLON.Observable();
  93867. /**
  93868. * An event triggered when the efffect layer changes its size.
  93869. */
  93870. this.onSizeChangedObservable = new BABYLON.Observable();
  93871. this.name = name;
  93872. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93873. this._engine = scene.getEngine();
  93874. this._maxSize = this._engine.getCaps().maxTextureSize;
  93875. this._scene.effectLayers.push(this);
  93876. // Generate Buffers
  93877. this._generateIndexBuffer();
  93878. this._genrateVertexBuffer();
  93879. }
  93880. Object.defineProperty(EffectLayer.prototype, "camera", {
  93881. /**
  93882. * Gets the camera attached to the layer.
  93883. */
  93884. get: function () {
  93885. return this._effectLayerOptions.camera;
  93886. },
  93887. enumerable: true,
  93888. configurable: true
  93889. });
  93890. /**
  93891. * Initializes the effect layer with the required options.
  93892. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93893. */
  93894. EffectLayer.prototype._init = function (options) {
  93895. // Adapt options
  93896. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93897. this._setMainTextureSize();
  93898. this._createMainTexture();
  93899. this._createTextureAndPostProcesses();
  93900. this._mergeEffect = this._createMergeEffect();
  93901. };
  93902. /**
  93903. * Generates the index buffer of the full screen quad blending to the main canvas.
  93904. */
  93905. EffectLayer.prototype._generateIndexBuffer = function () {
  93906. // Indices
  93907. var indices = [];
  93908. indices.push(0);
  93909. indices.push(1);
  93910. indices.push(2);
  93911. indices.push(0);
  93912. indices.push(2);
  93913. indices.push(3);
  93914. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93915. };
  93916. /**
  93917. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93918. */
  93919. EffectLayer.prototype._genrateVertexBuffer = function () {
  93920. // VBO
  93921. var vertices = [];
  93922. vertices.push(1, 1);
  93923. vertices.push(-1, 1);
  93924. vertices.push(-1, -1);
  93925. vertices.push(1, -1);
  93926. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93928. };
  93929. /**
  93930. * Sets the main texture desired size which is the closest power of two
  93931. * of the engine canvas size.
  93932. */
  93933. EffectLayer.prototype._setMainTextureSize = function () {
  93934. if (this._effectLayerOptions.mainTextureFixedSize) {
  93935. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93936. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93937. }
  93938. else {
  93939. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93940. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93941. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93942. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93943. }
  93944. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93945. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93946. };
  93947. /**
  93948. * Creates the main texture for the effect layer.
  93949. */
  93950. EffectLayer.prototype._createMainTexture = function () {
  93951. var _this = this;
  93952. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93953. width: this._mainTextureDesiredSize.width,
  93954. height: this._mainTextureDesiredSize.height
  93955. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93956. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93957. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93958. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93959. this._mainTexture.anisotropicFilteringLevel = 1;
  93960. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93961. this._mainTexture.renderParticles = false;
  93962. this._mainTexture.renderList = null;
  93963. this._mainTexture.ignoreCameraViewport = true;
  93964. // Custom render function
  93965. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93966. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93967. var index;
  93968. var engine = _this._scene.getEngine();
  93969. if (depthOnlySubMeshes.length) {
  93970. engine.setColorWrite(false);
  93971. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93972. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93973. }
  93974. engine.setColorWrite(true);
  93975. }
  93976. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93977. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93978. }
  93979. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93980. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93981. }
  93982. for (index = 0; index < transparentSubMeshes.length; index++) {
  93983. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93984. }
  93985. };
  93986. this._mainTexture.onClearObservable.add(function (engine) {
  93987. engine.clear(_this.neutralColor, true, true, true);
  93988. });
  93989. };
  93990. /**
  93991. * Checks for the readiness of the element composing the layer.
  93992. * @param subMesh the mesh to check for
  93993. * @param useInstances specify wether or not to use instances to render the mesh
  93994. * @param emissiveTexture the associated emissive texture used to generate the glow
  93995. * @return true if ready otherwise, false
  93996. */
  93997. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93998. var material = subMesh.getMaterial();
  93999. if (!material) {
  94000. return false;
  94001. }
  94002. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94003. return false;
  94004. }
  94005. var defines = [];
  94006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94007. var mesh = subMesh.getMesh();
  94008. var uv1 = false;
  94009. var uv2 = false;
  94010. // Alpha test
  94011. if (material && material.needAlphaTesting()) {
  94012. var alphaTexture = material.getAlphaTestTexture();
  94013. if (alphaTexture) {
  94014. defines.push("#define ALPHATEST");
  94015. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94016. alphaTexture.coordinatesIndex === 1) {
  94017. defines.push("#define DIFFUSEUV2");
  94018. uv2 = true;
  94019. }
  94020. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94021. defines.push("#define DIFFUSEUV1");
  94022. uv1 = true;
  94023. }
  94024. }
  94025. }
  94026. // Emissive
  94027. if (emissiveTexture) {
  94028. defines.push("#define EMISSIVE");
  94029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94030. emissiveTexture.coordinatesIndex === 1) {
  94031. defines.push("#define EMISSIVEUV2");
  94032. uv2 = true;
  94033. }
  94034. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94035. defines.push("#define EMISSIVEUV1");
  94036. uv1 = true;
  94037. }
  94038. }
  94039. if (uv1) {
  94040. attribs.push(BABYLON.VertexBuffer.UVKind);
  94041. defines.push("#define UV1");
  94042. }
  94043. if (uv2) {
  94044. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94045. defines.push("#define UV2");
  94046. }
  94047. // Bones
  94048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94051. if (mesh.numBoneInfluencers > 4) {
  94052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94054. }
  94055. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94056. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94057. }
  94058. else {
  94059. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94060. }
  94061. // Morph targets
  94062. var manager = mesh.morphTargetManager;
  94063. var morphInfluencers = 0;
  94064. if (manager) {
  94065. if (manager.numInfluencers > 0) {
  94066. defines.push("#define MORPHTARGETS");
  94067. morphInfluencers = manager.numInfluencers;
  94068. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94069. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94070. }
  94071. }
  94072. // Instances
  94073. if (useInstances) {
  94074. defines.push("#define INSTANCES");
  94075. attribs.push("world0");
  94076. attribs.push("world1");
  94077. attribs.push("world2");
  94078. attribs.push("world3");
  94079. }
  94080. // Get correct effect
  94081. var join = defines.join("\n");
  94082. if (this._cachedDefines !== join) {
  94083. this._cachedDefines = join;
  94084. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94085. }
  94086. return this._effectLayerMapGenerationEffect.isReady();
  94087. };
  94088. /**
  94089. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94090. */
  94091. EffectLayer.prototype.render = function () {
  94092. var currentEffect = this._mergeEffect;
  94093. // Check
  94094. if (!currentEffect.isReady())
  94095. return;
  94096. for (var i = 0; i < this._postProcesses.length; i++) {
  94097. if (!this._postProcesses[i].isReady()) {
  94098. return;
  94099. }
  94100. }
  94101. var engine = this._scene.getEngine();
  94102. this.onBeforeComposeObservable.notifyObservers(this);
  94103. // Render
  94104. engine.enableEffect(currentEffect);
  94105. engine.setState(false);
  94106. // VBOs
  94107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94108. // Cache
  94109. var previousAlphaMode = engine.getAlphaMode();
  94110. // Go Blend.
  94111. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  94112. // Blends the map on the main canvas.
  94113. this._internalRender(currentEffect);
  94114. // Restore Alpha
  94115. engine.setAlphaMode(previousAlphaMode);
  94116. this.onAfterComposeObservable.notifyObservers(this);
  94117. // Handle size changes.
  94118. var size = this._mainTexture.getSize();
  94119. this._setMainTextureSize();
  94120. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  94121. // Recreate RTT and post processes on size change.
  94122. this.onSizeChangedObservable.notifyObservers(this);
  94123. this._disposeTextureAndPostProcesses();
  94124. this._createMainTexture();
  94125. this._createTextureAndPostProcesses();
  94126. }
  94127. };
  94128. /**
  94129. * Determine if a given mesh will be used in the current effect.
  94130. * @param mesh mesh to test
  94131. * @returns true if the mesh will be used
  94132. */
  94133. EffectLayer.prototype.hasMesh = function (mesh) {
  94134. return true;
  94135. };
  94136. /**
  94137. * Returns true if the layer contains information to display, otherwise false.
  94138. * @returns true if the glow layer should be rendered
  94139. */
  94140. EffectLayer.prototype.shouldRender = function () {
  94141. return this.isEnabled && this._shouldRender;
  94142. };
  94143. /**
  94144. * Returns true if the mesh should render, otherwise false.
  94145. * @param mesh The mesh to render
  94146. * @returns true if it should render otherwise false
  94147. */
  94148. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  94149. return true;
  94150. };
  94151. /**
  94152. * Returns true if the mesh should render, otherwise false.
  94153. * @param mesh The mesh to render
  94154. * @returns true if it should render otherwise false
  94155. */
  94156. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  94157. return true;
  94158. };
  94159. /**
  94160. * Renders the submesh passed in parameter to the generation map.
  94161. */
  94162. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  94163. var _this = this;
  94164. if (!this.shouldRender()) {
  94165. return;
  94166. }
  94167. var material = subMesh.getMaterial();
  94168. var mesh = subMesh.getRenderingMesh();
  94169. var scene = this._scene;
  94170. var engine = scene.getEngine();
  94171. if (!material) {
  94172. return;
  94173. }
  94174. // Do not block in blend mode.
  94175. if (material.needAlphaBlendingForMesh(mesh)) {
  94176. return;
  94177. }
  94178. // Culling
  94179. engine.setState(material.backFaceCulling);
  94180. // Managing instances
  94181. var batch = mesh._getInstancesRenderList(subMesh._id);
  94182. if (batch.mustReturn) {
  94183. return;
  94184. }
  94185. // Early Exit per mesh
  94186. if (!this._shouldRenderMesh(mesh)) {
  94187. return;
  94188. }
  94189. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94190. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  94191. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  94192. engine.enableEffect(this._effectLayerMapGenerationEffect);
  94193. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  94194. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  94195. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  94196. // Alpha test
  94197. if (material && material.needAlphaTesting()) {
  94198. var alphaTexture = material.getAlphaTestTexture();
  94199. if (alphaTexture) {
  94200. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94201. var textureMatrix = alphaTexture.getTextureMatrix();
  94202. if (textureMatrix) {
  94203. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94204. }
  94205. }
  94206. }
  94207. // Glow emissive only
  94208. if (this._emissiveTextureAndColor.texture) {
  94209. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94210. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94211. }
  94212. // Bones
  94213. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94214. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94215. }
  94216. // Morph targets
  94217. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94218. // Draw
  94219. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94220. }
  94221. else {
  94222. // Need to reset refresh rate of the shadowMap
  94223. this._mainTexture.resetRefreshCounter();
  94224. }
  94225. };
  94226. /**
  94227. * Rebuild the required buffers.
  94228. * @hidden Internal use only.
  94229. */
  94230. EffectLayer.prototype._rebuild = function () {
  94231. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94232. if (vb) {
  94233. vb._rebuild();
  94234. }
  94235. this._generateIndexBuffer();
  94236. };
  94237. /**
  94238. * Dispose only the render target textures and post process.
  94239. */
  94240. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94241. this._mainTexture.dispose();
  94242. for (var i = 0; i < this._postProcesses.length; i++) {
  94243. if (this._postProcesses[i]) {
  94244. this._postProcesses[i].dispose();
  94245. }
  94246. }
  94247. this._postProcesses = [];
  94248. for (var i = 0; i < this._textures.length; i++) {
  94249. if (this._textures[i]) {
  94250. this._textures[i].dispose();
  94251. }
  94252. }
  94253. this._textures = [];
  94254. };
  94255. /**
  94256. * Dispose the highlight layer and free resources.
  94257. */
  94258. EffectLayer.prototype.dispose = function () {
  94259. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94260. if (vertexBuffer) {
  94261. vertexBuffer.dispose();
  94262. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94263. }
  94264. if (this._indexBuffer) {
  94265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94266. this._indexBuffer = null;
  94267. }
  94268. // Clean textures and post processes
  94269. this._disposeTextureAndPostProcesses();
  94270. // Remove from scene
  94271. var index = this._scene.effectLayers.indexOf(this, 0);
  94272. if (index > -1) {
  94273. this._scene.effectLayers.splice(index, 1);
  94274. }
  94275. // Callback
  94276. this.onDisposeObservable.notifyObservers(this);
  94277. this.onDisposeObservable.clear();
  94278. this.onBeforeRenderMainTextureObservable.clear();
  94279. this.onBeforeComposeObservable.clear();
  94280. this.onAfterComposeObservable.clear();
  94281. this.onSizeChangedObservable.clear();
  94282. };
  94283. /**
  94284. * Gets the class name of the effect layer
  94285. * @returns the string with the class name of the effect layer
  94286. */
  94287. EffectLayer.prototype.getClassName = function () {
  94288. return "EffectLayer";
  94289. };
  94290. /**
  94291. * Creates an effect layer from parsed effect layer data
  94292. * @param parsedEffectLayer defines effect layer data
  94293. * @param scene defines the current scene
  94294. * @param rootUrl defines the root URL containing the effect layer information
  94295. * @returns a parsed effect Layer
  94296. */
  94297. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94298. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94299. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94300. };
  94301. __decorate([
  94302. BABYLON.serialize()
  94303. ], EffectLayer.prototype, "name", void 0);
  94304. __decorate([
  94305. BABYLON.serializeAsColor4()
  94306. ], EffectLayer.prototype, "neutralColor", void 0);
  94307. __decorate([
  94308. BABYLON.serialize()
  94309. ], EffectLayer.prototype, "isEnabled", void 0);
  94310. __decorate([
  94311. BABYLON.serializeAsCameraReference()
  94312. ], EffectLayer.prototype, "camera", null);
  94313. return EffectLayer;
  94314. }());
  94315. BABYLON.EffectLayer = EffectLayer;
  94316. })(BABYLON || (BABYLON = {}));
  94317. //# sourceMappingURL=babylon.effectLayer.js.map
  94318. var BABYLON;
  94319. (function (BABYLON) {
  94320. /**
  94321. * Special Glow Blur post process only blurring the alpha channel
  94322. * It enforces keeping the most luminous color in the color channel.
  94323. */
  94324. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94325. __extends(GlowBlurPostProcess, _super);
  94326. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94328. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94329. _this.direction = direction;
  94330. _this.kernel = kernel;
  94331. _this.onApplyObservable.add(function (effect) {
  94332. effect.setFloat2("screenSize", _this.width, _this.height);
  94333. effect.setVector2("direction", _this.direction);
  94334. effect.setFloat("blurWidth", _this.kernel);
  94335. });
  94336. return _this;
  94337. }
  94338. return GlowBlurPostProcess;
  94339. }(BABYLON.PostProcess));
  94340. /**
  94341. * The highlight layer Helps adding a glow effect around a mesh.
  94342. *
  94343. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94344. * glowy meshes to your scene.
  94345. *
  94346. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94347. */
  94348. var HighlightLayer = /** @class */ (function (_super) {
  94349. __extends(HighlightLayer, _super);
  94350. /**
  94351. * Instantiates a new highlight Layer and references it to the scene..
  94352. * @param name The name of the layer
  94353. * @param scene The scene to use the layer in
  94354. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94355. */
  94356. function HighlightLayer(name, scene, options) {
  94357. var _this = _super.call(this, name, scene) || this;
  94358. _this.name = name;
  94359. /**
  94360. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94361. */
  94362. _this.innerGlow = true;
  94363. /**
  94364. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94365. */
  94366. _this.outerGlow = true;
  94367. /**
  94368. * An event triggered when the highlight layer is being blurred.
  94369. */
  94370. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94371. /**
  94372. * An event triggered when the highlight layer has been blurred.
  94373. */
  94374. _this.onAfterBlurObservable = new BABYLON.Observable();
  94375. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94376. _this._meshes = {};
  94377. _this._excludedMeshes = {};
  94378. _this.neutralColor = HighlightLayer.NeutralColor;
  94379. // Warn on stencil
  94380. if (!_this._engine.isStencilEnable) {
  94381. 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 }");
  94382. }
  94383. // Adapt options
  94384. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94385. // Initialize the layer
  94386. _this._init({
  94387. alphaBlendingMode: _this._options.alphaBlendingMode,
  94388. camera: _this._options.camera,
  94389. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94390. mainTextureRatio: _this._options.mainTextureRatio
  94391. });
  94392. // Do not render as long as no meshes have been added
  94393. _this._shouldRender = false;
  94394. return _this;
  94395. }
  94396. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94397. /**
  94398. * Gets the horizontal size of the blur.
  94399. */
  94400. get: function () {
  94401. return this._horizontalBlurPostprocess.kernel;
  94402. },
  94403. /**
  94404. * Specifies the horizontal size of the blur.
  94405. */
  94406. set: function (value) {
  94407. this._horizontalBlurPostprocess.kernel = value;
  94408. },
  94409. enumerable: true,
  94410. configurable: true
  94411. });
  94412. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94413. /**
  94414. * Gets the vertical size of the blur.
  94415. */
  94416. get: function () {
  94417. return this._verticalBlurPostprocess.kernel;
  94418. },
  94419. /**
  94420. * Specifies the vertical size of the blur.
  94421. */
  94422. set: function (value) {
  94423. this._verticalBlurPostprocess.kernel = value;
  94424. },
  94425. enumerable: true,
  94426. configurable: true
  94427. });
  94428. /**
  94429. * Get the effect name of the layer.
  94430. * @return The effect name
  94431. */
  94432. HighlightLayer.prototype.getEffectName = function () {
  94433. return HighlightLayer.EffectName;
  94434. };
  94435. /**
  94436. * Create the merge effect. This is the shader use to blit the information back
  94437. * to the main canvas at the end of the scene rendering.
  94438. */
  94439. HighlightLayer.prototype._createMergeEffect = function () {
  94440. // Effect
  94441. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94442. };
  94443. /**
  94444. * Creates the render target textures and post processes used in the highlight layer.
  94445. */
  94446. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94447. var _this = this;
  94448. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94449. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94450. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94451. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94452. var textureType = 0;
  94453. if (this._engine.getCaps().textureHalfFloatRender) {
  94454. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94455. }
  94456. else {
  94457. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94458. }
  94459. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94460. width: blurTextureWidth,
  94461. height: blurTextureHeight
  94462. }, this._scene, false, true, textureType);
  94463. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94464. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94465. this._blurTexture.anisotropicFilteringLevel = 16;
  94466. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94467. this._blurTexture.renderParticles = false;
  94468. this._blurTexture.ignoreCameraViewport = true;
  94469. this._textures = [this._blurTexture];
  94470. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94471. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94472. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94473. effect.setTexture("textureSampler", _this._mainTexture);
  94474. });
  94475. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94476. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94477. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94478. });
  94479. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94480. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94481. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94482. });
  94483. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94484. }
  94485. else {
  94486. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94487. width: blurTextureWidth,
  94488. height: blurTextureHeight
  94489. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94490. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94491. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94492. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94493. effect.setTexture("textureSampler", _this._mainTexture);
  94494. });
  94495. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94496. width: blurTextureWidth,
  94497. height: blurTextureHeight
  94498. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94499. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94500. }
  94501. this._mainTexture.onAfterUnbindObservable.add(function () {
  94502. _this.onBeforeBlurObservable.notifyObservers(_this);
  94503. var internalTexture = _this._blurTexture.getInternalTexture();
  94504. if (internalTexture) {
  94505. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94506. }
  94507. _this.onAfterBlurObservable.notifyObservers(_this);
  94508. });
  94509. // Prevent autoClear.
  94510. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94511. };
  94512. /**
  94513. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94514. */
  94515. HighlightLayer.prototype.needStencil = function () {
  94516. return true;
  94517. };
  94518. /**
  94519. * Checks for the readiness of the element composing the layer.
  94520. * @param subMesh the mesh to check for
  94521. * @param useInstances specify wether or not to use instances to render the mesh
  94522. * @param emissiveTexture the associated emissive texture used to generate the glow
  94523. * @return true if ready otherwise, false
  94524. */
  94525. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94526. var material = subMesh.getMaterial();
  94527. var mesh = subMesh.getRenderingMesh();
  94528. if (!material || !mesh || !this._meshes) {
  94529. return false;
  94530. }
  94531. var emissiveTexture = null;
  94532. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94533. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94534. emissiveTexture = material.emissiveTexture;
  94535. }
  94536. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94537. };
  94538. /**
  94539. * Implementation specific of rendering the generating effect on the main canvas.
  94540. * @param effect The effect used to render through
  94541. */
  94542. HighlightLayer.prototype._internalRender = function (effect) {
  94543. // Texture
  94544. effect.setTexture("textureSampler", this._blurTexture);
  94545. // Cache
  94546. var engine = this._engine;
  94547. var previousStencilBuffer = engine.getStencilBuffer();
  94548. var previousStencilFunction = engine.getStencilFunction();
  94549. var previousStencilMask = engine.getStencilMask();
  94550. var previousStencilOperationPass = engine.getStencilOperationPass();
  94551. var previousStencilOperationFail = engine.getStencilOperationFail();
  94552. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94553. var previousStencilReference = engine.getStencilFunctionReference();
  94554. // Stencil operations
  94555. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94556. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94557. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94558. // Draw order
  94559. engine.setStencilMask(0x00);
  94560. engine.setStencilBuffer(true);
  94561. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94562. // 2 passes inner outer
  94563. if (this.outerGlow) {
  94564. effect.setFloat("offset", 0);
  94565. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94566. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94567. }
  94568. if (this.innerGlow) {
  94569. effect.setFloat("offset", 1);
  94570. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94571. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94572. }
  94573. // Restore Cache
  94574. engine.setStencilFunction(previousStencilFunction);
  94575. engine.setStencilMask(previousStencilMask);
  94576. engine.setStencilBuffer(previousStencilBuffer);
  94577. engine.setStencilOperationPass(previousStencilOperationPass);
  94578. engine.setStencilOperationFail(previousStencilOperationFail);
  94579. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94580. engine.setStencilFunctionReference(previousStencilReference);
  94581. };
  94582. /**
  94583. * Returns true if the layer contains information to display, otherwise false.
  94584. */
  94585. HighlightLayer.prototype.shouldRender = function () {
  94586. if (_super.prototype.shouldRender.call(this)) {
  94587. return this._meshes ? true : false;
  94588. }
  94589. return false;
  94590. };
  94591. /**
  94592. * Returns true if the mesh should render, otherwise false.
  94593. * @param mesh The mesh to render
  94594. * @returns true if it should render otherwise false
  94595. */
  94596. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94597. // Excluded Mesh
  94598. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94599. return false;
  94600. }
  94601. ;
  94602. return true;
  94603. };
  94604. /**
  94605. * Sets the required values for both the emissive texture and and the main color.
  94606. */
  94607. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94608. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94609. if (highlightLayerMesh) {
  94610. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94611. }
  94612. else {
  94613. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94614. }
  94615. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94616. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94617. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94618. }
  94619. else {
  94620. this._emissiveTextureAndColor.texture = null;
  94621. }
  94622. };
  94623. /**
  94624. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94625. * @param mesh The mesh to exclude from the highlight layer
  94626. */
  94627. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94628. if (!this._excludedMeshes) {
  94629. return;
  94630. }
  94631. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94632. if (!meshExcluded) {
  94633. this._excludedMeshes[mesh.uniqueId] = {
  94634. mesh: mesh,
  94635. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94636. mesh.getEngine().setStencilBuffer(false);
  94637. }),
  94638. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94639. mesh.getEngine().setStencilBuffer(true);
  94640. }),
  94641. };
  94642. }
  94643. };
  94644. /**
  94645. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94646. * @param mesh The mesh to highlight
  94647. */
  94648. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94649. if (!this._excludedMeshes) {
  94650. return;
  94651. }
  94652. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94653. if (meshExcluded) {
  94654. if (meshExcluded.beforeRender) {
  94655. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94656. }
  94657. if (meshExcluded.afterRender) {
  94658. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94659. }
  94660. }
  94661. this._excludedMeshes[mesh.uniqueId] = null;
  94662. };
  94663. /**
  94664. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94665. * @param mesh mesh to test
  94666. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94667. */
  94668. HighlightLayer.prototype.hasMesh = function (mesh) {
  94669. if (!this._meshes) {
  94670. return false;
  94671. }
  94672. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94673. };
  94674. /**
  94675. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94676. * @param mesh The mesh to highlight
  94677. * @param color The color of the highlight
  94678. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94679. */
  94680. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94681. var _this = this;
  94682. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94683. if (!this._meshes) {
  94684. return;
  94685. }
  94686. var meshHighlight = this._meshes[mesh.uniqueId];
  94687. if (meshHighlight) {
  94688. meshHighlight.color = color;
  94689. }
  94690. else {
  94691. this._meshes[mesh.uniqueId] = {
  94692. mesh: mesh,
  94693. color: color,
  94694. // Lambda required for capture due to Observable this context
  94695. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94696. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94697. _this._defaultStencilReference(mesh);
  94698. }
  94699. else {
  94700. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94701. }
  94702. }),
  94703. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94704. glowEmissiveOnly: glowEmissiveOnly
  94705. };
  94706. }
  94707. this._shouldRender = true;
  94708. };
  94709. /**
  94710. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94711. * @param mesh The mesh to highlight
  94712. */
  94713. HighlightLayer.prototype.removeMesh = function (mesh) {
  94714. if (!this._meshes) {
  94715. return;
  94716. }
  94717. var meshHighlight = this._meshes[mesh.uniqueId];
  94718. if (meshHighlight) {
  94719. if (meshHighlight.observerHighlight) {
  94720. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94721. }
  94722. if (meshHighlight.observerDefault) {
  94723. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94724. }
  94725. delete this._meshes[mesh.uniqueId];
  94726. }
  94727. this._shouldRender = false;
  94728. for (var meshHighlightToCheck in this._meshes) {
  94729. if (this._meshes[meshHighlightToCheck]) {
  94730. this._shouldRender = true;
  94731. break;
  94732. }
  94733. }
  94734. };
  94735. /**
  94736. * Force the stencil to the normal expected value for none glowing parts
  94737. */
  94738. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94739. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94740. };
  94741. /**
  94742. * Free any resources and references associated to a mesh.
  94743. * Internal use
  94744. * @param mesh The mesh to free.
  94745. */
  94746. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94747. this.removeMesh(mesh);
  94748. this.removeExcludedMesh(mesh);
  94749. };
  94750. /**
  94751. * Dispose the highlight layer and free resources.
  94752. */
  94753. HighlightLayer.prototype.dispose = function () {
  94754. if (this._meshes) {
  94755. // Clean mesh references
  94756. for (var id in this._meshes) {
  94757. var meshHighlight = this._meshes[id];
  94758. if (meshHighlight && meshHighlight.mesh) {
  94759. if (meshHighlight.observerHighlight) {
  94760. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94761. }
  94762. if (meshHighlight.observerDefault) {
  94763. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94764. }
  94765. }
  94766. }
  94767. this._meshes = null;
  94768. }
  94769. if (this._excludedMeshes) {
  94770. for (var id in this._excludedMeshes) {
  94771. var meshHighlight = this._excludedMeshes[id];
  94772. if (meshHighlight) {
  94773. if (meshHighlight.beforeRender) {
  94774. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94775. }
  94776. if (meshHighlight.afterRender) {
  94777. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94778. }
  94779. }
  94780. }
  94781. this._excludedMeshes = null;
  94782. }
  94783. _super.prototype.dispose.call(this);
  94784. };
  94785. /**
  94786. * Gets the class name of the effect layer
  94787. * @returns the string with the class name of the effect layer
  94788. */
  94789. HighlightLayer.prototype.getClassName = function () {
  94790. return "HighlightLayer";
  94791. };
  94792. /**
  94793. * Serializes this Highlight layer
  94794. * @returns a serialized Highlight layer object
  94795. */
  94796. HighlightLayer.prototype.serialize = function () {
  94797. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94798. serializationObject.customType = "BABYLON.HighlightLayer";
  94799. // Highlighted meshes
  94800. serializationObject.meshes = [];
  94801. if (this._meshes) {
  94802. for (var m in this._meshes) {
  94803. var mesh = this._meshes[m];
  94804. if (mesh) {
  94805. serializationObject.meshes.push({
  94806. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94807. color: mesh.color.asArray(),
  94808. meshId: mesh.mesh.id
  94809. });
  94810. }
  94811. }
  94812. }
  94813. // Excluded meshes
  94814. serializationObject.excludedMeshes = [];
  94815. if (this._excludedMeshes) {
  94816. for (var e in this._excludedMeshes) {
  94817. var excludedMesh = this._excludedMeshes[e];
  94818. if (excludedMesh) {
  94819. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94820. }
  94821. }
  94822. }
  94823. return serializationObject;
  94824. };
  94825. /**
  94826. * Creates a Highlight layer from parsed Highlight layer data
  94827. * @param parsedHightlightLayer defines the Highlight layer data
  94828. * @param scene defines the current scene
  94829. * @param rootUrl defines the root URL containing the Highlight layer information
  94830. * @returns a parsed Highlight layer
  94831. */
  94832. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94833. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94834. var index;
  94835. // Excluded meshes
  94836. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94837. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94838. if (mesh) {
  94839. hl.addExcludedMesh(mesh);
  94840. }
  94841. }
  94842. // Included meshes
  94843. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94844. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94845. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94846. if (mesh) {
  94847. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94848. }
  94849. }
  94850. return hl;
  94851. };
  94852. /**
  94853. * Effect Name of the highlight layer.
  94854. */
  94855. HighlightLayer.EffectName = "HighlightLayer";
  94856. /**
  94857. * The neutral color used during the preparation of the glow effect.
  94858. * This is black by default as the blend operation is a blend operation.
  94859. */
  94860. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94861. /**
  94862. * Stencil value used for glowing meshes.
  94863. */
  94864. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94865. /**
  94866. * Stencil value used for the other meshes in the scene.
  94867. */
  94868. HighlightLayer.NormalMeshStencilReference = 0x01;
  94869. __decorate([
  94870. BABYLON.serialize()
  94871. ], HighlightLayer.prototype, "innerGlow", void 0);
  94872. __decorate([
  94873. BABYLON.serialize()
  94874. ], HighlightLayer.prototype, "outerGlow", void 0);
  94875. __decorate([
  94876. BABYLON.serialize()
  94877. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94878. __decorate([
  94879. BABYLON.serialize()
  94880. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94881. __decorate([
  94882. BABYLON.serialize("options")
  94883. ], HighlightLayer.prototype, "_options", void 0);
  94884. return HighlightLayer;
  94885. }(BABYLON.EffectLayer));
  94886. BABYLON.HighlightLayer = HighlightLayer;
  94887. })(BABYLON || (BABYLON = {}));
  94888. //# sourceMappingURL=babylon.highlightLayer.js.map
  94889. var BABYLON;
  94890. (function (BABYLON) {
  94891. /**
  94892. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94893. *
  94894. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94895. * glowy meshes to your scene.
  94896. *
  94897. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94898. */
  94899. var GlowLayer = /** @class */ (function (_super) {
  94900. __extends(GlowLayer, _super);
  94901. /**
  94902. * Instantiates a new glow Layer and references it to the scene.
  94903. * @param name The name of the layer
  94904. * @param scene The scene to use the layer in
  94905. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94906. */
  94907. function GlowLayer(name, scene, options) {
  94908. var _this = _super.call(this, name, scene) || this;
  94909. _this._intensity = 1.0;
  94910. _this._includedOnlyMeshes = [];
  94911. _this._excludedMeshes = [];
  94912. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94913. // Adapt options
  94914. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94915. // Initialize the layer
  94916. _this._init({
  94917. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94918. camera: _this._options.camera,
  94919. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94920. mainTextureRatio: _this._options.mainTextureRatio
  94921. });
  94922. return _this;
  94923. }
  94924. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94925. /**
  94926. * Gets the kernel size of the blur.
  94927. */
  94928. get: function () {
  94929. return this._horizontalBlurPostprocess1.kernel;
  94930. },
  94931. /**
  94932. * Sets the kernel size of the blur.
  94933. */
  94934. set: function (value) {
  94935. this._horizontalBlurPostprocess1.kernel = value;
  94936. this._verticalBlurPostprocess1.kernel = value;
  94937. this._horizontalBlurPostprocess2.kernel = value;
  94938. this._verticalBlurPostprocess2.kernel = value;
  94939. },
  94940. enumerable: true,
  94941. configurable: true
  94942. });
  94943. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94944. /**
  94945. * Gets the glow intensity.
  94946. */
  94947. get: function () {
  94948. return this._intensity;
  94949. },
  94950. /**
  94951. * Sets the glow intensity.
  94952. */
  94953. set: function (value) {
  94954. this._intensity = value;
  94955. },
  94956. enumerable: true,
  94957. configurable: true
  94958. });
  94959. /**
  94960. * Get the effect name of the layer.
  94961. * @return The effect name
  94962. */
  94963. GlowLayer.prototype.getEffectName = function () {
  94964. return GlowLayer.EffectName;
  94965. };
  94966. /**
  94967. * Create the merge effect. This is the shader use to blit the information back
  94968. * to the main canvas at the end of the scene rendering.
  94969. */
  94970. GlowLayer.prototype._createMergeEffect = function () {
  94971. // Effect
  94972. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94973. };
  94974. /**
  94975. * Creates the render target textures and post processes used in the glow layer.
  94976. */
  94977. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94978. var _this = this;
  94979. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94980. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94981. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94982. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94983. var textureType = 0;
  94984. if (this._engine.getCaps().textureHalfFloatRender) {
  94985. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94986. }
  94987. else {
  94988. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94989. }
  94990. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94991. width: blurTextureWidth,
  94992. height: blurTextureHeight
  94993. }, this._scene, false, true, textureType);
  94994. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94995. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94996. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94997. this._blurTexture1.renderParticles = false;
  94998. this._blurTexture1.ignoreCameraViewport = true;
  94999. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95000. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95001. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95002. width: blurTextureWidth2,
  95003. height: blurTextureHeight2
  95004. }, this._scene, false, true, textureType);
  95005. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95006. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95007. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95008. this._blurTexture2.renderParticles = false;
  95009. this._blurTexture2.ignoreCameraViewport = true;
  95010. this._textures = [this._blurTexture1, this._blurTexture2];
  95011. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95012. width: blurTextureWidth,
  95013. height: blurTextureHeight
  95014. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95015. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95016. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95017. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95018. effect.setTexture("textureSampler", _this._mainTexture);
  95019. });
  95020. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95021. width: blurTextureWidth,
  95022. height: blurTextureHeight
  95023. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95024. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95025. width: blurTextureWidth2,
  95026. height: blurTextureHeight2
  95027. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95028. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95029. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95030. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95031. effect.setTexture("textureSampler", _this._blurTexture1);
  95032. });
  95033. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95034. width: blurTextureWidth2,
  95035. height: blurTextureHeight2
  95036. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95037. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95038. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95039. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95040. this._mainTexture.samples = this._options.mainTextureSamples;
  95041. this._mainTexture.onAfterUnbindObservable.add(function () {
  95042. var internalTexture = _this._blurTexture1.getInternalTexture();
  95043. if (internalTexture) {
  95044. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95045. internalTexture = _this._blurTexture2.getInternalTexture();
  95046. if (internalTexture) {
  95047. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95048. }
  95049. }
  95050. });
  95051. // Prevent autoClear.
  95052. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95053. };
  95054. /**
  95055. * Checks for the readiness of the element composing the layer.
  95056. * @param subMesh the mesh to check for
  95057. * @param useInstances specify wether or not to use instances to render the mesh
  95058. * @param emissiveTexture the associated emissive texture used to generate the glow
  95059. * @return true if ready otherwise, false
  95060. */
  95061. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95062. var material = subMesh.getMaterial();
  95063. var mesh = subMesh.getRenderingMesh();
  95064. if (!material || !mesh) {
  95065. return false;
  95066. }
  95067. var emissiveTexture = material.emissiveTexture;
  95068. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95069. };
  95070. /**
  95071. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95072. */
  95073. GlowLayer.prototype.needStencil = function () {
  95074. return false;
  95075. };
  95076. /**
  95077. * Implementation specific of rendering the generating effect on the main canvas.
  95078. * @param effect The effect used to render through
  95079. */
  95080. GlowLayer.prototype._internalRender = function (effect) {
  95081. // Texture
  95082. effect.setTexture("textureSampler", this._blurTexture1);
  95083. effect.setTexture("textureSampler2", this._blurTexture2);
  95084. effect.setFloat("offset", this._intensity);
  95085. // Cache
  95086. var engine = this._engine;
  95087. var previousStencilBuffer = engine.getStencilBuffer();
  95088. // Draw order
  95089. engine.setStencilBuffer(false);
  95090. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95091. // Draw order
  95092. engine.setStencilBuffer(previousStencilBuffer);
  95093. };
  95094. /**
  95095. * Sets the required values for both the emissive texture and and the main color.
  95096. */
  95097. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95098. var textureLevel = 1.0;
  95099. if (this.customEmissiveTextureSelector) {
  95100. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  95101. }
  95102. else {
  95103. if (material) {
  95104. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95105. if (this._emissiveTextureAndColor.texture) {
  95106. textureLevel = this._emissiveTextureAndColor.texture.level;
  95107. }
  95108. }
  95109. else {
  95110. this._emissiveTextureAndColor.texture = null;
  95111. }
  95112. }
  95113. if (this.customEmissiveColorSelector) {
  95114. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  95115. }
  95116. else {
  95117. if (material.emissiveColor) {
  95118. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  95119. }
  95120. else {
  95121. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95122. }
  95123. }
  95124. };
  95125. /**
  95126. * Returns true if the mesh should render, otherwise false.
  95127. * @param mesh The mesh to render
  95128. * @returns true if it should render otherwise false
  95129. */
  95130. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  95131. return this.hasMesh(mesh);
  95132. };
  95133. /**
  95134. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  95135. * @param mesh The mesh to exclude from the glow layer
  95136. */
  95137. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  95138. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  95139. this._excludedMeshes.push(mesh.uniqueId);
  95140. }
  95141. };
  95142. /**
  95143. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  95144. * @param mesh The mesh to remove
  95145. */
  95146. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  95147. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  95148. if (index !== -1) {
  95149. this._excludedMeshes.splice(index, 1);
  95150. }
  95151. };
  95152. /**
  95153. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  95154. * @param mesh The mesh to include in the glow layer
  95155. */
  95156. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  95157. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  95158. this._includedOnlyMeshes.push(mesh.uniqueId);
  95159. }
  95160. };
  95161. /**
  95162. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  95163. * @param mesh The mesh to remove
  95164. */
  95165. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  95166. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  95167. if (index !== -1) {
  95168. this._includedOnlyMeshes.splice(index, 1);
  95169. }
  95170. };
  95171. /**
  95172. * Determine if a given mesh will be used in the glow layer
  95173. * @param mesh The mesh to test
  95174. * @returns true if the mesh will be highlighted by the current glow layer
  95175. */
  95176. GlowLayer.prototype.hasMesh = function (mesh) {
  95177. // Included Mesh
  95178. if (this._includedOnlyMeshes.length) {
  95179. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  95180. }
  95181. ;
  95182. // Excluded Mesh
  95183. if (this._excludedMeshes.length) {
  95184. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  95185. }
  95186. ;
  95187. return true;
  95188. };
  95189. /**
  95190. * Free any resources and references associated to a mesh.
  95191. * Internal use
  95192. * @param mesh The mesh to free.
  95193. */
  95194. GlowLayer.prototype._disposeMesh = function (mesh) {
  95195. this.removeIncludedOnlyMesh(mesh);
  95196. this.removeExcludedMesh(mesh);
  95197. };
  95198. /**
  95199. * Gets the class name of the effect layer
  95200. * @returns the string with the class name of the effect layer
  95201. */
  95202. GlowLayer.prototype.getClassName = function () {
  95203. return "GlowLayer";
  95204. };
  95205. /**
  95206. * Serializes this glow layer
  95207. * @returns a serialized glow layer object
  95208. */
  95209. GlowLayer.prototype.serialize = function () {
  95210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95211. serializationObject.customType = "BABYLON.GlowLayer";
  95212. var index;
  95213. // Included meshes
  95214. serializationObject.includedMeshes = [];
  95215. if (this._includedOnlyMeshes.length) {
  95216. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95217. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95218. if (mesh) {
  95219. serializationObject.includedMeshes.push(mesh.id);
  95220. }
  95221. }
  95222. }
  95223. // Excluded meshes
  95224. serializationObject.excludedMeshes = [];
  95225. if (this._excludedMeshes.length) {
  95226. for (index = 0; index < this._excludedMeshes.length; index++) {
  95227. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95228. if (mesh) {
  95229. serializationObject.excludedMeshes.push(mesh.id);
  95230. }
  95231. }
  95232. }
  95233. return serializationObject;
  95234. };
  95235. /**
  95236. * Creates a Glow Layer from parsed glow layer data
  95237. * @param parsedGlowLayer defines glow layer data
  95238. * @param scene defines the current scene
  95239. * @param rootUrl defines the root URL containing the glow layer information
  95240. * @returns a parsed Glow Layer
  95241. */
  95242. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95243. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95244. var index;
  95245. // Excluded meshes
  95246. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95247. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95248. if (mesh) {
  95249. gl.addExcludedMesh(mesh);
  95250. }
  95251. }
  95252. // Included meshes
  95253. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95254. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95255. if (mesh) {
  95256. gl.addIncludedOnlyMesh(mesh);
  95257. }
  95258. }
  95259. return gl;
  95260. };
  95261. /**
  95262. * Effect Name of the layer.
  95263. */
  95264. GlowLayer.EffectName = "GlowLayer";
  95265. /**
  95266. * The default blur kernel size used for the glow.
  95267. */
  95268. GlowLayer.DefaultBlurKernelSize = 32;
  95269. /**
  95270. * The default texture size ratio used for the glow.
  95271. */
  95272. GlowLayer.DefaultTextureRatio = 0.5;
  95273. __decorate([
  95274. BABYLON.serialize()
  95275. ], GlowLayer.prototype, "blurKernelSize", null);
  95276. __decorate([
  95277. BABYLON.serialize()
  95278. ], GlowLayer.prototype, "intensity", null);
  95279. __decorate([
  95280. BABYLON.serialize("options")
  95281. ], GlowLayer.prototype, "_options", void 0);
  95282. return GlowLayer;
  95283. }(BABYLON.EffectLayer));
  95284. BABYLON.GlowLayer = GlowLayer;
  95285. })(BABYLON || (BABYLON = {}));
  95286. //# sourceMappingURL=babylon.glowLayer.js.map
  95287. var BABYLON;
  95288. (function (BABYLON) {
  95289. /**
  95290. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95291. */
  95292. var AssetTaskState;
  95293. (function (AssetTaskState) {
  95294. /**
  95295. * Initialization
  95296. */
  95297. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95298. /**
  95299. * Running
  95300. */
  95301. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95302. /**
  95303. * Done
  95304. */
  95305. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95306. /**
  95307. * Error
  95308. */
  95309. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95310. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95311. /**
  95312. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95313. */
  95314. var AbstractAssetTask = /** @class */ (function () {
  95315. /**
  95316. * Creates a new {BABYLON.AssetsManager}
  95317. * @param name defines the name of the task
  95318. */
  95319. function AbstractAssetTask(
  95320. /**
  95321. * Task name
  95322. */ name) {
  95323. this.name = name;
  95324. this._isCompleted = false;
  95325. this._taskState = AssetTaskState.INIT;
  95326. }
  95327. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95328. /**
  95329. * Get if the task is completed
  95330. */
  95331. get: function () {
  95332. return this._isCompleted;
  95333. },
  95334. enumerable: true,
  95335. configurable: true
  95336. });
  95337. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95338. /**
  95339. * Gets the current state of the task
  95340. */
  95341. get: function () {
  95342. return this._taskState;
  95343. },
  95344. enumerable: true,
  95345. configurable: true
  95346. });
  95347. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95348. /**
  95349. * Gets the current error object (if task is in error)
  95350. */
  95351. get: function () {
  95352. return this._errorObject;
  95353. },
  95354. enumerable: true,
  95355. configurable: true
  95356. });
  95357. /**
  95358. * Internal only
  95359. * @hidden
  95360. */
  95361. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95362. if (this._errorObject) {
  95363. return;
  95364. }
  95365. this._errorObject = {
  95366. message: message,
  95367. exception: exception
  95368. };
  95369. };
  95370. /**
  95371. * Execute the current task
  95372. * @param scene defines the scene where you want your assets to be loaded
  95373. * @param onSuccess is a callback called when the task is successfully executed
  95374. * @param onError is a callback called if an error occurs
  95375. */
  95376. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95377. var _this = this;
  95378. this._taskState = AssetTaskState.RUNNING;
  95379. this.runTask(scene, function () {
  95380. _this.onDoneCallback(onSuccess, onError);
  95381. }, function (msg, exception) {
  95382. _this.onErrorCallback(onError, msg, exception);
  95383. });
  95384. };
  95385. /**
  95386. * Execute the current task
  95387. * @param scene defines the scene where you want your assets to be loaded
  95388. * @param onSuccess is a callback called when the task is successfully executed
  95389. * @param onError is a callback called if an error occurs
  95390. */
  95391. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95392. throw new Error("runTask is not implemented");
  95393. };
  95394. /**
  95395. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95396. * This can be used with failed tasks that have the reason for failure fixed.
  95397. */
  95398. AbstractAssetTask.prototype.reset = function () {
  95399. this._taskState = AssetTaskState.INIT;
  95400. };
  95401. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95402. this._taskState = AssetTaskState.ERROR;
  95403. this._errorObject = {
  95404. message: message,
  95405. exception: exception
  95406. };
  95407. if (this.onError) {
  95408. this.onError(this, message, exception);
  95409. }
  95410. onError();
  95411. };
  95412. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95413. try {
  95414. this._taskState = AssetTaskState.DONE;
  95415. this._isCompleted = true;
  95416. if (this.onSuccess) {
  95417. this.onSuccess(this);
  95418. }
  95419. onSuccess();
  95420. }
  95421. catch (e) {
  95422. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95423. }
  95424. };
  95425. return AbstractAssetTask;
  95426. }());
  95427. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95428. /**
  95429. * Class used to share progress information about assets loading
  95430. */
  95431. var AssetsProgressEvent = /** @class */ (function () {
  95432. /**
  95433. * Creates a {BABYLON.AssetsProgressEvent}
  95434. * @param remainingCount defines the number of remaining tasks to process
  95435. * @param totalCount defines the total number of tasks
  95436. * @param task defines the task that was just processed
  95437. */
  95438. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95439. this.remainingCount = remainingCount;
  95440. this.totalCount = totalCount;
  95441. this.task = task;
  95442. }
  95443. return AssetsProgressEvent;
  95444. }());
  95445. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95446. /**
  95447. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95448. */
  95449. var MeshAssetTask = /** @class */ (function (_super) {
  95450. __extends(MeshAssetTask, _super);
  95451. /**
  95452. * Creates a new {BABYLON.MeshAssetTask}
  95453. * @param name defines the name of the task
  95454. * @param meshesNames defines the list of mesh's names you want to load
  95455. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95456. * @param sceneFilename defines the filename of the scene to load from
  95457. */
  95458. function MeshAssetTask(
  95459. /**
  95460. * Defines the name of the task
  95461. */
  95462. name,
  95463. /**
  95464. * Defines the list of mesh's names you want to load
  95465. */
  95466. meshesNames,
  95467. /**
  95468. * Defines the root url to use as a base to load your meshes and associated resources
  95469. */
  95470. rootUrl,
  95471. /**
  95472. * Defines the filename of the scene to load from
  95473. */
  95474. sceneFilename) {
  95475. var _this = _super.call(this, name) || this;
  95476. _this.name = name;
  95477. _this.meshesNames = meshesNames;
  95478. _this.rootUrl = rootUrl;
  95479. _this.sceneFilename = sceneFilename;
  95480. return _this;
  95481. }
  95482. /**
  95483. * Execute the current task
  95484. * @param scene defines the scene where you want your assets to be loaded
  95485. * @param onSuccess is a callback called when the task is successfully executed
  95486. * @param onError is a callback called if an error occurs
  95487. */
  95488. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95489. var _this = this;
  95490. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95491. _this.loadedMeshes = meshes;
  95492. _this.loadedParticleSystems = particleSystems;
  95493. _this.loadedSkeletons = skeletons;
  95494. onSuccess();
  95495. }, null, function (scene, message, exception) {
  95496. onError(message, exception);
  95497. });
  95498. };
  95499. return MeshAssetTask;
  95500. }(AbstractAssetTask));
  95501. BABYLON.MeshAssetTask = MeshAssetTask;
  95502. /**
  95503. * Define a task used by {BABYLON.AssetsManager} to load text content
  95504. */
  95505. var TextFileAssetTask = /** @class */ (function (_super) {
  95506. __extends(TextFileAssetTask, _super);
  95507. /**
  95508. * Creates a new TextFileAssetTask object
  95509. * @param name defines the name of the task
  95510. * @param url defines the location of the file to load
  95511. */
  95512. function TextFileAssetTask(
  95513. /**
  95514. * Defines the name of the task
  95515. */
  95516. name,
  95517. /**
  95518. * Defines the location of the file to load
  95519. */
  95520. url) {
  95521. var _this = _super.call(this, name) || this;
  95522. _this.name = name;
  95523. _this.url = url;
  95524. return _this;
  95525. }
  95526. /**
  95527. * Execute the current task
  95528. * @param scene defines the scene where you want your assets to be loaded
  95529. * @param onSuccess is a callback called when the task is successfully executed
  95530. * @param onError is a callback called if an error occurs
  95531. */
  95532. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95533. var _this = this;
  95534. scene._loadFile(this.url, function (data) {
  95535. _this.text = data;
  95536. onSuccess();
  95537. }, undefined, false, false, function (request, exception) {
  95538. if (request) {
  95539. onError(request.status + " " + request.statusText, exception);
  95540. }
  95541. });
  95542. };
  95543. return TextFileAssetTask;
  95544. }(AbstractAssetTask));
  95545. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95546. /**
  95547. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95548. */
  95549. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95550. __extends(BinaryFileAssetTask, _super);
  95551. /**
  95552. * Creates a new BinaryFileAssetTask object
  95553. * @param name defines the name of the new task
  95554. * @param url defines the location of the file to load
  95555. */
  95556. function BinaryFileAssetTask(
  95557. /**
  95558. * Defines the name of the task
  95559. */
  95560. name,
  95561. /**
  95562. * Defines the location of the file to load
  95563. */
  95564. url) {
  95565. var _this = _super.call(this, name) || this;
  95566. _this.name = name;
  95567. _this.url = url;
  95568. return _this;
  95569. }
  95570. /**
  95571. * Execute the current task
  95572. * @param scene defines the scene where you want your assets to be loaded
  95573. * @param onSuccess is a callback called when the task is successfully executed
  95574. * @param onError is a callback called if an error occurs
  95575. */
  95576. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95577. var _this = this;
  95578. scene._loadFile(this.url, function (data) {
  95579. _this.data = data;
  95580. onSuccess();
  95581. }, undefined, true, true, function (request, exception) {
  95582. if (request) {
  95583. onError(request.status + " " + request.statusText, exception);
  95584. }
  95585. });
  95586. };
  95587. return BinaryFileAssetTask;
  95588. }(AbstractAssetTask));
  95589. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95590. /**
  95591. * Define a task used by {BABYLON.AssetsManager} to load images
  95592. */
  95593. var ImageAssetTask = /** @class */ (function (_super) {
  95594. __extends(ImageAssetTask, _super);
  95595. /**
  95596. * Creates a new ImageAssetTask
  95597. * @param name defines the name of the task
  95598. * @param url defines the location of the image to load
  95599. */
  95600. function ImageAssetTask(
  95601. /**
  95602. * Defines the name of the task
  95603. */
  95604. name,
  95605. /**
  95606. * Defines the location of the image to load
  95607. */
  95608. url) {
  95609. var _this = _super.call(this, name) || this;
  95610. _this.name = name;
  95611. _this.url = url;
  95612. return _this;
  95613. }
  95614. /**
  95615. * Execute the current task
  95616. * @param scene defines the scene where you want your assets to be loaded
  95617. * @param onSuccess is a callback called when the task is successfully executed
  95618. * @param onError is a callback called if an error occurs
  95619. */
  95620. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95621. var _this = this;
  95622. var img = new Image();
  95623. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95624. img.onload = function () {
  95625. _this.image = img;
  95626. onSuccess();
  95627. };
  95628. img.onerror = function (err) {
  95629. onError("Error loading image", err);
  95630. };
  95631. img.src = this.url;
  95632. };
  95633. return ImageAssetTask;
  95634. }(AbstractAssetTask));
  95635. BABYLON.ImageAssetTask = ImageAssetTask;
  95636. /**
  95637. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95638. */
  95639. var TextureAssetTask = /** @class */ (function (_super) {
  95640. __extends(TextureAssetTask, _super);
  95641. /**
  95642. * Creates a new TextureAssetTask object
  95643. * @param name defines the name of the task
  95644. * @param url defines the location of the file to load
  95645. * @param noMipmap defines if mipmap should not be generated (default is false)
  95646. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95647. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95648. */
  95649. function TextureAssetTask(
  95650. /**
  95651. * Defines the name of the task
  95652. */
  95653. name,
  95654. /**
  95655. * Defines the location of the file to load
  95656. */
  95657. url,
  95658. /**
  95659. * Defines if mipmap should not be generated (default is false)
  95660. */
  95661. noMipmap,
  95662. /**
  95663. * Defines if texture must be inverted on Y axis (default is false)
  95664. */
  95665. invertY,
  95666. /**
  95667. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95668. */
  95669. samplingMode) {
  95670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95671. var _this = _super.call(this, name) || this;
  95672. _this.name = name;
  95673. _this.url = url;
  95674. _this.noMipmap = noMipmap;
  95675. _this.invertY = invertY;
  95676. _this.samplingMode = samplingMode;
  95677. return _this;
  95678. }
  95679. /**
  95680. * Execute the current task
  95681. * @param scene defines the scene where you want your assets to be loaded
  95682. * @param onSuccess is a callback called when the task is successfully executed
  95683. * @param onError is a callback called if an error occurs
  95684. */
  95685. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95686. var onload = function () {
  95687. onSuccess();
  95688. };
  95689. var onerror = function (message, exception) {
  95690. onError(message, exception);
  95691. };
  95692. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95693. };
  95694. return TextureAssetTask;
  95695. }(AbstractAssetTask));
  95696. BABYLON.TextureAssetTask = TextureAssetTask;
  95697. /**
  95698. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95699. */
  95700. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95701. __extends(CubeTextureAssetTask, _super);
  95702. /**
  95703. * Creates a new CubeTextureAssetTask
  95704. * @param name defines the name of the task
  95705. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95706. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95707. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95708. * @param files defines the explicit list of files (undefined by default)
  95709. */
  95710. function CubeTextureAssetTask(
  95711. /**
  95712. * Defines the name of the task
  95713. */
  95714. name,
  95715. /**
  95716. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95717. */
  95718. url,
  95719. /**
  95720. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95721. */
  95722. extensions,
  95723. /**
  95724. * Defines if mipmaps should not be generated (default is false)
  95725. */
  95726. noMipmap,
  95727. /**
  95728. * Defines the explicit list of files (undefined by default)
  95729. */
  95730. files) {
  95731. var _this = _super.call(this, name) || this;
  95732. _this.name = name;
  95733. _this.url = url;
  95734. _this.extensions = extensions;
  95735. _this.noMipmap = noMipmap;
  95736. _this.files = files;
  95737. return _this;
  95738. }
  95739. /**
  95740. * Execute the current task
  95741. * @param scene defines the scene where you want your assets to be loaded
  95742. * @param onSuccess is a callback called when the task is successfully executed
  95743. * @param onError is a callback called if an error occurs
  95744. */
  95745. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95746. var onload = function () {
  95747. onSuccess();
  95748. };
  95749. var onerror = function (message, exception) {
  95750. onError(message, exception);
  95751. };
  95752. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95753. };
  95754. return CubeTextureAssetTask;
  95755. }(AbstractAssetTask));
  95756. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95757. /**
  95758. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95759. */
  95760. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95761. __extends(HDRCubeTextureAssetTask, _super);
  95762. /**
  95763. * Creates a new HDRCubeTextureAssetTask object
  95764. * @param name defines the name of the task
  95765. * @param url defines the location of the file to load
  95766. * @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.
  95767. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95768. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95769. * @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)
  95770. * @param reserved Internal use only
  95771. */
  95772. function HDRCubeTextureAssetTask(
  95773. /**
  95774. * Defines the name of the task
  95775. */
  95776. name,
  95777. /**
  95778. * Defines the location of the file to load
  95779. */
  95780. url,
  95781. /**
  95782. * Defines the desired size (the more it increases the longer the generation will be)
  95783. */
  95784. size,
  95785. /**
  95786. * Defines if mipmaps should not be generated (default is false)
  95787. */
  95788. noMipmap,
  95789. /**
  95790. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95791. */
  95792. generateHarmonics,
  95793. /**
  95794. * 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)
  95795. */
  95796. gammaSpace,
  95797. /**
  95798. * Internal Use Only
  95799. */
  95800. reserved) {
  95801. if (noMipmap === void 0) { noMipmap = false; }
  95802. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95803. if (gammaSpace === void 0) { gammaSpace = false; }
  95804. if (reserved === void 0) { reserved = false; }
  95805. var _this = _super.call(this, name) || this;
  95806. _this.name = name;
  95807. _this.url = url;
  95808. _this.size = size;
  95809. _this.noMipmap = noMipmap;
  95810. _this.generateHarmonics = generateHarmonics;
  95811. _this.gammaSpace = gammaSpace;
  95812. _this.reserved = reserved;
  95813. return _this;
  95814. }
  95815. /**
  95816. * Execute the current task
  95817. * @param scene defines the scene where you want your assets to be loaded
  95818. * @param onSuccess is a callback called when the task is successfully executed
  95819. * @param onError is a callback called if an error occurs
  95820. */
  95821. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95822. var onload = function () {
  95823. onSuccess();
  95824. };
  95825. var onerror = function (message, exception) {
  95826. onError(message, exception);
  95827. };
  95828. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95829. };
  95830. return HDRCubeTextureAssetTask;
  95831. }(AbstractAssetTask));
  95832. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95833. /**
  95834. * This class can be used to easily import assets into a scene
  95835. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95836. */
  95837. var AssetsManager = /** @class */ (function () {
  95838. /**
  95839. * Creates a new AssetsManager
  95840. * @param scene defines the scene to work on
  95841. */
  95842. function AssetsManager(scene) {
  95843. this._isLoading = false;
  95844. this._tasks = new Array();
  95845. this._waitingTasksCount = 0;
  95846. this._totalTasksCount = 0;
  95847. /**
  95848. * Observable called when all tasks are processed
  95849. */
  95850. this.onTaskSuccessObservable = new BABYLON.Observable();
  95851. /**
  95852. * Observable called when a task had an error
  95853. */
  95854. this.onTaskErrorObservable = new BABYLON.Observable();
  95855. /**
  95856. * Observable called when a task is successful
  95857. */
  95858. this.onTasksDoneObservable = new BABYLON.Observable();
  95859. /**
  95860. * Observable called when a task is done (whatever the result is)
  95861. */
  95862. this.onProgressObservable = new BABYLON.Observable();
  95863. /**
  95864. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95865. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95866. */
  95867. this.useDefaultLoadingScreen = true;
  95868. this._scene = scene;
  95869. }
  95870. /**
  95871. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95872. * @param taskName defines the name of the new task
  95873. * @param meshesNames defines the name of meshes to load
  95874. * @param rootUrl defines the root url to use to locate files
  95875. * @param sceneFilename defines the filename of the scene file
  95876. * @returns a new {BABYLON.MeshAssetTask} object
  95877. */
  95878. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95879. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95880. this._tasks.push(task);
  95881. return task;
  95882. };
  95883. /**
  95884. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95885. * @param taskName defines the name of the new task
  95886. * @param url defines the url of the file to load
  95887. * @returns a new {BABYLON.TextFileAssetTask} object
  95888. */
  95889. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95890. var task = new TextFileAssetTask(taskName, url);
  95891. this._tasks.push(task);
  95892. return task;
  95893. };
  95894. /**
  95895. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95896. * @param taskName defines the name of the new task
  95897. * @param url defines the url of the file to load
  95898. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95899. */
  95900. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95901. var task = new BinaryFileAssetTask(taskName, url);
  95902. this._tasks.push(task);
  95903. return task;
  95904. };
  95905. /**
  95906. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95907. * @param taskName defines the name of the new task
  95908. * @param url defines the url of the file to load
  95909. * @returns a new {BABYLON.ImageAssetTask} object
  95910. */
  95911. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95912. var task = new ImageAssetTask(taskName, url);
  95913. this._tasks.push(task);
  95914. return task;
  95915. };
  95916. /**
  95917. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95918. * @param taskName defines the name of the new task
  95919. * @param url defines the url of the file to load
  95920. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95921. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95922. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95923. * @returns a new {BABYLON.TextureAssetTask} object
  95924. */
  95925. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95927. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95928. this._tasks.push(task);
  95929. return task;
  95930. };
  95931. /**
  95932. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95933. * @param taskName defines the name of the new task
  95934. * @param url defines the url of the file to load
  95935. * @param extensions defines the extension to use to load the cube map (can be null)
  95936. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95937. * @param files defines the list of files to load (can be null)
  95938. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95939. */
  95940. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95941. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95942. this._tasks.push(task);
  95943. return task;
  95944. };
  95945. /**
  95946. *
  95947. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95948. * @param taskName defines the name of the new task
  95949. * @param url defines the url of the file to load
  95950. * @param size defines the size you want for the cubemap (can be null)
  95951. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95952. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95953. * @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)
  95954. * @param reserved Internal use only
  95955. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95956. */
  95957. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95958. if (noMipmap === void 0) { noMipmap = false; }
  95959. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95960. if (gammaSpace === void 0) { gammaSpace = false; }
  95961. if (reserved === void 0) { reserved = false; }
  95962. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95963. this._tasks.push(task);
  95964. return task;
  95965. };
  95966. /**
  95967. * Remove a task from the assets manager.
  95968. * @param task the task to remove
  95969. */
  95970. AssetsManager.prototype.removeTask = function (task) {
  95971. var index = this._tasks.indexOf(task);
  95972. if (index > -1) {
  95973. this._tasks.splice(index, 1);
  95974. }
  95975. };
  95976. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95977. this._waitingTasksCount--;
  95978. try {
  95979. if (this.onProgress) {
  95980. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95981. }
  95982. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95983. }
  95984. catch (e) {
  95985. BABYLON.Tools.Error("Error running progress callbacks.");
  95986. console.log(e);
  95987. }
  95988. if (this._waitingTasksCount === 0) {
  95989. try {
  95990. if (this.onFinish) {
  95991. this.onFinish(this._tasks);
  95992. }
  95993. // Let's remove successfull tasks
  95994. var currentTasks = this._tasks.slice();
  95995. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95996. var task = currentTasks_1[_i];
  95997. if (task.taskState === AssetTaskState.DONE) {
  95998. var index = this._tasks.indexOf(task);
  95999. if (index > -1) {
  96000. this._tasks.splice(index, 1);
  96001. }
  96002. }
  96003. }
  96004. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96005. }
  96006. catch (e) {
  96007. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96008. console.log(e);
  96009. }
  96010. this._isLoading = false;
  96011. this._scene.getEngine().hideLoadingUI();
  96012. }
  96013. };
  96014. AssetsManager.prototype._runTask = function (task) {
  96015. var _this = this;
  96016. var done = function () {
  96017. try {
  96018. if (_this.onTaskSuccess) {
  96019. _this.onTaskSuccess(task);
  96020. }
  96021. _this.onTaskSuccessObservable.notifyObservers(task);
  96022. _this._decreaseWaitingTasksCount(task);
  96023. }
  96024. catch (e) {
  96025. error("Error executing task success callbacks", e);
  96026. }
  96027. };
  96028. var error = function (message, exception) {
  96029. task._setErrorObject(message, exception);
  96030. if (_this.onTaskError) {
  96031. _this.onTaskError(task);
  96032. }
  96033. _this.onTaskErrorObservable.notifyObservers(task);
  96034. _this._decreaseWaitingTasksCount(task);
  96035. };
  96036. task.run(this._scene, done, error);
  96037. };
  96038. /**
  96039. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96040. * @return the current instance of the {BABYLON.AssetsManager}
  96041. */
  96042. AssetsManager.prototype.reset = function () {
  96043. this._isLoading = false;
  96044. this._tasks = new Array();
  96045. return this;
  96046. };
  96047. /**
  96048. * Start the loading process
  96049. * @return the current instance of the {BABYLON.AssetsManager}
  96050. */
  96051. AssetsManager.prototype.load = function () {
  96052. if (this._isLoading) {
  96053. return this;
  96054. }
  96055. this._isLoading = true;
  96056. this._waitingTasksCount = this._tasks.length;
  96057. this._totalTasksCount = this._tasks.length;
  96058. if (this._waitingTasksCount === 0) {
  96059. this._isLoading = false;
  96060. if (this.onFinish) {
  96061. this.onFinish(this._tasks);
  96062. }
  96063. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96064. return this;
  96065. }
  96066. if (this.useDefaultLoadingScreen) {
  96067. this._scene.getEngine().displayLoadingUI();
  96068. }
  96069. for (var index = 0; index < this._tasks.length; index++) {
  96070. var task = this._tasks[index];
  96071. if (task.taskState === AssetTaskState.INIT) {
  96072. this._runTask(task);
  96073. }
  96074. }
  96075. return this;
  96076. };
  96077. return AssetsManager;
  96078. }());
  96079. BABYLON.AssetsManager = AssetsManager;
  96080. })(BABYLON || (BABYLON = {}));
  96081. //# sourceMappingURL=babylon.assetsManager.js.map
  96082. var BABYLON;
  96083. (function (BABYLON) {
  96084. var serializedGeometries = [];
  96085. var serializeGeometry = function (geometry, serializationGeometries) {
  96086. if (serializedGeometries[geometry.id]) {
  96087. return;
  96088. }
  96089. if (geometry.doNotSerialize) {
  96090. return;
  96091. }
  96092. if (geometry instanceof BABYLON.BoxGeometry) {
  96093. serializationGeometries.boxes.push(geometry.serialize());
  96094. }
  96095. else if (geometry instanceof BABYLON.SphereGeometry) {
  96096. serializationGeometries.spheres.push(geometry.serialize());
  96097. }
  96098. else if (geometry instanceof BABYLON.CylinderGeometry) {
  96099. serializationGeometries.cylinders.push(geometry.serialize());
  96100. }
  96101. else if (geometry instanceof BABYLON.TorusGeometry) {
  96102. serializationGeometries.toruses.push(geometry.serialize());
  96103. }
  96104. else if (geometry instanceof BABYLON.GroundGeometry) {
  96105. serializationGeometries.grounds.push(geometry.serialize());
  96106. }
  96107. else if (geometry instanceof BABYLON.Plane) {
  96108. serializationGeometries.planes.push(geometry.serialize());
  96109. }
  96110. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  96111. serializationGeometries.torusKnots.push(geometry.serialize());
  96112. }
  96113. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  96114. throw new Error("Unknown primitive type");
  96115. }
  96116. else {
  96117. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  96118. }
  96119. serializedGeometries[geometry.id] = true;
  96120. };
  96121. var serializeMesh = function (mesh, serializationScene) {
  96122. var serializationObject = {};
  96123. // Geometry
  96124. var geometry = mesh._geometry;
  96125. if (geometry) {
  96126. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  96127. // 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
  96128. serializeGeometry(geometry, serializationScene.geometries);
  96129. }
  96130. }
  96131. // Custom
  96132. if (mesh.serialize) {
  96133. mesh.serialize(serializationObject);
  96134. }
  96135. return serializationObject;
  96136. };
  96137. var finalizeSingleMesh = function (mesh, serializationObject) {
  96138. //only works if the mesh is already loaded
  96139. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96140. //serialize material
  96141. if (mesh.material) {
  96142. if (mesh.material instanceof BABYLON.MultiMaterial) {
  96143. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  96144. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96145. serializationObject.multiMaterials.push(mesh.material.serialize());
  96146. }
  96147. }
  96148. else {
  96149. serializationObject.materials = serializationObject.materials || [];
  96150. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96151. serializationObject.materials.push(mesh.material.serialize());
  96152. }
  96153. }
  96154. }
  96155. //serialize geometry
  96156. var geometry = mesh._geometry;
  96157. if (geometry) {
  96158. if (!serializationObject.geometries) {
  96159. serializationObject.geometries = {};
  96160. serializationObject.geometries.boxes = [];
  96161. serializationObject.geometries.spheres = [];
  96162. serializationObject.geometries.cylinders = [];
  96163. serializationObject.geometries.toruses = [];
  96164. serializationObject.geometries.grounds = [];
  96165. serializationObject.geometries.planes = [];
  96166. serializationObject.geometries.torusKnots = [];
  96167. serializationObject.geometries.vertexData = [];
  96168. }
  96169. serializeGeometry(geometry, serializationObject.geometries);
  96170. }
  96171. // Skeletons
  96172. if (mesh.skeleton) {
  96173. serializationObject.skeletons = serializationObject.skeletons || [];
  96174. serializationObject.skeletons.push(mesh.skeleton.serialize());
  96175. }
  96176. //serialize the actual mesh
  96177. serializationObject.meshes = serializationObject.meshes || [];
  96178. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96179. }
  96180. };
  96181. var SceneSerializer = /** @class */ (function () {
  96182. function SceneSerializer() {
  96183. }
  96184. SceneSerializer.ClearCache = function () {
  96185. serializedGeometries = [];
  96186. };
  96187. SceneSerializer.Serialize = function (scene) {
  96188. var serializationObject = {};
  96189. SceneSerializer.ClearCache();
  96190. // Scene
  96191. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  96192. serializationObject.autoClear = scene.autoClear;
  96193. serializationObject.clearColor = scene.clearColor.asArray();
  96194. serializationObject.ambientColor = scene.ambientColor.asArray();
  96195. serializationObject.gravity = scene.gravity.asArray();
  96196. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96197. serializationObject.workerCollisions = scene.workerCollisions;
  96198. // Fog
  96199. if (scene.fogMode && scene.fogMode !== 0) {
  96200. serializationObject.fogMode = scene.fogMode;
  96201. serializationObject.fogColor = scene.fogColor.asArray();
  96202. serializationObject.fogStart = scene.fogStart;
  96203. serializationObject.fogEnd = scene.fogEnd;
  96204. serializationObject.fogDensity = scene.fogDensity;
  96205. }
  96206. //Physics
  96207. if (scene.isPhysicsEnabled()) {
  96208. var physicEngine = scene.getPhysicsEngine();
  96209. if (physicEngine) {
  96210. serializationObject.physicsEnabled = true;
  96211. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96212. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96213. }
  96214. }
  96215. // Metadata
  96216. if (scene.metadata) {
  96217. serializationObject.metadata = scene.metadata;
  96218. }
  96219. // Morph targets
  96220. serializationObject.morphTargetManagers = [];
  96221. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96222. var abstractMesh = _a[_i];
  96223. var manager = abstractMesh.morphTargetManager;
  96224. if (manager) {
  96225. serializationObject.morphTargetManagers.push(manager.serialize());
  96226. }
  96227. }
  96228. // Lights
  96229. serializationObject.lights = [];
  96230. var index;
  96231. var light;
  96232. for (index = 0; index < scene.lights.length; index++) {
  96233. light = scene.lights[index];
  96234. if (!light.doNotSerialize) {
  96235. serializationObject.lights.push(light.serialize());
  96236. }
  96237. }
  96238. // Cameras
  96239. serializationObject.cameras = [];
  96240. for (index = 0; index < scene.cameras.length; index++) {
  96241. var camera = scene.cameras[index];
  96242. if (!camera.doNotSerialize) {
  96243. serializationObject.cameras.push(camera.serialize());
  96244. }
  96245. }
  96246. if (scene.activeCamera) {
  96247. serializationObject.activeCameraID = scene.activeCamera.id;
  96248. }
  96249. // Animations
  96250. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96251. // Materials
  96252. serializationObject.materials = [];
  96253. serializationObject.multiMaterials = [];
  96254. var material;
  96255. for (index = 0; index < scene.materials.length; index++) {
  96256. material = scene.materials[index];
  96257. if (!material.doNotSerialize) {
  96258. serializationObject.materials.push(material.serialize());
  96259. }
  96260. }
  96261. // MultiMaterials
  96262. serializationObject.multiMaterials = [];
  96263. for (index = 0; index < scene.multiMaterials.length; index++) {
  96264. var multiMaterial = scene.multiMaterials[index];
  96265. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96266. }
  96267. // Environment texture
  96268. if (scene.environmentTexture) {
  96269. serializationObject.environmentTexture = scene.environmentTexture.name;
  96270. }
  96271. // Skeletons
  96272. serializationObject.skeletons = [];
  96273. for (index = 0; index < scene.skeletons.length; index++) {
  96274. var skeleton = scene.skeletons[index];
  96275. if (!skeleton.doNotSerialize) {
  96276. serializationObject.skeletons.push(skeleton.serialize());
  96277. }
  96278. }
  96279. // Transform nodes
  96280. serializationObject.transformNodes = [];
  96281. for (index = 0; index < scene.transformNodes.length; index++) {
  96282. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96283. }
  96284. // Geometries
  96285. serializationObject.geometries = {};
  96286. serializationObject.geometries.boxes = [];
  96287. serializationObject.geometries.spheres = [];
  96288. serializationObject.geometries.cylinders = [];
  96289. serializationObject.geometries.toruses = [];
  96290. serializationObject.geometries.grounds = [];
  96291. serializationObject.geometries.planes = [];
  96292. serializationObject.geometries.torusKnots = [];
  96293. serializationObject.geometries.vertexData = [];
  96294. serializedGeometries = [];
  96295. var geometries = scene.getGeometries();
  96296. for (index = 0; index < geometries.length; index++) {
  96297. var geometry = geometries[index];
  96298. if (geometry.isReady()) {
  96299. serializeGeometry(geometry, serializationObject.geometries);
  96300. }
  96301. }
  96302. // Meshes
  96303. serializationObject.meshes = [];
  96304. for (index = 0; index < scene.meshes.length; index++) {
  96305. var abstractMesh = scene.meshes[index];
  96306. if (abstractMesh instanceof BABYLON.Mesh) {
  96307. var mesh = abstractMesh;
  96308. if (!mesh.doNotSerialize) {
  96309. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96310. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96311. }
  96312. }
  96313. }
  96314. }
  96315. // Particles Systems
  96316. serializationObject.particleSystems = [];
  96317. for (index = 0; index < scene.particleSystems.length; index++) {
  96318. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96319. }
  96320. // Lens flares
  96321. serializationObject.lensFlareSystems = [];
  96322. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96323. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96324. }
  96325. // Shadows
  96326. serializationObject.shadowGenerators = [];
  96327. for (index = 0; index < scene.lights.length; index++) {
  96328. light = scene.lights[index];
  96329. var shadowGenerator = light.getShadowGenerator();
  96330. if (shadowGenerator) {
  96331. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96332. }
  96333. }
  96334. // Action Manager
  96335. if (scene.actionManager) {
  96336. serializationObject.actions = scene.actionManager.serialize("scene");
  96337. }
  96338. // Audio
  96339. serializationObject.sounds = [];
  96340. for (index = 0; index < scene.soundTracks.length; index++) {
  96341. var soundtrack = scene.soundTracks[index];
  96342. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96343. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96344. }
  96345. }
  96346. // Effect layers
  96347. serializationObject.effectLayers = [];
  96348. for (index = 0; index < scene.effectLayers.length; index++) {
  96349. var layer = scene.effectLayers[index];
  96350. if (layer.serialize) {
  96351. serializationObject.effectLayers.push(layer.serialize());
  96352. }
  96353. }
  96354. return serializationObject;
  96355. };
  96356. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96357. if (withParents === void 0) { withParents = false; }
  96358. if (withChildren === void 0) { withChildren = false; }
  96359. var serializationObject = {};
  96360. SceneSerializer.ClearCache();
  96361. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96362. if (withParents || withChildren) {
  96363. //deliberate for loop! not for each, appended should be processed as well.
  96364. for (var i = 0; i < toSerialize.length; ++i) {
  96365. if (withChildren) {
  96366. toSerialize[i].getDescendants().forEach(function (node) {
  96367. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96368. toSerialize.push(node);
  96369. }
  96370. });
  96371. }
  96372. //make sure the array doesn't contain the object already
  96373. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96374. toSerialize.push(toSerialize[i].parent);
  96375. }
  96376. }
  96377. }
  96378. toSerialize.forEach(function (mesh) {
  96379. finalizeSingleMesh(mesh, serializationObject);
  96380. });
  96381. return serializationObject;
  96382. };
  96383. return SceneSerializer;
  96384. }());
  96385. BABYLON.SceneSerializer = SceneSerializer;
  96386. })(BABYLON || (BABYLON = {}));
  96387. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96388. var BABYLON;
  96389. (function (BABYLON) {
  96390. var ReflectionProbe = /** @class */ (function () {
  96391. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96393. var _this = this;
  96394. this.name = name;
  96395. this._viewMatrix = BABYLON.Matrix.Identity();
  96396. this._target = BABYLON.Vector3.Zero();
  96397. this._add = BABYLON.Vector3.Zero();
  96398. this._invertYAxis = false;
  96399. this.position = BABYLON.Vector3.Zero();
  96400. this._scene = scene;
  96401. this._scene.reflectionProbes.push(this);
  96402. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96403. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96404. switch (faceIndex) {
  96405. case 0:
  96406. _this._add.copyFromFloats(1, 0, 0);
  96407. break;
  96408. case 1:
  96409. _this._add.copyFromFloats(-1, 0, 0);
  96410. break;
  96411. case 2:
  96412. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96413. break;
  96414. case 3:
  96415. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96416. break;
  96417. case 4:
  96418. _this._add.copyFromFloats(0, 0, 1);
  96419. break;
  96420. case 5:
  96421. _this._add.copyFromFloats(0, 0, -1);
  96422. break;
  96423. }
  96424. if (_this._attachedMesh) {
  96425. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96426. }
  96427. _this.position.addToRef(_this._add, _this._target);
  96428. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96429. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96430. scene._forcedViewPosition = _this.position;
  96431. });
  96432. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96433. scene._forcedViewPosition = null;
  96434. scene.updateTransformMatrix(true);
  96435. });
  96436. if (scene.activeCamera) {
  96437. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96438. }
  96439. }
  96440. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96441. get: function () {
  96442. return this._renderTargetTexture.samples;
  96443. },
  96444. set: function (value) {
  96445. this._renderTargetTexture.samples = value;
  96446. },
  96447. enumerable: true,
  96448. configurable: true
  96449. });
  96450. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96451. get: function () {
  96452. return this._renderTargetTexture.refreshRate;
  96453. },
  96454. set: function (value) {
  96455. this._renderTargetTexture.refreshRate = value;
  96456. },
  96457. enumerable: true,
  96458. configurable: true
  96459. });
  96460. ReflectionProbe.prototype.getScene = function () {
  96461. return this._scene;
  96462. };
  96463. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96464. get: function () {
  96465. return this._renderTargetTexture;
  96466. },
  96467. enumerable: true,
  96468. configurable: true
  96469. });
  96470. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96471. get: function () {
  96472. return this._renderTargetTexture.renderList;
  96473. },
  96474. enumerable: true,
  96475. configurable: true
  96476. });
  96477. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96478. this._attachedMesh = mesh;
  96479. };
  96480. /**
  96481. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96482. *
  96483. * @param renderingGroupId The rendering group id corresponding to its index
  96484. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96485. */
  96486. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96487. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96488. };
  96489. ReflectionProbe.prototype.dispose = function () {
  96490. var index = this._scene.reflectionProbes.indexOf(this);
  96491. if (index !== -1) {
  96492. // Remove from the scene if found
  96493. this._scene.reflectionProbes.splice(index, 1);
  96494. }
  96495. if (this._renderTargetTexture) {
  96496. this._renderTargetTexture.dispose();
  96497. this._renderTargetTexture = null;
  96498. }
  96499. };
  96500. return ReflectionProbe;
  96501. }());
  96502. BABYLON.ReflectionProbe = ReflectionProbe;
  96503. })(BABYLON || (BABYLON = {}));
  96504. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96505. var BABYLON;
  96506. (function (BABYLON) {
  96507. var Layer = /** @class */ (function () {
  96508. function Layer(name, imgUrl, scene, isBackground, color) {
  96509. this.name = name;
  96510. this.scale = new BABYLON.Vector2(1, 1);
  96511. this.offset = new BABYLON.Vector2(0, 0);
  96512. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96513. this.layerMask = 0x0FFFFFFF;
  96514. this._vertexBuffers = {};
  96515. // Events
  96516. /**
  96517. * An event triggered when the layer is disposed.
  96518. */
  96519. this.onDisposeObservable = new BABYLON.Observable();
  96520. /**
  96521. * An event triggered before rendering the scene
  96522. */
  96523. this.onBeforeRenderObservable = new BABYLON.Observable();
  96524. /**
  96525. * An event triggered after rendering the scene
  96526. */
  96527. this.onAfterRenderObservable = new BABYLON.Observable();
  96528. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96529. this.isBackground = isBackground === undefined ? true : isBackground;
  96530. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96531. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96532. this._scene.layers.push(this);
  96533. var engine = this._scene.getEngine();
  96534. // VBO
  96535. var vertices = [];
  96536. vertices.push(1, 1);
  96537. vertices.push(-1, 1);
  96538. vertices.push(-1, -1);
  96539. vertices.push(1, -1);
  96540. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96541. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96542. this._createIndexBuffer();
  96543. // Effects
  96544. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96545. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96546. }
  96547. Object.defineProperty(Layer.prototype, "onDispose", {
  96548. set: function (callback) {
  96549. if (this._onDisposeObserver) {
  96550. this.onDisposeObservable.remove(this._onDisposeObserver);
  96551. }
  96552. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96553. },
  96554. enumerable: true,
  96555. configurable: true
  96556. });
  96557. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96558. set: function (callback) {
  96559. if (this._onBeforeRenderObserver) {
  96560. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96561. }
  96562. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96563. },
  96564. enumerable: true,
  96565. configurable: true
  96566. });
  96567. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96568. set: function (callback) {
  96569. if (this._onAfterRenderObserver) {
  96570. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96571. }
  96572. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96573. },
  96574. enumerable: true,
  96575. configurable: true
  96576. });
  96577. Layer.prototype._createIndexBuffer = function () {
  96578. var engine = this._scene.getEngine();
  96579. // Indices
  96580. var indices = [];
  96581. indices.push(0);
  96582. indices.push(1);
  96583. indices.push(2);
  96584. indices.push(0);
  96585. indices.push(2);
  96586. indices.push(3);
  96587. this._indexBuffer = engine.createIndexBuffer(indices);
  96588. };
  96589. Layer.prototype._rebuild = function () {
  96590. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96591. if (vb) {
  96592. vb._rebuild();
  96593. }
  96594. this._createIndexBuffer();
  96595. };
  96596. Layer.prototype.render = function () {
  96597. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96598. // Check
  96599. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96600. return;
  96601. var engine = this._scene.getEngine();
  96602. this.onBeforeRenderObservable.notifyObservers(this);
  96603. // Render
  96604. engine.enableEffect(currentEffect);
  96605. engine.setState(false);
  96606. // Texture
  96607. currentEffect.setTexture("textureSampler", this.texture);
  96608. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96609. // Color
  96610. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96611. // Scale / offset
  96612. currentEffect.setVector2("offset", this.offset);
  96613. currentEffect.setVector2("scale", this.scale);
  96614. // VBOs
  96615. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96616. // Draw order
  96617. if (!this.alphaTest) {
  96618. engine.setAlphaMode(this.alphaBlendingMode);
  96619. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96621. }
  96622. else {
  96623. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96624. }
  96625. this.onAfterRenderObservable.notifyObservers(this);
  96626. };
  96627. Layer.prototype.dispose = function () {
  96628. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96629. if (vertexBuffer) {
  96630. vertexBuffer.dispose();
  96631. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96632. }
  96633. if (this._indexBuffer) {
  96634. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96635. this._indexBuffer = null;
  96636. }
  96637. if (this.texture) {
  96638. this.texture.dispose();
  96639. this.texture = null;
  96640. }
  96641. // Remove from scene
  96642. var index = this._scene.layers.indexOf(this);
  96643. this._scene.layers.splice(index, 1);
  96644. // Callback
  96645. this.onDisposeObservable.notifyObservers(this);
  96646. this.onDisposeObservable.clear();
  96647. this.onAfterRenderObservable.clear();
  96648. this.onBeforeRenderObservable.clear();
  96649. };
  96650. return Layer;
  96651. }());
  96652. BABYLON.Layer = Layer;
  96653. })(BABYLON || (BABYLON = {}));
  96654. //# sourceMappingURL=babylon.layer.js.map
  96655. var BABYLON;
  96656. (function (BABYLON) {
  96657. var TextureTools = /** @class */ (function () {
  96658. function TextureTools() {
  96659. }
  96660. /**
  96661. * Uses the GPU to create a copy texture rescaled at a given size
  96662. * @param texture Texture to copy from
  96663. * @param width Desired width
  96664. * @param height Desired height
  96665. * @return Generated texture
  96666. */
  96667. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96668. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96669. var scene = texture.getScene();
  96670. var engine = scene.getEngine();
  96671. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96672. rtt.wrapU = texture.wrapU;
  96673. rtt.wrapV = texture.wrapV;
  96674. rtt.uOffset = texture.uOffset;
  96675. rtt.vOffset = texture.vOffset;
  96676. rtt.uScale = texture.uScale;
  96677. rtt.vScale = texture.vScale;
  96678. rtt.uAng = texture.uAng;
  96679. rtt.vAng = texture.vAng;
  96680. rtt.wAng = texture.wAng;
  96681. rtt.coordinatesIndex = texture.coordinatesIndex;
  96682. rtt.level = texture.level;
  96683. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96684. rtt._texture.isReady = false;
  96685. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96686. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96687. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96688. passPostProcess.getEffect().executeWhenCompiled(function () {
  96689. passPostProcess.onApply = function (effect) {
  96690. effect.setTexture("textureSampler", texture);
  96691. };
  96692. var internalTexture = rtt.getInternalTexture();
  96693. if (internalTexture) {
  96694. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96695. engine.unBindFramebuffer(internalTexture);
  96696. rtt.disposeFramebufferObjects();
  96697. passPostProcess.dispose();
  96698. internalTexture.isReady = true;
  96699. }
  96700. });
  96701. return rtt;
  96702. };
  96703. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96704. if (!scene._environmentBRDFTexture) {
  96705. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96706. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96707. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96708. scene._environmentBRDFTexture = texture;
  96709. }
  96710. return scene._environmentBRDFTexture;
  96711. };
  96712. 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=";
  96713. return TextureTools;
  96714. }());
  96715. BABYLON.TextureTools = TextureTools;
  96716. })(BABYLON || (BABYLON = {}));
  96717. //# sourceMappingURL=babylon.textureTools.js.map
  96718. var BABYLON;
  96719. (function (BABYLON) {
  96720. var FramingBehavior = /** @class */ (function () {
  96721. function FramingBehavior() {
  96722. this._mode = FramingBehavior.FitFrustumSidesMode;
  96723. this._radiusScale = 1.0;
  96724. this._positionScale = 0.5;
  96725. this._defaultElevation = 0.3;
  96726. this._elevationReturnTime = 1500;
  96727. this._elevationReturnWaitTime = 1000;
  96728. this._zoomStopsAnimation = false;
  96729. this._framingTime = 1500;
  96730. this._isPointerDown = false;
  96731. this._lastInteractionTime = -Infinity;
  96732. // Framing control
  96733. this._animatables = new Array();
  96734. this._betaIsAnimating = false;
  96735. }
  96736. Object.defineProperty(FramingBehavior.prototype, "name", {
  96737. get: function () {
  96738. return "Framing";
  96739. },
  96740. enumerable: true,
  96741. configurable: true
  96742. });
  96743. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96744. /**
  96745. * Gets current mode used by the behavior.
  96746. */
  96747. get: function () {
  96748. return this._mode;
  96749. },
  96750. /**
  96751. * Sets the current mode used by the behavior
  96752. */
  96753. set: function (mode) {
  96754. this._mode = mode;
  96755. },
  96756. enumerable: true,
  96757. configurable: true
  96758. });
  96759. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96760. /**
  96761. * Gets the scale applied to the radius
  96762. */
  96763. get: function () {
  96764. return this._radiusScale;
  96765. },
  96766. /**
  96767. * Sets the scale applied to the radius (1 by default)
  96768. */
  96769. set: function (radius) {
  96770. this._radiusScale = radius;
  96771. },
  96772. enumerable: true,
  96773. configurable: true
  96774. });
  96775. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96776. /**
  96777. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96778. */
  96779. get: function () {
  96780. return this._positionScale;
  96781. },
  96782. /**
  96783. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96784. */
  96785. set: function (scale) {
  96786. this._positionScale = scale;
  96787. },
  96788. enumerable: true,
  96789. configurable: true
  96790. });
  96791. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96792. /**
  96793. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96794. * behaviour is triggered, in radians.
  96795. */
  96796. get: function () {
  96797. return this._defaultElevation;
  96798. },
  96799. /**
  96800. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96801. * behaviour is triggered, in radians.
  96802. */
  96803. set: function (elevation) {
  96804. this._defaultElevation = elevation;
  96805. },
  96806. enumerable: true,
  96807. configurable: true
  96808. });
  96809. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96810. /**
  96811. * Gets the time (in milliseconds) taken to return to the default beta position.
  96812. * Negative value indicates camera should not return to default.
  96813. */
  96814. get: function () {
  96815. return this._elevationReturnTime;
  96816. },
  96817. /**
  96818. * Sets the time (in milliseconds) taken to return to the default beta position.
  96819. * Negative value indicates camera should not return to default.
  96820. */
  96821. set: function (speed) {
  96822. this._elevationReturnTime = speed;
  96823. },
  96824. enumerable: true,
  96825. configurable: true
  96826. });
  96827. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96828. /**
  96829. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96830. */
  96831. get: function () {
  96832. return this._elevationReturnWaitTime;
  96833. },
  96834. /**
  96835. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96836. */
  96837. set: function (time) {
  96838. this._elevationReturnWaitTime = time;
  96839. },
  96840. enumerable: true,
  96841. configurable: true
  96842. });
  96843. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96844. /**
  96845. * Gets the flag that indicates if user zooming should stop animation.
  96846. */
  96847. get: function () {
  96848. return this._zoomStopsAnimation;
  96849. },
  96850. /**
  96851. * Sets the flag that indicates if user zooming should stop animation.
  96852. */
  96853. set: function (flag) {
  96854. this._zoomStopsAnimation = flag;
  96855. },
  96856. enumerable: true,
  96857. configurable: true
  96858. });
  96859. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96860. /**
  96861. * Gets the transition time when framing the mesh, in milliseconds
  96862. */
  96863. get: function () {
  96864. return this._framingTime;
  96865. },
  96866. /**
  96867. * Sets the transition time when framing the mesh, in milliseconds
  96868. */
  96869. set: function (time) {
  96870. this._framingTime = time;
  96871. },
  96872. enumerable: true,
  96873. configurable: true
  96874. });
  96875. FramingBehavior.prototype.init = function () {
  96876. // Do notihng
  96877. };
  96878. FramingBehavior.prototype.attach = function (camera) {
  96879. var _this = this;
  96880. this._attachedCamera = camera;
  96881. var scene = this._attachedCamera.getScene();
  96882. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96883. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96884. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96885. _this._isPointerDown = true;
  96886. return;
  96887. }
  96888. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96889. _this._isPointerDown = false;
  96890. }
  96891. });
  96892. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96893. if (mesh) {
  96894. _this.zoomOnMesh(mesh);
  96895. }
  96896. });
  96897. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96898. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96899. _this._applyUserInteraction();
  96900. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96901. // back to the default position after a given timeout
  96902. _this._maintainCameraAboveGround();
  96903. });
  96904. };
  96905. FramingBehavior.prototype.detach = function () {
  96906. if (!this._attachedCamera) {
  96907. return;
  96908. }
  96909. var scene = this._attachedCamera.getScene();
  96910. if (this._onPrePointerObservableObserver) {
  96911. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96912. }
  96913. if (this._onAfterCheckInputsObserver) {
  96914. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96915. }
  96916. if (this._onMeshTargetChangedObserver) {
  96917. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96918. }
  96919. this._attachedCamera = null;
  96920. };
  96921. /**
  96922. * Targets the given mesh and updates zoom level accordingly.
  96923. * @param mesh The mesh to target.
  96924. * @param radius Optional. If a cached radius position already exists, overrides default.
  96925. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96926. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96927. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96928. */
  96929. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96930. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96931. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96932. mesh.computeWorldMatrix(true);
  96933. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96934. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96935. };
  96936. /**
  96937. * Targets the given mesh with its children and updates zoom level accordingly.
  96938. * @param mesh The mesh to target.
  96939. * @param radius Optional. If a cached radius position already exists, overrides default.
  96940. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96941. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96942. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96943. */
  96944. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96945. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96946. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96947. mesh.computeWorldMatrix(true);
  96948. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96949. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96950. };
  96951. /**
  96952. * Targets the given meshes with their children and updates zoom level accordingly.
  96953. * @param meshes The mesh to target.
  96954. * @param radius Optional. If a cached radius position already exists, overrides default.
  96955. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96956. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96957. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96958. */
  96959. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96960. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96961. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96962. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96963. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96964. for (var i = 0; i < meshes.length; i++) {
  96965. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96966. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96967. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96968. }
  96969. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96970. };
  96971. /**
  96972. * Targets the given mesh and updates zoom level accordingly.
  96973. * @param mesh The mesh to target.
  96974. * @param radius Optional. If a cached radius position already exists, overrides default.
  96975. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96976. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96977. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96978. */
  96979. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96980. var _this = this;
  96981. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96982. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96983. var zoomTarget;
  96984. if (!this._attachedCamera) {
  96985. return;
  96986. }
  96987. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96988. var bottom = minimumWorld.y;
  96989. var top = maximumWorld.y;
  96990. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96991. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96992. if (focusOnOriginXZ) {
  96993. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96994. }
  96995. else {
  96996. var centerWorld = minimumWorld.add(radiusWorld);
  96997. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96998. }
  96999. if (!this._vectorTransition) {
  97000. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97001. }
  97002. this._betaIsAnimating = true;
  97003. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97004. if (animatable) {
  97005. this._animatables.push(animatable);
  97006. }
  97007. // sets the radius and lower radius bounds
  97008. // Small delta ensures camera is not always at lower zoom limit.
  97009. var radius = 0;
  97010. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97011. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97012. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97013. radius = position;
  97014. }
  97015. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97016. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97017. if (this._attachedCamera.lowerRadiusLimit === null) {
  97018. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97019. }
  97020. }
  97021. // Set sensibilities
  97022. var extend = maximumWorld.subtract(minimumWorld).length();
  97023. this._attachedCamera.panningSensibility = 5000 / extend;
  97024. this._attachedCamera.wheelPrecision = 100 / radius;
  97025. // transition to new radius
  97026. if (!this._radiusTransition) {
  97027. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97028. }
  97029. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97030. _this.stopAllAnimations();
  97031. if (onAnimationEnd) {
  97032. onAnimationEnd();
  97033. }
  97034. if (_this._attachedCamera) {
  97035. _this._attachedCamera.storeState();
  97036. }
  97037. });
  97038. if (animatable) {
  97039. this._animatables.push(animatable);
  97040. }
  97041. };
  97042. /**
  97043. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97044. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97045. * frustum width.
  97046. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97047. * to fully enclose the mesh in the viewing frustum.
  97048. */
  97049. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97050. var size = maximumWorld.subtract(minimumWorld);
  97051. var boxVectorGlobalDiagonal = size.length();
  97052. var frustumSlope = this._getFrustumSlope();
  97053. // Formula for setting distance
  97054. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97055. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97056. // Horizon distance
  97057. var radius = radiusWithoutFraming * this._radiusScale;
  97058. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97059. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97060. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97061. var camera = this._attachedCamera;
  97062. if (!camera) {
  97063. return 0;
  97064. }
  97065. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97066. // Don't exceed the requested limit
  97067. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97068. }
  97069. // Don't exceed the upper radius limit
  97070. if (camera.upperRadiusLimit) {
  97071. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97072. }
  97073. return distance;
  97074. };
  97075. /**
  97076. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97077. * is automatically returned to its default position (expected to be above ground plane).
  97078. */
  97079. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97080. var _this = this;
  97081. if (this._elevationReturnTime < 0) {
  97082. return;
  97083. }
  97084. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97085. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97086. var limitBeta = Math.PI * 0.5;
  97087. // Bring the camera back up if below the ground plane
  97088. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97089. this._betaIsAnimating = true;
  97090. //Transition to new position
  97091. this.stopAllAnimations();
  97092. if (!this._betaTransition) {
  97093. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97094. }
  97095. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97096. _this._clearAnimationLocks();
  97097. _this.stopAllAnimations();
  97098. });
  97099. if (animatabe) {
  97100. this._animatables.push(animatabe);
  97101. }
  97102. }
  97103. };
  97104. /**
  97105. * Returns the frustum slope based on the canvas ratio and camera FOV
  97106. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  97107. */
  97108. FramingBehavior.prototype._getFrustumSlope = function () {
  97109. // Calculate the viewport ratio
  97110. // Aspect Ratio is Height/Width.
  97111. var camera = this._attachedCamera;
  97112. if (!camera) {
  97113. return BABYLON.Vector2.Zero();
  97114. }
  97115. var engine = camera.getScene().getEngine();
  97116. var aspectRatio = engine.getAspectRatio(camera);
  97117. // Camera FOV is the vertical field of view (top-bottom) in radians.
  97118. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  97119. var frustumSlopeY = Math.tan(camera.fov / 2);
  97120. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  97121. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  97122. // along the forward vector.
  97123. var frustumSlopeX = frustumSlopeY * aspectRatio;
  97124. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  97125. };
  97126. /**
  97127. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  97128. */
  97129. FramingBehavior.prototype._clearAnimationLocks = function () {
  97130. this._betaIsAnimating = false;
  97131. };
  97132. /**
  97133. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97134. */
  97135. FramingBehavior.prototype._applyUserInteraction = function () {
  97136. if (this.isUserIsMoving) {
  97137. this._lastInteractionTime = BABYLON.Tools.Now;
  97138. this.stopAllAnimations();
  97139. this._clearAnimationLocks();
  97140. }
  97141. };
  97142. /**
  97143. * Stops and removes all animations that have been applied to the camera
  97144. */
  97145. FramingBehavior.prototype.stopAllAnimations = function () {
  97146. if (this._attachedCamera) {
  97147. this._attachedCamera.animations = [];
  97148. }
  97149. while (this._animatables.length) {
  97150. if (this._animatables[0]) {
  97151. this._animatables[0].onAnimationEnd = null;
  97152. this._animatables[0].stop();
  97153. }
  97154. this._animatables.shift();
  97155. }
  97156. };
  97157. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  97158. /**
  97159. * Gets a value indicating if the user is moving the camera
  97160. */
  97161. get: function () {
  97162. if (!this._attachedCamera) {
  97163. return false;
  97164. }
  97165. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97166. this._attachedCamera.inertialBetaOffset !== 0 ||
  97167. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97168. this._attachedCamera.inertialPanningX !== 0 ||
  97169. this._attachedCamera.inertialPanningY !== 0 ||
  97170. this._isPointerDown;
  97171. },
  97172. enumerable: true,
  97173. configurable: true
  97174. });
  97175. /**
  97176. * The easing function used by animations
  97177. */
  97178. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  97179. /**
  97180. * The easing mode used by animations
  97181. */
  97182. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  97183. // Statics
  97184. /**
  97185. * The camera can move all the way towards the mesh.
  97186. */
  97187. FramingBehavior.IgnoreBoundsSizeMode = 0;
  97188. /**
  97189. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  97190. */
  97191. FramingBehavior.FitFrustumSidesMode = 1;
  97192. return FramingBehavior;
  97193. }());
  97194. BABYLON.FramingBehavior = FramingBehavior;
  97195. })(BABYLON || (BABYLON = {}));
  97196. //# sourceMappingURL=babylon.framingBehavior.js.map
  97197. var BABYLON;
  97198. (function (BABYLON) {
  97199. /**
  97200. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97201. */
  97202. var BouncingBehavior = /** @class */ (function () {
  97203. function BouncingBehavior() {
  97204. /**
  97205. * The duration of the animation, in milliseconds
  97206. */
  97207. this.transitionDuration = 450;
  97208. /**
  97209. * Length of the distance animated by the transition when lower radius is reached
  97210. */
  97211. this.lowerRadiusTransitionRange = 2;
  97212. /**
  97213. * Length of the distance animated by the transition when upper radius is reached
  97214. */
  97215. this.upperRadiusTransitionRange = -2;
  97216. this._autoTransitionRange = false;
  97217. // Animations
  97218. this._radiusIsAnimating = false;
  97219. this._radiusBounceTransition = null;
  97220. this._animatables = new Array();
  97221. }
  97222. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97223. get: function () {
  97224. return "Bouncing";
  97225. },
  97226. enumerable: true,
  97227. configurable: true
  97228. });
  97229. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97230. /**
  97231. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97232. */
  97233. get: function () {
  97234. return this._autoTransitionRange;
  97235. },
  97236. /**
  97237. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97238. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97239. */
  97240. set: function (value) {
  97241. var _this = this;
  97242. if (this._autoTransitionRange === value) {
  97243. return;
  97244. }
  97245. this._autoTransitionRange = value;
  97246. var camera = this._attachedCamera;
  97247. if (!camera) {
  97248. return;
  97249. }
  97250. if (value) {
  97251. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97252. if (!mesh) {
  97253. return;
  97254. }
  97255. mesh.computeWorldMatrix(true);
  97256. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97257. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97258. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97259. });
  97260. }
  97261. else if (this._onMeshTargetChangedObserver) {
  97262. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97263. }
  97264. },
  97265. enumerable: true,
  97266. configurable: true
  97267. });
  97268. BouncingBehavior.prototype.init = function () {
  97269. // Do notihng
  97270. };
  97271. BouncingBehavior.prototype.attach = function (camera) {
  97272. var _this = this;
  97273. this._attachedCamera = camera;
  97274. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97275. if (!_this._attachedCamera) {
  97276. return;
  97277. }
  97278. // Add the bounce animation to the lower radius limit
  97279. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97280. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97281. }
  97282. // Add the bounce animation to the upper radius limit
  97283. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97284. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97285. }
  97286. });
  97287. };
  97288. BouncingBehavior.prototype.detach = function () {
  97289. if (!this._attachedCamera) {
  97290. return;
  97291. }
  97292. if (this._onAfterCheckInputsObserver) {
  97293. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97294. }
  97295. if (this._onMeshTargetChangedObserver) {
  97296. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97297. }
  97298. this._attachedCamera = null;
  97299. };
  97300. /**
  97301. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97302. * @param radiusLimit The limit to check against.
  97303. * @return Bool to indicate if at limit.
  97304. */
  97305. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97306. if (!this._attachedCamera) {
  97307. return false;
  97308. }
  97309. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97310. return true;
  97311. }
  97312. return false;
  97313. };
  97314. /**
  97315. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97316. * @param radiusDelta The delta by which to animate to. Can be negative.
  97317. */
  97318. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97319. var _this = this;
  97320. if (!this._attachedCamera) {
  97321. return;
  97322. }
  97323. if (!this._radiusBounceTransition) {
  97324. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97325. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97326. }
  97327. // Prevent zoom until bounce has completed
  97328. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97329. this._attachedCamera.wheelPrecision = Infinity;
  97330. this._attachedCamera.inertialRadiusOffset = 0;
  97331. // Animate to the radius limit
  97332. this.stopAllAnimations();
  97333. this._radiusIsAnimating = true;
  97334. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97335. if (animatable) {
  97336. this._animatables.push(animatable);
  97337. }
  97338. };
  97339. /**
  97340. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97341. */
  97342. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97343. this._radiusIsAnimating = false;
  97344. if (this._attachedCamera) {
  97345. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97346. }
  97347. };
  97348. /**
  97349. * Stops and removes all animations that have been applied to the camera
  97350. */
  97351. BouncingBehavior.prototype.stopAllAnimations = function () {
  97352. if (this._attachedCamera) {
  97353. this._attachedCamera.animations = [];
  97354. }
  97355. while (this._animatables.length) {
  97356. this._animatables[0].onAnimationEnd = null;
  97357. this._animatables[0].stop();
  97358. this._animatables.shift();
  97359. }
  97360. };
  97361. /**
  97362. * The easing function used by animations
  97363. */
  97364. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97365. /**
  97366. * The easing mode used by animations
  97367. */
  97368. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97369. return BouncingBehavior;
  97370. }());
  97371. BABYLON.BouncingBehavior = BouncingBehavior;
  97372. })(BABYLON || (BABYLON = {}));
  97373. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97374. var BABYLON;
  97375. (function (BABYLON) {
  97376. var AutoRotationBehavior = /** @class */ (function () {
  97377. function AutoRotationBehavior() {
  97378. this._zoomStopsAnimation = false;
  97379. this._idleRotationSpeed = 0.05;
  97380. this._idleRotationWaitTime = 2000;
  97381. this._idleRotationSpinupTime = 2000;
  97382. this._isPointerDown = false;
  97383. this._lastFrameTime = null;
  97384. this._lastInteractionTime = -Infinity;
  97385. this._cameraRotationSpeed = 0;
  97386. this._lastFrameRadius = 0;
  97387. }
  97388. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97389. get: function () {
  97390. return "AutoRotation";
  97391. },
  97392. enumerable: true,
  97393. configurable: true
  97394. });
  97395. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97396. /**
  97397. * Gets the flag that indicates if user zooming should stop animation.
  97398. */
  97399. get: function () {
  97400. return this._zoomStopsAnimation;
  97401. },
  97402. /**
  97403. * Sets the flag that indicates if user zooming should stop animation.
  97404. */
  97405. set: function (flag) {
  97406. this._zoomStopsAnimation = flag;
  97407. },
  97408. enumerable: true,
  97409. configurable: true
  97410. });
  97411. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97412. /**
  97413. * Gets the default speed at which the camera rotates around the model.
  97414. */
  97415. get: function () {
  97416. return this._idleRotationSpeed;
  97417. },
  97418. /**
  97419. * Sets the default speed at which the camera rotates around the model.
  97420. */
  97421. set: function (speed) {
  97422. this._idleRotationSpeed = speed;
  97423. },
  97424. enumerable: true,
  97425. configurable: true
  97426. });
  97427. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97428. /**
  97429. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97430. */
  97431. get: function () {
  97432. return this._idleRotationWaitTime;
  97433. },
  97434. /**
  97435. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97436. */
  97437. set: function (time) {
  97438. this._idleRotationWaitTime = time;
  97439. },
  97440. enumerable: true,
  97441. configurable: true
  97442. });
  97443. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97444. /**
  97445. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97446. */
  97447. get: function () {
  97448. return this._idleRotationSpinupTime;
  97449. },
  97450. /**
  97451. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97452. */
  97453. set: function (time) {
  97454. this._idleRotationSpinupTime = time;
  97455. },
  97456. enumerable: true,
  97457. configurable: true
  97458. });
  97459. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97460. /**
  97461. * Gets a value indicating if the camera is currently rotating because of this behavior
  97462. */
  97463. get: function () {
  97464. return Math.abs(this._cameraRotationSpeed) > 0;
  97465. },
  97466. enumerable: true,
  97467. configurable: true
  97468. });
  97469. AutoRotationBehavior.prototype.init = function () {
  97470. // Do notihng
  97471. };
  97472. AutoRotationBehavior.prototype.attach = function (camera) {
  97473. var _this = this;
  97474. this._attachedCamera = camera;
  97475. var scene = this._attachedCamera.getScene();
  97476. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97477. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97478. _this._isPointerDown = true;
  97479. return;
  97480. }
  97481. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97482. _this._isPointerDown = false;
  97483. }
  97484. });
  97485. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97486. var now = BABYLON.Tools.Now;
  97487. var dt = 0;
  97488. if (_this._lastFrameTime != null) {
  97489. dt = now - _this._lastFrameTime;
  97490. }
  97491. _this._lastFrameTime = now;
  97492. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97493. _this._applyUserInteraction();
  97494. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97495. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97496. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97497. // Step camera rotation by rotation speed
  97498. if (_this._attachedCamera) {
  97499. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97500. }
  97501. });
  97502. };
  97503. AutoRotationBehavior.prototype.detach = function () {
  97504. if (!this._attachedCamera) {
  97505. return;
  97506. }
  97507. var scene = this._attachedCamera.getScene();
  97508. if (this._onPrePointerObservableObserver) {
  97509. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97510. }
  97511. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97512. this._attachedCamera = null;
  97513. };
  97514. /**
  97515. * Returns true if user is scrolling.
  97516. * @return true if user is scrolling.
  97517. */
  97518. AutoRotationBehavior.prototype._userIsZooming = function () {
  97519. if (!this._attachedCamera) {
  97520. return false;
  97521. }
  97522. return this._attachedCamera.inertialRadiusOffset !== 0;
  97523. };
  97524. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97525. if (!this._attachedCamera) {
  97526. return false;
  97527. }
  97528. var zoomHasHitLimit = false;
  97529. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97530. zoomHasHitLimit = true;
  97531. }
  97532. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97533. this._lastFrameRadius = this._attachedCamera.radius;
  97534. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97535. };
  97536. /**
  97537. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97538. */
  97539. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97540. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97541. this._lastInteractionTime = BABYLON.Tools.Now;
  97542. }
  97543. };
  97544. // Tools
  97545. AutoRotationBehavior.prototype._userIsMoving = function () {
  97546. if (!this._attachedCamera) {
  97547. return false;
  97548. }
  97549. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97550. this._attachedCamera.inertialBetaOffset !== 0 ||
  97551. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97552. this._attachedCamera.inertialPanningX !== 0 ||
  97553. this._attachedCamera.inertialPanningY !== 0 ||
  97554. this._isPointerDown;
  97555. };
  97556. return AutoRotationBehavior;
  97557. }());
  97558. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97559. })(BABYLON || (BABYLON = {}));
  97560. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97561. var BABYLON;
  97562. (function (BABYLON) {
  97563. var NullEngineOptions = /** @class */ (function () {
  97564. function NullEngineOptions() {
  97565. this.renderWidth = 512;
  97566. this.renderHeight = 256;
  97567. this.textureSize = 512;
  97568. this.deterministicLockstep = false;
  97569. this.lockstepMaxSteps = 4;
  97570. }
  97571. return NullEngineOptions;
  97572. }());
  97573. BABYLON.NullEngineOptions = NullEngineOptions;
  97574. /**
  97575. * The null engine class provides support for headless version of babylon.js.
  97576. * This can be used in server side scenario or for testing purposes
  97577. */
  97578. var NullEngine = /** @class */ (function (_super) {
  97579. __extends(NullEngine, _super);
  97580. function NullEngine(options) {
  97581. if (options === void 0) { options = new NullEngineOptions(); }
  97582. var _this = _super.call(this, null) || this;
  97583. if (options.deterministicLockstep === undefined) {
  97584. options.deterministicLockstep = false;
  97585. }
  97586. if (options.lockstepMaxSteps === undefined) {
  97587. options.lockstepMaxSteps = 4;
  97588. }
  97589. _this._options = options;
  97590. // Init caps
  97591. // We consider we are on a webgl1 capable device
  97592. _this._caps = new BABYLON.EngineCapabilities();
  97593. _this._caps.maxTexturesImageUnits = 16;
  97594. _this._caps.maxVertexTextureImageUnits = 16;
  97595. _this._caps.maxTextureSize = 512;
  97596. _this._caps.maxCubemapTextureSize = 512;
  97597. _this._caps.maxRenderTextureSize = 512;
  97598. _this._caps.maxVertexAttribs = 16;
  97599. _this._caps.maxVaryingVectors = 16;
  97600. _this._caps.maxFragmentUniformVectors = 16;
  97601. _this._caps.maxVertexUniformVectors = 16;
  97602. // Extensions
  97603. _this._caps.standardDerivatives = false;
  97604. _this._caps.astc = null;
  97605. _this._caps.s3tc = null;
  97606. _this._caps.pvrtc = null;
  97607. _this._caps.etc1 = null;
  97608. _this._caps.etc2 = null;
  97609. _this._caps.textureAnisotropicFilterExtension = null;
  97610. _this._caps.maxAnisotropy = 0;
  97611. _this._caps.uintIndices = false;
  97612. _this._caps.fragmentDepthSupported = false;
  97613. _this._caps.highPrecisionShaderSupported = true;
  97614. _this._caps.colorBufferFloat = false;
  97615. _this._caps.textureFloat = false;
  97616. _this._caps.textureFloatLinearFiltering = false;
  97617. _this._caps.textureFloatRender = false;
  97618. _this._caps.textureHalfFloat = false;
  97619. _this._caps.textureHalfFloatLinearFiltering = false;
  97620. _this._caps.textureHalfFloatRender = false;
  97621. _this._caps.textureLOD = false;
  97622. _this._caps.drawBuffersExtension = false;
  97623. _this._caps.depthTextureExtension = false;
  97624. _this._caps.vertexArrayObject = false;
  97625. _this._caps.instancedArrays = false;
  97626. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97627. // Wrappers
  97628. if (typeof URL === "undefined") {
  97629. URL = {
  97630. createObjectURL: function () { },
  97631. revokeObjectURL: function () { }
  97632. };
  97633. }
  97634. if (typeof Blob === "undefined") {
  97635. Blob = function () { };
  97636. }
  97637. return _this;
  97638. }
  97639. NullEngine.prototype.isDeterministicLockStep = function () {
  97640. return this._options.deterministicLockstep;
  97641. };
  97642. NullEngine.prototype.getLockstepMaxSteps = function () {
  97643. return this._options.lockstepMaxSteps;
  97644. };
  97645. NullEngine.prototype.getHardwareScalingLevel = function () {
  97646. return 1.0;
  97647. };
  97648. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97649. return {
  97650. capacity: 0,
  97651. references: 1,
  97652. is32Bits: false
  97653. };
  97654. };
  97655. NullEngine.prototype.createIndexBuffer = function (indices) {
  97656. return {
  97657. capacity: 0,
  97658. references: 1,
  97659. is32Bits: false
  97660. };
  97661. };
  97662. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97663. if (stencil === void 0) { stencil = false; }
  97664. };
  97665. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97666. if (useScreen === void 0) { useScreen = false; }
  97667. if (!useScreen && this._currentRenderTarget) {
  97668. return this._currentRenderTarget.width;
  97669. }
  97670. return this._options.renderWidth;
  97671. };
  97672. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97673. if (useScreen === void 0) { useScreen = false; }
  97674. if (!useScreen && this._currentRenderTarget) {
  97675. return this._currentRenderTarget.height;
  97676. }
  97677. return this._options.renderHeight;
  97678. };
  97679. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97680. this._cachedViewport = viewport;
  97681. };
  97682. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97683. return {
  97684. transformFeedback: null,
  97685. __SPECTOR_rebuildProgram: null
  97686. };
  97687. };
  97688. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97689. return [];
  97690. };
  97691. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97692. return [];
  97693. };
  97694. NullEngine.prototype.bindSamplers = function (effect) {
  97695. this._currentEffect = null;
  97696. };
  97697. NullEngine.prototype.enableEffect = function (effect) {
  97698. this._currentEffect = effect;
  97699. if (effect.onBind) {
  97700. effect.onBind(effect);
  97701. }
  97702. effect.onBindObservable.notifyObservers(effect);
  97703. };
  97704. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97705. if (zOffset === void 0) { zOffset = 0; }
  97706. if (reverseSide === void 0) { reverseSide = false; }
  97707. };
  97708. NullEngine.prototype.setIntArray = function (uniform, array) {
  97709. };
  97710. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97711. };
  97712. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97713. };
  97714. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97715. };
  97716. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97717. };
  97718. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97719. };
  97720. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97721. };
  97722. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97723. };
  97724. NullEngine.prototype.setArray = function (uniform, array) {
  97725. };
  97726. NullEngine.prototype.setArray2 = function (uniform, array) {
  97727. };
  97728. NullEngine.prototype.setArray3 = function (uniform, array) {
  97729. };
  97730. NullEngine.prototype.setArray4 = function (uniform, array) {
  97731. };
  97732. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97733. };
  97734. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97735. };
  97736. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97737. };
  97738. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97739. };
  97740. NullEngine.prototype.setFloat = function (uniform, value) {
  97741. };
  97742. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97743. };
  97744. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97745. };
  97746. NullEngine.prototype.setBool = function (uniform, bool) {
  97747. };
  97748. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97749. };
  97750. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97751. };
  97752. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97753. };
  97754. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97755. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97756. if (this._alphaMode === mode) {
  97757. return;
  97758. }
  97759. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97760. if (!noDepthWriteChange) {
  97761. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97762. }
  97763. this._alphaMode = mode;
  97764. };
  97765. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97766. };
  97767. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97768. if (this.preventCacheWipeBetweenFrames) {
  97769. return;
  97770. }
  97771. this.resetTextureCache();
  97772. this._currentEffect = null;
  97773. if (bruteForce) {
  97774. this._currentProgram = null;
  97775. this._stencilState.reset();
  97776. this._depthCullingState.reset();
  97777. this._alphaState.reset();
  97778. }
  97779. this._cachedVertexBuffers = null;
  97780. this._cachedIndexBuffer = null;
  97781. this._cachedEffectForVertexBuffers = null;
  97782. };
  97783. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97784. };
  97785. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97786. };
  97787. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97788. };
  97789. NullEngine.prototype._createTexture = function () {
  97790. return {};
  97791. };
  97792. NullEngine.prototype._releaseTexture = function (texture) {
  97793. };
  97794. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97796. if (onLoad === void 0) { onLoad = null; }
  97797. if (onError === void 0) { onError = null; }
  97798. if (buffer === void 0) { buffer = null; }
  97799. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97800. var url = String(urlArg);
  97801. texture.url = url;
  97802. texture.generateMipMaps = !noMipmap;
  97803. texture.samplingMode = samplingMode;
  97804. texture.invertY = invertY;
  97805. texture.baseWidth = this._options.textureSize;
  97806. texture.baseHeight = this._options.textureSize;
  97807. texture.width = this._options.textureSize;
  97808. texture.height = this._options.textureSize;
  97809. if (format) {
  97810. texture.format = format;
  97811. }
  97812. texture.isReady = true;
  97813. if (onLoad) {
  97814. onLoad();
  97815. }
  97816. this._internalTexturesCache.push(texture);
  97817. return texture;
  97818. };
  97819. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97820. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97821. if (options !== undefined && typeof options === "object") {
  97822. fullOptions.generateMipMaps = options.generateMipMaps;
  97823. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97824. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97825. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97826. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97827. }
  97828. else {
  97829. fullOptions.generateMipMaps = options;
  97830. fullOptions.generateDepthBuffer = true;
  97831. fullOptions.generateStencilBuffer = false;
  97832. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97833. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97834. }
  97835. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97836. var width = size.width || size;
  97837. var height = size.height || size;
  97838. texture._depthStencilBuffer = {};
  97839. texture._framebuffer = {};
  97840. texture.baseWidth = width;
  97841. texture.baseHeight = height;
  97842. texture.width = width;
  97843. texture.height = height;
  97844. texture.isReady = true;
  97845. texture.samples = 1;
  97846. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97847. texture.samplingMode = fullOptions.samplingMode;
  97848. texture.type = fullOptions.type;
  97849. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97850. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97851. this._internalTexturesCache.push(texture);
  97852. return texture;
  97853. };
  97854. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97855. texture.samplingMode = samplingMode;
  97856. };
  97857. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97858. if (this._currentRenderTarget) {
  97859. this.unBindFramebuffer(this._currentRenderTarget);
  97860. }
  97861. this._currentRenderTarget = texture;
  97862. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97863. if (this._cachedViewport && !forceFullscreenViewport) {
  97864. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97865. }
  97866. };
  97867. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97868. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97869. this._currentRenderTarget = null;
  97870. if (onBeforeUnbind) {
  97871. if (texture._MSAAFramebuffer) {
  97872. this._currentFramebuffer = texture._framebuffer;
  97873. }
  97874. onBeforeUnbind();
  97875. }
  97876. this._currentFramebuffer = null;
  97877. };
  97878. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97879. var vbo = {
  97880. capacity: 1,
  97881. references: 1,
  97882. is32Bits: false
  97883. };
  97884. return vbo;
  97885. };
  97886. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97887. if (offset === void 0) { offset = 0; }
  97888. };
  97889. /**
  97890. * Updates a dynamic vertex buffer.
  97891. * @param vertexBuffer the vertex buffer to update
  97892. * @param data the data used to update the vertex buffer
  97893. * @param byteOffset the byte offset of the data (optional)
  97894. * @param byteLength the byte length of the data (optional)
  97895. */
  97896. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97897. };
  97898. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97899. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97900. this._boundTexturesCache[this._activeChannel] = texture;
  97901. }
  97902. };
  97903. NullEngine.prototype._bindTexture = function (channel, texture) {
  97904. if (channel < 0) {
  97905. return;
  97906. }
  97907. this._bindTextureDirectly(0, texture);
  97908. };
  97909. NullEngine.prototype._releaseBuffer = function (buffer) {
  97910. buffer.references--;
  97911. if (buffer.references === 0) {
  97912. return true;
  97913. }
  97914. return false;
  97915. };
  97916. NullEngine.prototype.releaseEffects = function () {
  97917. };
  97918. return NullEngine;
  97919. }(BABYLON.Engine));
  97920. BABYLON.NullEngine = NullEngine;
  97921. })(BABYLON || (BABYLON = {}));
  97922. //# sourceMappingURL=babylon.nullEngine.js.map
  97923. var BABYLON;
  97924. (function (BABYLON) {
  97925. /**
  97926. * This class can be used to get instrumentation data from a Babylon engine
  97927. */
  97928. var EngineInstrumentation = /** @class */ (function () {
  97929. function EngineInstrumentation(engine) {
  97930. this.engine = engine;
  97931. this._captureGPUFrameTime = false;
  97932. this._gpuFrameTime = new BABYLON.PerfCounter();
  97933. this._captureShaderCompilationTime = false;
  97934. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97935. // Observers
  97936. this._onBeginFrameObserver = null;
  97937. this._onEndFrameObserver = null;
  97938. this._onBeforeShaderCompilationObserver = null;
  97939. this._onAfterShaderCompilationObserver = null;
  97940. }
  97941. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97942. // Properties
  97943. /**
  97944. * Gets the perf counter used for GPU frame time
  97945. */
  97946. get: function () {
  97947. return this._gpuFrameTime;
  97948. },
  97949. enumerable: true,
  97950. configurable: true
  97951. });
  97952. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97953. /**
  97954. * Gets the GPU frame time capture status
  97955. */
  97956. get: function () {
  97957. return this._captureGPUFrameTime;
  97958. },
  97959. /**
  97960. * Enable or disable the GPU frame time capture
  97961. */
  97962. set: function (value) {
  97963. var _this = this;
  97964. if (value === this._captureGPUFrameTime) {
  97965. return;
  97966. }
  97967. this._captureGPUFrameTime = value;
  97968. if (value) {
  97969. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97970. if (!_this._gpuFrameTimeToken) {
  97971. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97972. }
  97973. });
  97974. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97975. if (!_this._gpuFrameTimeToken) {
  97976. return;
  97977. }
  97978. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97979. if (time > -1) {
  97980. _this._gpuFrameTimeToken = null;
  97981. _this._gpuFrameTime.fetchNewFrame();
  97982. _this._gpuFrameTime.addCount(time, true);
  97983. }
  97984. });
  97985. }
  97986. else {
  97987. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97988. this._onBeginFrameObserver = null;
  97989. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97990. this._onEndFrameObserver = null;
  97991. }
  97992. },
  97993. enumerable: true,
  97994. configurable: true
  97995. });
  97996. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97997. /**
  97998. * Gets the perf counter used for shader compilation time
  97999. */
  98000. get: function () {
  98001. return this._shaderCompilationTime;
  98002. },
  98003. enumerable: true,
  98004. configurable: true
  98005. });
  98006. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98007. /**
  98008. * Gets the shader compilation time capture status
  98009. */
  98010. get: function () {
  98011. return this._captureShaderCompilationTime;
  98012. },
  98013. /**
  98014. * Enable or disable the shader compilation time capture
  98015. */
  98016. set: function (value) {
  98017. var _this = this;
  98018. if (value === this._captureShaderCompilationTime) {
  98019. return;
  98020. }
  98021. this._captureShaderCompilationTime = value;
  98022. if (value) {
  98023. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98024. _this._shaderCompilationTime.fetchNewFrame();
  98025. _this._shaderCompilationTime.beginMonitoring();
  98026. });
  98027. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98028. _this._shaderCompilationTime.endMonitoring();
  98029. });
  98030. }
  98031. else {
  98032. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98033. this._onBeforeShaderCompilationObserver = null;
  98034. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98035. this._onAfterShaderCompilationObserver = null;
  98036. }
  98037. },
  98038. enumerable: true,
  98039. configurable: true
  98040. });
  98041. EngineInstrumentation.prototype.dispose = function () {
  98042. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98043. this._onBeginFrameObserver = null;
  98044. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98045. this._onEndFrameObserver = null;
  98046. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98047. this._onBeforeShaderCompilationObserver = null;
  98048. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98049. this._onAfterShaderCompilationObserver = null;
  98050. this.engine = null;
  98051. };
  98052. return EngineInstrumentation;
  98053. }());
  98054. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98055. })(BABYLON || (BABYLON = {}));
  98056. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98057. var BABYLON;
  98058. (function (BABYLON) {
  98059. /**
  98060. * This class can be used to get instrumentation data from a Babylon engine
  98061. */
  98062. var SceneInstrumentation = /** @class */ (function () {
  98063. function SceneInstrumentation(scene) {
  98064. var _this = this;
  98065. this.scene = scene;
  98066. this._captureActiveMeshesEvaluationTime = false;
  98067. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98068. this._captureRenderTargetsRenderTime = false;
  98069. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98070. this._captureFrameTime = false;
  98071. this._frameTime = new BABYLON.PerfCounter();
  98072. this._captureRenderTime = false;
  98073. this._renderTime = new BABYLON.PerfCounter();
  98074. this._captureInterFrameTime = false;
  98075. this._interFrameTime = new BABYLON.PerfCounter();
  98076. this._captureParticlesRenderTime = false;
  98077. this._particlesRenderTime = new BABYLON.PerfCounter();
  98078. this._captureSpritesRenderTime = false;
  98079. this._spritesRenderTime = new BABYLON.PerfCounter();
  98080. this._capturePhysicsTime = false;
  98081. this._physicsTime = new BABYLON.PerfCounter();
  98082. this._captureAnimationsTime = false;
  98083. this._animationsTime = new BABYLON.PerfCounter();
  98084. // Observers
  98085. this._onBeforeActiveMeshesEvaluationObserver = null;
  98086. this._onAfterActiveMeshesEvaluationObserver = null;
  98087. this._onBeforeRenderTargetsRenderObserver = null;
  98088. this._onAfterRenderTargetsRenderObserver = null;
  98089. this._onAfterRenderObserver = null;
  98090. this._onBeforeDrawPhaseObserver = null;
  98091. this._onAfterDrawPhaseObserver = null;
  98092. this._onBeforeAnimationsObserver = null;
  98093. this._onBeforeParticlesRenderingObserver = null;
  98094. this._onAfterParticlesRenderingObserver = null;
  98095. this._onBeforeSpritesRenderingObserver = null;
  98096. this._onAfterSpritesRenderingObserver = null;
  98097. this._onBeforePhysicsObserver = null;
  98098. this._onAfterPhysicsObserver = null;
  98099. this._onAfterAnimationsObserver = null;
  98100. // Before render
  98101. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  98102. if (_this._captureActiveMeshesEvaluationTime) {
  98103. _this._activeMeshesEvaluationTime.fetchNewFrame();
  98104. }
  98105. if (_this._captureRenderTargetsRenderTime) {
  98106. _this._renderTargetsRenderTime.fetchNewFrame();
  98107. }
  98108. if (_this._captureFrameTime) {
  98109. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  98110. _this._frameTime.beginMonitoring();
  98111. }
  98112. if (_this._captureInterFrameTime) {
  98113. _this._interFrameTime.endMonitoring();
  98114. }
  98115. if (_this._captureParticlesRenderTime) {
  98116. _this._particlesRenderTime.fetchNewFrame();
  98117. }
  98118. if (_this._captureSpritesRenderTime) {
  98119. _this._spritesRenderTime.fetchNewFrame();
  98120. }
  98121. if (_this._captureAnimationsTime) {
  98122. _this._animationsTime.beginMonitoring();
  98123. }
  98124. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  98125. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  98126. });
  98127. // After render
  98128. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  98129. if (_this._captureFrameTime) {
  98130. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  98131. _this._frameTime.endMonitoring();
  98132. }
  98133. if (_this._captureRenderTime) {
  98134. _this._renderTime.endMonitoring(false);
  98135. }
  98136. if (_this._captureInterFrameTime) {
  98137. _this._interFrameTime.beginMonitoring();
  98138. }
  98139. });
  98140. }
  98141. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  98142. // Properties
  98143. /**
  98144. * Gets the perf counter used for active meshes evaluation time
  98145. */
  98146. get: function () {
  98147. return this._activeMeshesEvaluationTime;
  98148. },
  98149. enumerable: true,
  98150. configurable: true
  98151. });
  98152. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  98153. /**
  98154. * Gets the active meshes evaluation time capture status
  98155. */
  98156. get: function () {
  98157. return this._captureActiveMeshesEvaluationTime;
  98158. },
  98159. /**
  98160. * Enable or disable the active meshes evaluation time capture
  98161. */
  98162. set: function (value) {
  98163. var _this = this;
  98164. if (value === this._captureActiveMeshesEvaluationTime) {
  98165. return;
  98166. }
  98167. this._captureActiveMeshesEvaluationTime = value;
  98168. if (value) {
  98169. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  98170. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  98171. _this._activeMeshesEvaluationTime.beginMonitoring();
  98172. });
  98173. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  98174. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  98175. _this._activeMeshesEvaluationTime.endMonitoring();
  98176. });
  98177. }
  98178. else {
  98179. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98180. this._onBeforeActiveMeshesEvaluationObserver = null;
  98181. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98182. this._onAfterActiveMeshesEvaluationObserver = null;
  98183. }
  98184. },
  98185. enumerable: true,
  98186. configurable: true
  98187. });
  98188. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  98189. /**
  98190. * Gets the perf counter used for render targets render time
  98191. */
  98192. get: function () {
  98193. return this._renderTargetsRenderTime;
  98194. },
  98195. enumerable: true,
  98196. configurable: true
  98197. });
  98198. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98199. /**
  98200. * Gets the render targets render time capture status
  98201. */
  98202. get: function () {
  98203. return this._captureRenderTargetsRenderTime;
  98204. },
  98205. /**
  98206. * Enable or disable the render targets render time capture
  98207. */
  98208. set: function (value) {
  98209. var _this = this;
  98210. if (value === this._captureRenderTargetsRenderTime) {
  98211. return;
  98212. }
  98213. this._captureRenderTargetsRenderTime = value;
  98214. if (value) {
  98215. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98216. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98217. _this._renderTargetsRenderTime.beginMonitoring();
  98218. });
  98219. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98220. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98221. _this._renderTargetsRenderTime.endMonitoring(false);
  98222. });
  98223. }
  98224. else {
  98225. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98226. this._onBeforeRenderTargetsRenderObserver = null;
  98227. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98228. this._onAfterRenderTargetsRenderObserver = null;
  98229. }
  98230. },
  98231. enumerable: true,
  98232. configurable: true
  98233. });
  98234. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98235. /**
  98236. * Gets the perf counter used for particles render time
  98237. */
  98238. get: function () {
  98239. return this._particlesRenderTime;
  98240. },
  98241. enumerable: true,
  98242. configurable: true
  98243. });
  98244. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98245. /**
  98246. * Gets the particles render time capture status
  98247. */
  98248. get: function () {
  98249. return this._captureParticlesRenderTime;
  98250. },
  98251. /**
  98252. * Enable or disable the particles render time capture
  98253. */
  98254. set: function (value) {
  98255. var _this = this;
  98256. if (value === this._captureParticlesRenderTime) {
  98257. return;
  98258. }
  98259. this._captureParticlesRenderTime = value;
  98260. if (value) {
  98261. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98262. BABYLON.Tools.StartPerformanceCounter("Particles");
  98263. _this._particlesRenderTime.beginMonitoring();
  98264. });
  98265. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  98266. BABYLON.Tools.EndPerformanceCounter("Particles");
  98267. _this._particlesRenderTime.endMonitoring(false);
  98268. });
  98269. }
  98270. else {
  98271. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98272. this._onBeforeParticlesRenderingObserver = null;
  98273. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98274. this._onAfterParticlesRenderingObserver = null;
  98275. }
  98276. },
  98277. enumerable: true,
  98278. configurable: true
  98279. });
  98280. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98281. /**
  98282. * Gets the perf counter used for sprites render time
  98283. */
  98284. get: function () {
  98285. return this._spritesRenderTime;
  98286. },
  98287. enumerable: true,
  98288. configurable: true
  98289. });
  98290. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98291. /**
  98292. * Gets the sprites render time capture status
  98293. */
  98294. get: function () {
  98295. return this._captureSpritesRenderTime;
  98296. },
  98297. /**
  98298. * Enable or disable the sprites render time capture
  98299. */
  98300. set: function (value) {
  98301. var _this = this;
  98302. if (value === this._captureSpritesRenderTime) {
  98303. return;
  98304. }
  98305. this._captureSpritesRenderTime = value;
  98306. if (value) {
  98307. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98308. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98309. _this._spritesRenderTime.beginMonitoring();
  98310. });
  98311. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98312. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98313. _this._spritesRenderTime.endMonitoring(false);
  98314. });
  98315. }
  98316. else {
  98317. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98318. this._onBeforeSpritesRenderingObserver = null;
  98319. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98320. this._onAfterSpritesRenderingObserver = null;
  98321. }
  98322. },
  98323. enumerable: true,
  98324. configurable: true
  98325. });
  98326. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98327. /**
  98328. * Gets the perf counter used for physics time
  98329. */
  98330. get: function () {
  98331. return this._physicsTime;
  98332. },
  98333. enumerable: true,
  98334. configurable: true
  98335. });
  98336. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98337. /**
  98338. * Gets the physics time capture status
  98339. */
  98340. get: function () {
  98341. return this._capturePhysicsTime;
  98342. },
  98343. /**
  98344. * Enable or disable the physics time capture
  98345. */
  98346. set: function (value) {
  98347. var _this = this;
  98348. if (value === this._capturePhysicsTime) {
  98349. return;
  98350. }
  98351. this._capturePhysicsTime = value;
  98352. if (value) {
  98353. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98354. BABYLON.Tools.StartPerformanceCounter("Physics");
  98355. _this._physicsTime.beginMonitoring();
  98356. });
  98357. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98358. BABYLON.Tools.EndPerformanceCounter("Physics");
  98359. _this._physicsTime.endMonitoring();
  98360. });
  98361. }
  98362. else {
  98363. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98364. this._onBeforePhysicsObserver = null;
  98365. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98366. this._onAfterPhysicsObserver = null;
  98367. }
  98368. },
  98369. enumerable: true,
  98370. configurable: true
  98371. });
  98372. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98373. /**
  98374. * Gets the perf counter used for animations time
  98375. */
  98376. get: function () {
  98377. return this._animationsTime;
  98378. },
  98379. enumerable: true,
  98380. configurable: true
  98381. });
  98382. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98383. /**
  98384. * Gets the animations time capture status
  98385. */
  98386. get: function () {
  98387. return this._captureAnimationsTime;
  98388. },
  98389. /**
  98390. * Enable or disable the animations time capture
  98391. */
  98392. set: function (value) {
  98393. var _this = this;
  98394. if (value === this._captureAnimationsTime) {
  98395. return;
  98396. }
  98397. this._captureAnimationsTime = value;
  98398. if (value) {
  98399. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98400. _this._animationsTime.endMonitoring();
  98401. });
  98402. }
  98403. else {
  98404. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98405. this._onAfterAnimationsObserver = null;
  98406. }
  98407. },
  98408. enumerable: true,
  98409. configurable: true
  98410. });
  98411. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98412. /**
  98413. * Gets the perf counter used for frame time capture
  98414. */
  98415. get: function () {
  98416. return this._frameTime;
  98417. },
  98418. enumerable: true,
  98419. configurable: true
  98420. });
  98421. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98422. /**
  98423. * Gets the frame time capture status
  98424. */
  98425. get: function () {
  98426. return this._captureFrameTime;
  98427. },
  98428. /**
  98429. * Enable or disable the frame time capture
  98430. */
  98431. set: function (value) {
  98432. this._captureFrameTime = value;
  98433. },
  98434. enumerable: true,
  98435. configurable: true
  98436. });
  98437. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98438. /**
  98439. * Gets the perf counter used for inter-frames time capture
  98440. */
  98441. get: function () {
  98442. return this._interFrameTime;
  98443. },
  98444. enumerable: true,
  98445. configurable: true
  98446. });
  98447. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98448. /**
  98449. * Gets the inter-frames time capture status
  98450. */
  98451. get: function () {
  98452. return this._captureInterFrameTime;
  98453. },
  98454. /**
  98455. * Enable or disable the inter-frames time capture
  98456. */
  98457. set: function (value) {
  98458. this._captureInterFrameTime = value;
  98459. },
  98460. enumerable: true,
  98461. configurable: true
  98462. });
  98463. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98464. /**
  98465. * Gets the perf counter used for render time capture
  98466. */
  98467. get: function () {
  98468. return this._renderTime;
  98469. },
  98470. enumerable: true,
  98471. configurable: true
  98472. });
  98473. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98474. /**
  98475. * Gets the render time capture status
  98476. */
  98477. get: function () {
  98478. return this._captureRenderTime;
  98479. },
  98480. /**
  98481. * Enable or disable the render time capture
  98482. */
  98483. set: function (value) {
  98484. var _this = this;
  98485. if (value === this._captureRenderTime) {
  98486. return;
  98487. }
  98488. this._captureRenderTime = value;
  98489. if (value) {
  98490. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98491. _this._renderTime.beginMonitoring();
  98492. BABYLON.Tools.StartPerformanceCounter("Main render");
  98493. });
  98494. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98495. _this._renderTime.endMonitoring(false);
  98496. BABYLON.Tools.EndPerformanceCounter("Main render");
  98497. });
  98498. }
  98499. else {
  98500. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98501. this._onBeforeDrawPhaseObserver = null;
  98502. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98503. this._onAfterDrawPhaseObserver = null;
  98504. }
  98505. },
  98506. enumerable: true,
  98507. configurable: true
  98508. });
  98509. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98510. /**
  98511. * Gets the perf counter used for draw calls
  98512. */
  98513. get: function () {
  98514. return this.scene.getEngine()._drawCalls;
  98515. },
  98516. enumerable: true,
  98517. configurable: true
  98518. });
  98519. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98520. /**
  98521. * Gets the perf counter used for texture collisions
  98522. */
  98523. get: function () {
  98524. return this.scene.getEngine()._textureCollisions;
  98525. },
  98526. enumerable: true,
  98527. configurable: true
  98528. });
  98529. SceneInstrumentation.prototype.dispose = function () {
  98530. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98531. this._onAfterRenderObserver = null;
  98532. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98533. this._onBeforeActiveMeshesEvaluationObserver = null;
  98534. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98535. this._onAfterActiveMeshesEvaluationObserver = null;
  98536. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98537. this._onBeforeRenderTargetsRenderObserver = null;
  98538. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98539. this._onAfterRenderTargetsRenderObserver = null;
  98540. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98541. this._onBeforeAnimationsObserver = null;
  98542. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98543. this._onBeforeParticlesRenderingObserver = null;
  98544. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98545. this._onAfterParticlesRenderingObserver = null;
  98546. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98547. this._onBeforeSpritesRenderingObserver = null;
  98548. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98549. this._onAfterSpritesRenderingObserver = null;
  98550. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98551. this._onBeforeDrawPhaseObserver = null;
  98552. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98553. this._onAfterDrawPhaseObserver = null;
  98554. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98555. this._onBeforePhysicsObserver = null;
  98556. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98557. this._onAfterPhysicsObserver = null;
  98558. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98559. this._onAfterAnimationsObserver = null;
  98560. this.scene = null;
  98561. };
  98562. return SceneInstrumentation;
  98563. }());
  98564. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98565. })(BABYLON || (BABYLON = {}));
  98566. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98567. var BABYLON;
  98568. (function (BABYLON) {
  98569. /**
  98570. * @hidden
  98571. **/
  98572. var _TimeToken = /** @class */ (function () {
  98573. function _TimeToken() {
  98574. this._timeElapsedQueryEnded = false;
  98575. }
  98576. return _TimeToken;
  98577. }());
  98578. BABYLON._TimeToken = _TimeToken;
  98579. })(BABYLON || (BABYLON = {}));
  98580. //# sourceMappingURL=babylon.timeToken.js.map
  98581. var BABYLON;
  98582. (function (BABYLON) {
  98583. /**
  98584. * Background material defines definition.
  98585. * @hidden Mainly internal Use
  98586. */
  98587. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98588. __extends(BackgroundMaterialDefines, _super);
  98589. /**
  98590. * Constructor of the defines.
  98591. */
  98592. function BackgroundMaterialDefines() {
  98593. var _this = _super.call(this) || this;
  98594. /**
  98595. * True if the diffuse texture is in use.
  98596. */
  98597. _this.DIFFUSE = false;
  98598. /**
  98599. * The direct UV channel to use.
  98600. */
  98601. _this.DIFFUSEDIRECTUV = 0;
  98602. /**
  98603. * True if the diffuse texture is in gamma space.
  98604. */
  98605. _this.GAMMADIFFUSE = false;
  98606. /**
  98607. * True if the diffuse texture has opacity in the alpha channel.
  98608. */
  98609. _this.DIFFUSEHASALPHA = false;
  98610. /**
  98611. * True if you want the material to fade to transparent at grazing angle.
  98612. */
  98613. _this.OPACITYFRESNEL = false;
  98614. /**
  98615. * True if an extra blur needs to be added in the reflection.
  98616. */
  98617. _this.REFLECTIONBLUR = false;
  98618. /**
  98619. * True if you want the material to fade to reflection at grazing angle.
  98620. */
  98621. _this.REFLECTIONFRESNEL = false;
  98622. /**
  98623. * True if you want the material to falloff as far as you move away from the scene center.
  98624. */
  98625. _this.REFLECTIONFALLOFF = false;
  98626. /**
  98627. * False if the current Webgl implementation does not support the texture lod extension.
  98628. */
  98629. _this.TEXTURELODSUPPORT = false;
  98630. /**
  98631. * True to ensure the data are premultiplied.
  98632. */
  98633. _this.PREMULTIPLYALPHA = false;
  98634. /**
  98635. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98636. */
  98637. _this.USERGBCOLOR = false;
  98638. /**
  98639. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98640. * stays aligned with the desired configuration.
  98641. */
  98642. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98643. /**
  98644. * True to add noise in order to reduce the banding effect.
  98645. */
  98646. _this.NOISE = false;
  98647. /**
  98648. * is the reflection texture in BGR color scheme?
  98649. * Mainly used to solve a bug in ios10 video tag
  98650. */
  98651. _this.REFLECTIONBGR = false;
  98652. _this.IMAGEPROCESSING = false;
  98653. _this.VIGNETTE = false;
  98654. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98655. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98656. _this.TONEMAPPING = false;
  98657. _this.CONTRAST = false;
  98658. _this.COLORCURVES = false;
  98659. _this.COLORGRADING = false;
  98660. _this.COLORGRADING3D = false;
  98661. _this.SAMPLER3DGREENDEPTH = false;
  98662. _this.SAMPLER3DBGRMAP = false;
  98663. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98664. _this.EXPOSURE = false;
  98665. // Reflection.
  98666. _this.REFLECTION = false;
  98667. _this.REFLECTIONMAP_3D = false;
  98668. _this.REFLECTIONMAP_SPHERICAL = false;
  98669. _this.REFLECTIONMAP_PLANAR = false;
  98670. _this.REFLECTIONMAP_CUBIC = false;
  98671. _this.REFLECTIONMAP_PROJECTION = false;
  98672. _this.REFLECTIONMAP_SKYBOX = false;
  98673. _this.REFLECTIONMAP_EXPLICIT = false;
  98674. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98675. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98676. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98677. _this.INVERTCUBICMAP = false;
  98678. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98679. _this.LODINREFLECTIONALPHA = false;
  98680. _this.GAMMAREFLECTION = false;
  98681. _this.RGBDREFLECTION = false;
  98682. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98683. // Default BJS.
  98684. _this.MAINUV1 = false;
  98685. _this.MAINUV2 = false;
  98686. _this.UV1 = false;
  98687. _this.UV2 = false;
  98688. _this.CLIPPLANE = false;
  98689. _this.POINTSIZE = false;
  98690. _this.FOG = false;
  98691. _this.NORMAL = false;
  98692. _this.NUM_BONE_INFLUENCERS = 0;
  98693. _this.BonesPerMesh = 0;
  98694. _this.INSTANCES = false;
  98695. _this.SHADOWFLOAT = false;
  98696. _this.rebuild();
  98697. return _this;
  98698. }
  98699. return BackgroundMaterialDefines;
  98700. }(BABYLON.MaterialDefines));
  98701. /**
  98702. * Background material used to create an efficient environement around your scene.
  98703. */
  98704. var BackgroundMaterial = /** @class */ (function (_super) {
  98705. __extends(BackgroundMaterial, _super);
  98706. /**
  98707. * Instantiates a Background Material in the given scene
  98708. * @param name The friendly name of the material
  98709. * @param scene The scene to add the material to
  98710. */
  98711. function BackgroundMaterial(name, scene) {
  98712. var _this = _super.call(this, name, scene) || this;
  98713. /**
  98714. * Key light Color (multiply against the environement texture)
  98715. */
  98716. _this.primaryColor = BABYLON.Color3.White();
  98717. _this._primaryColorShadowLevel = 0;
  98718. _this._primaryColorHighlightLevel = 0;
  98719. /**
  98720. * Reflection Texture used in the material.
  98721. * Should be author in a specific way for the best result (refer to the documentation).
  98722. */
  98723. _this.reflectionTexture = null;
  98724. /**
  98725. * Reflection Texture level of blur.
  98726. *
  98727. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98728. * texture twice.
  98729. */
  98730. _this.reflectionBlur = 0;
  98731. /**
  98732. * Diffuse Texture used in the material.
  98733. * Should be author in a specific way for the best result (refer to the documentation).
  98734. */
  98735. _this.diffuseTexture = null;
  98736. _this._shadowLights = null;
  98737. /**
  98738. * Specify the list of lights casting shadow on the material.
  98739. * All scene shadow lights will be included if null.
  98740. */
  98741. _this.shadowLights = null;
  98742. /**
  98743. * Helps adjusting the shadow to a softer level if required.
  98744. * 0 means black shadows and 1 means no shadows.
  98745. */
  98746. _this.shadowLevel = 0;
  98747. /**
  98748. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98749. * It is usually zero but might be interesting to modify according to your setup.
  98750. */
  98751. _this.sceneCenter = BABYLON.Vector3.Zero();
  98752. /**
  98753. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98754. * This helps ensuring a nice transition when the camera goes under the ground.
  98755. */
  98756. _this.opacityFresnel = true;
  98757. /**
  98758. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98759. * This helps adding a mirror texture on the ground.
  98760. */
  98761. _this.reflectionFresnel = false;
  98762. /**
  98763. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98764. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98765. */
  98766. _this.reflectionFalloffDistance = 0.0;
  98767. /**
  98768. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98769. */
  98770. _this.reflectionAmount = 1.0;
  98771. /**
  98772. * This specifies the weight of the reflection at grazing angle.
  98773. */
  98774. _this.reflectionReflectance0 = 0.05;
  98775. /**
  98776. * This specifies the weight of the reflection at a perpendicular point of view.
  98777. */
  98778. _this.reflectionReflectance90 = 0.5;
  98779. /**
  98780. * Helps to directly use the maps channels instead of their level.
  98781. */
  98782. _this.useRGBColor = true;
  98783. /**
  98784. * This helps reducing the banding effect that could occur on the background.
  98785. */
  98786. _this.enableNoise = false;
  98787. _this._fovMultiplier = 1.0;
  98788. /**
  98789. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98790. */
  98791. _this.useEquirectangularFOV = false;
  98792. _this._maxSimultaneousLights = 4;
  98793. /**
  98794. * Number of Simultaneous lights allowed on the material.
  98795. */
  98796. _this.maxSimultaneousLights = 4;
  98797. /**
  98798. * Keep track of the image processing observer to allow dispose and replace.
  98799. */
  98800. _this._imageProcessingObserver = null;
  98801. /**
  98802. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98803. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98804. */
  98805. _this.switchToBGR = false;
  98806. // Temp values kept as cache in the material.
  98807. _this._renderTargets = new BABYLON.SmartArray(16);
  98808. _this._reflectionControls = BABYLON.Vector4.Zero();
  98809. _this._white = BABYLON.Color3.White();
  98810. _this._primaryShadowColor = BABYLON.Color3.Black();
  98811. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98812. // Setup the default processing configuration to the scene.
  98813. _this._attachImageProcessingConfiguration(null);
  98814. _this.getRenderTargetTextures = function () {
  98815. _this._renderTargets.reset();
  98816. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98817. _this._renderTargets.push(_this._diffuseTexture);
  98818. }
  98819. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98820. _this._renderTargets.push(_this._reflectionTexture);
  98821. }
  98822. return _this._renderTargets;
  98823. };
  98824. return _this;
  98825. }
  98826. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98827. /**
  98828. * Experimental Internal Use Only.
  98829. *
  98830. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98831. * This acts as a helper to set the primary color to a more "human friendly" value.
  98832. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98833. * output color as close as possible from the chosen value.
  98834. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98835. * part of lighting setup.)
  98836. */
  98837. get: function () {
  98838. return this.__perceptualColor;
  98839. },
  98840. set: function (value) {
  98841. this.__perceptualColor = value;
  98842. this._computePrimaryColorFromPerceptualColor();
  98843. this._markAllSubMeshesAsLightsDirty();
  98844. },
  98845. enumerable: true,
  98846. configurable: true
  98847. });
  98848. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98849. /**
  98850. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98851. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98852. */
  98853. get: function () {
  98854. return this._primaryColorShadowLevel;
  98855. },
  98856. set: function (value) {
  98857. this._primaryColorShadowLevel = value;
  98858. this._computePrimaryColors();
  98859. this._markAllSubMeshesAsLightsDirty();
  98860. },
  98861. enumerable: true,
  98862. configurable: true
  98863. });
  98864. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98865. /**
  98866. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98867. * The primary color is used at the level chosen to define what the white area would look.
  98868. */
  98869. get: function () {
  98870. return this._primaryColorHighlightLevel;
  98871. },
  98872. set: function (value) {
  98873. this._primaryColorHighlightLevel = value;
  98874. this._computePrimaryColors();
  98875. this._markAllSubMeshesAsLightsDirty();
  98876. },
  98877. enumerable: true,
  98878. configurable: true
  98879. });
  98880. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98881. /**
  98882. * Sets the reflection reflectance fresnel values according to the default standard
  98883. * empirically know to work well :-)
  98884. */
  98885. set: function (value) {
  98886. var reflectionWeight = value;
  98887. if (reflectionWeight < 0.5) {
  98888. reflectionWeight = reflectionWeight * 2.0;
  98889. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98890. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98891. }
  98892. else {
  98893. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98894. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98895. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98896. }
  98897. },
  98898. enumerable: true,
  98899. configurable: true
  98900. });
  98901. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98902. /**
  98903. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98904. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98905. * Recommended to be keep at 1.0 except for special cases.
  98906. */
  98907. get: function () {
  98908. return this._fovMultiplier;
  98909. },
  98910. set: function (value) {
  98911. if (isNaN(value)) {
  98912. value = 1.0;
  98913. }
  98914. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98915. },
  98916. enumerable: true,
  98917. configurable: true
  98918. });
  98919. /**
  98920. * Attaches a new image processing configuration to the PBR Material.
  98921. * @param configuration (if null the scene configuration will be use)
  98922. */
  98923. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98924. var _this = this;
  98925. if (configuration === this._imageProcessingConfiguration) {
  98926. return;
  98927. }
  98928. // Detaches observer.
  98929. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98930. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98931. }
  98932. // Pick the scene configuration if needed.
  98933. if (!configuration) {
  98934. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98935. }
  98936. else {
  98937. this._imageProcessingConfiguration = configuration;
  98938. }
  98939. // Attaches observer.
  98940. if (this._imageProcessingConfiguration) {
  98941. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98942. _this._computePrimaryColorFromPerceptualColor();
  98943. _this._markAllSubMeshesAsImageProcessingDirty();
  98944. });
  98945. }
  98946. };
  98947. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98948. /**
  98949. * Gets the image processing configuration used either in this material.
  98950. */
  98951. get: function () {
  98952. return this._imageProcessingConfiguration;
  98953. },
  98954. /**
  98955. * Sets the Default image processing configuration used either in the this material.
  98956. *
  98957. * If sets to null, the scene one is in use.
  98958. */
  98959. set: function (value) {
  98960. this._attachImageProcessingConfiguration(value);
  98961. // Ensure the effect will be rebuilt.
  98962. this._markAllSubMeshesAsTexturesDirty();
  98963. },
  98964. enumerable: true,
  98965. configurable: true
  98966. });
  98967. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98968. /**
  98969. * Gets wether the color curves effect is enabled.
  98970. */
  98971. get: function () {
  98972. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98973. },
  98974. /**
  98975. * Sets wether the color curves effect is enabled.
  98976. */
  98977. set: function (value) {
  98978. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98979. },
  98980. enumerable: true,
  98981. configurable: true
  98982. });
  98983. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98984. /**
  98985. * Gets wether the color grading effect is enabled.
  98986. */
  98987. get: function () {
  98988. return this.imageProcessingConfiguration.colorGradingEnabled;
  98989. },
  98990. /**
  98991. * Gets wether the color grading effect is enabled.
  98992. */
  98993. set: function (value) {
  98994. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98995. },
  98996. enumerable: true,
  98997. configurable: true
  98998. });
  98999. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99000. /**
  99001. * Gets wether tonemapping is enabled or not.
  99002. */
  99003. get: function () {
  99004. return this._imageProcessingConfiguration.toneMappingEnabled;
  99005. },
  99006. /**
  99007. * Sets wether tonemapping is enabled or not
  99008. */
  99009. set: function (value) {
  99010. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99011. },
  99012. enumerable: true,
  99013. configurable: true
  99014. });
  99015. ;
  99016. ;
  99017. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99018. /**
  99019. * The camera exposure used on this material.
  99020. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99021. * This corresponds to a photographic exposure.
  99022. */
  99023. get: function () {
  99024. return this._imageProcessingConfiguration.exposure;
  99025. },
  99026. /**
  99027. * The camera exposure used on this material.
  99028. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99029. * This corresponds to a photographic exposure.
  99030. */
  99031. set: function (value) {
  99032. this._imageProcessingConfiguration.exposure = value;
  99033. },
  99034. enumerable: true,
  99035. configurable: true
  99036. });
  99037. ;
  99038. ;
  99039. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99040. /**
  99041. * Gets The camera contrast used on this material.
  99042. */
  99043. get: function () {
  99044. return this._imageProcessingConfiguration.contrast;
  99045. },
  99046. /**
  99047. * Sets The camera contrast used on this material.
  99048. */
  99049. set: function (value) {
  99050. this._imageProcessingConfiguration.contrast = value;
  99051. },
  99052. enumerable: true,
  99053. configurable: true
  99054. });
  99055. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  99056. /**
  99057. * Gets the Color Grading 2D Lookup Texture.
  99058. */
  99059. get: function () {
  99060. return this._imageProcessingConfiguration.colorGradingTexture;
  99061. },
  99062. /**
  99063. * Sets the Color Grading 2D Lookup Texture.
  99064. */
  99065. set: function (value) {
  99066. this.imageProcessingConfiguration.colorGradingTexture = value;
  99067. },
  99068. enumerable: true,
  99069. configurable: true
  99070. });
  99071. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  99072. /**
  99073. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99074. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99075. * 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;
  99076. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99077. */
  99078. get: function () {
  99079. return this.imageProcessingConfiguration.colorCurves;
  99080. },
  99081. /**
  99082. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99083. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99084. * 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;
  99085. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99086. */
  99087. set: function (value) {
  99088. this.imageProcessingConfiguration.colorCurves = value;
  99089. },
  99090. enumerable: true,
  99091. configurable: true
  99092. });
  99093. /**
  99094. * The entire material has been created in order to prevent overdraw.
  99095. * @returns false
  99096. */
  99097. BackgroundMaterial.prototype.needAlphaTesting = function () {
  99098. return true;
  99099. };
  99100. /**
  99101. * The entire material has been created in order to prevent overdraw.
  99102. * @returns true if blending is enable
  99103. */
  99104. BackgroundMaterial.prototype.needAlphaBlending = function () {
  99105. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  99106. };
  99107. /**
  99108. * Checks wether the material is ready to be rendered for a given mesh.
  99109. * @param mesh The mesh to render
  99110. * @param subMesh The submesh to check against
  99111. * @param useInstances Specify wether or not the material is used with instances
  99112. * @returns true if all the dependencies are ready (Textures, Effects...)
  99113. */
  99114. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  99115. var _this = this;
  99116. if (useInstances === void 0) { useInstances = false; }
  99117. if (subMesh.effect && this.isFrozen) {
  99118. if (this._wasPreviouslyReady) {
  99119. return true;
  99120. }
  99121. }
  99122. if (!subMesh._materialDefines) {
  99123. subMesh._materialDefines = new BackgroundMaterialDefines();
  99124. }
  99125. var scene = this.getScene();
  99126. var defines = subMesh._materialDefines;
  99127. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  99128. if (defines._renderId === scene.getRenderId()) {
  99129. return true;
  99130. }
  99131. }
  99132. var engine = scene.getEngine();
  99133. // Lights
  99134. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  99135. defines._needNormals = true;
  99136. // Textures
  99137. if (defines._areTexturesDirty) {
  99138. defines._needUVs = false;
  99139. if (scene.texturesEnabled) {
  99140. if (scene.getEngine().getCaps().textureLOD) {
  99141. defines.TEXTURELODSUPPORT = true;
  99142. }
  99143. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99144. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  99145. return false;
  99146. }
  99147. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  99148. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  99149. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  99150. defines.OPACITYFRESNEL = this._opacityFresnel;
  99151. }
  99152. else {
  99153. defines.DIFFUSE = false;
  99154. defines.DIFFUSEHASALPHA = false;
  99155. defines.GAMMADIFFUSE = false;
  99156. defines.OPACITYFRESNEL = false;
  99157. }
  99158. var reflectionTexture = this._reflectionTexture;
  99159. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99160. if (!reflectionTexture.isReadyOrNotBlocking()) {
  99161. return false;
  99162. }
  99163. defines.REFLECTION = true;
  99164. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  99165. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  99166. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  99167. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  99168. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  99169. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  99170. defines.REFLECTIONBGR = this.switchToBGR;
  99171. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  99172. defines.INVERTCUBICMAP = true;
  99173. }
  99174. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  99175. switch (reflectionTexture.coordinatesMode) {
  99176. case BABYLON.Texture.EXPLICIT_MODE:
  99177. defines.REFLECTIONMAP_EXPLICIT = true;
  99178. break;
  99179. case BABYLON.Texture.PLANAR_MODE:
  99180. defines.REFLECTIONMAP_PLANAR = true;
  99181. break;
  99182. case BABYLON.Texture.PROJECTION_MODE:
  99183. defines.REFLECTIONMAP_PROJECTION = true;
  99184. break;
  99185. case BABYLON.Texture.SKYBOX_MODE:
  99186. defines.REFLECTIONMAP_SKYBOX = true;
  99187. break;
  99188. case BABYLON.Texture.SPHERICAL_MODE:
  99189. defines.REFLECTIONMAP_SPHERICAL = true;
  99190. break;
  99191. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  99192. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  99193. break;
  99194. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  99195. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  99196. break;
  99197. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  99198. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99199. break;
  99200. case BABYLON.Texture.CUBIC_MODE:
  99201. case BABYLON.Texture.INVCUBIC_MODE:
  99202. default:
  99203. defines.REFLECTIONMAP_CUBIC = true;
  99204. break;
  99205. }
  99206. if (this.reflectionFresnel) {
  99207. defines.REFLECTIONFRESNEL = true;
  99208. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99209. this._reflectionControls.x = this.reflectionAmount;
  99210. this._reflectionControls.y = this.reflectionReflectance0;
  99211. this._reflectionControls.z = this.reflectionReflectance90;
  99212. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  99213. }
  99214. else {
  99215. defines.REFLECTIONFRESNEL = false;
  99216. defines.REFLECTIONFALLOFF = false;
  99217. }
  99218. }
  99219. else {
  99220. defines.REFLECTION = false;
  99221. defines.REFLECTIONFRESNEL = false;
  99222. defines.REFLECTIONFALLOFF = false;
  99223. defines.REFLECTIONBLUR = false;
  99224. defines.REFLECTIONMAP_3D = false;
  99225. defines.REFLECTIONMAP_SPHERICAL = false;
  99226. defines.REFLECTIONMAP_PLANAR = false;
  99227. defines.REFLECTIONMAP_CUBIC = false;
  99228. defines.REFLECTIONMAP_PROJECTION = false;
  99229. defines.REFLECTIONMAP_SKYBOX = false;
  99230. defines.REFLECTIONMAP_EXPLICIT = false;
  99231. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99232. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99233. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99234. defines.INVERTCUBICMAP = false;
  99235. defines.REFLECTIONMAP_OPPOSITEZ = false;
  99236. defines.LODINREFLECTIONALPHA = false;
  99237. defines.GAMMAREFLECTION = false;
  99238. defines.RGBDREFLECTION = false;
  99239. }
  99240. }
  99241. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  99242. defines.USERGBCOLOR = this._useRGBColor;
  99243. defines.NOISE = this._enableNoise;
  99244. }
  99245. if (defines._areLightsDirty) {
  99246. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  99247. }
  99248. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  99249. if (!this._imageProcessingConfiguration.isReady()) {
  99250. return false;
  99251. }
  99252. this._imageProcessingConfiguration.prepareDefines(defines);
  99253. }
  99254. // Misc.
  99255. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  99256. // Values that need to be evaluated on every frame
  99257. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  99258. // Attribs
  99259. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  99260. if (mesh) {
  99261. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99262. mesh.createNormals(true);
  99263. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  99264. }
  99265. }
  99266. }
  99267. // Get correct effect
  99268. if (defines.isDirty) {
  99269. defines.markAsProcessed();
  99270. scene.resetCachedMaterial();
  99271. // Fallbacks
  99272. var fallbacks = new BABYLON.EffectFallbacks();
  99273. if (defines.FOG) {
  99274. fallbacks.addFallback(0, "FOG");
  99275. }
  99276. if (defines.POINTSIZE) {
  99277. fallbacks.addFallback(1, "POINTSIZE");
  99278. }
  99279. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  99280. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99281. fallbacks.addCPUSkinningFallback(0, mesh);
  99282. }
  99283. //Attributes
  99284. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99285. if (defines.NORMAL) {
  99286. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99287. }
  99288. if (defines.UV1) {
  99289. attribs.push(BABYLON.VertexBuffer.UVKind);
  99290. }
  99291. if (defines.UV2) {
  99292. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99293. }
  99294. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99295. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99296. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99297. "vFogInfos", "vFogColor", "pointSize",
  99298. "vClipPlane", "mBones",
  99299. "vPrimaryColor", "vPrimaryColorShadow",
  99300. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99301. "shadowLevel", "alpha",
  99302. "vBackgroundCenter", "vReflectionControl",
  99303. "vDiffuseInfos", "diffuseMatrix",
  99304. ];
  99305. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99306. var uniformBuffers = ["Material", "Scene"];
  99307. if (BABYLON.ImageProcessingConfiguration) {
  99308. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99309. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99310. }
  99311. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99312. uniformsNames: uniforms,
  99313. uniformBuffersNames: uniformBuffers,
  99314. samplers: samplers,
  99315. defines: defines,
  99316. maxSimultaneousLights: this._maxSimultaneousLights
  99317. });
  99318. var onCompiled = function (effect) {
  99319. if (_this.onCompiled) {
  99320. _this.onCompiled(effect);
  99321. }
  99322. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99323. };
  99324. var join = defines.toString();
  99325. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99326. attributes: attribs,
  99327. uniformsNames: uniforms,
  99328. uniformBuffersNames: uniformBuffers,
  99329. samplers: samplers,
  99330. defines: join,
  99331. fallbacks: fallbacks,
  99332. onCompiled: onCompiled,
  99333. onError: this.onError,
  99334. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99335. }, engine), defines);
  99336. this.buildUniformLayout();
  99337. }
  99338. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99339. return false;
  99340. }
  99341. defines._renderId = scene.getRenderId();
  99342. this._wasPreviouslyReady = true;
  99343. return true;
  99344. };
  99345. /**
  99346. * Compute the primary color according to the chosen perceptual color.
  99347. */
  99348. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99349. if (!this.__perceptualColor) {
  99350. return;
  99351. }
  99352. this._primaryColor.copyFrom(this.__perceptualColor);
  99353. // Revert gamma space.
  99354. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99355. // Revert image processing configuration.
  99356. if (this._imageProcessingConfiguration) {
  99357. // Revert Exposure.
  99358. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99359. }
  99360. this._computePrimaryColors();
  99361. };
  99362. /**
  99363. * Compute the highlights and shadow colors according to their chosen levels.
  99364. */
  99365. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99366. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99367. return;
  99368. }
  99369. // Find the highlight color based on the configuration.
  99370. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99371. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99372. // Find the shadow color based on the configuration.
  99373. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99374. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99375. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99376. };
  99377. /**
  99378. * Build the uniform buffer used in the material.
  99379. */
  99380. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99381. // Order is important !
  99382. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99383. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99384. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99385. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99386. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99387. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99388. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99389. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99390. this._uniformBuffer.addUniform("pointSize", 1);
  99391. this._uniformBuffer.addUniform("shadowLevel", 1);
  99392. this._uniformBuffer.addUniform("alpha", 1);
  99393. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99394. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99395. this._uniformBuffer.create();
  99396. };
  99397. /**
  99398. * Unbind the material.
  99399. */
  99400. BackgroundMaterial.prototype.unbind = function () {
  99401. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99402. this._uniformBuffer.setTexture("diffuseSampler", null);
  99403. }
  99404. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99405. this._uniformBuffer.setTexture("reflectionSampler", null);
  99406. }
  99407. _super.prototype.unbind.call(this);
  99408. };
  99409. /**
  99410. * Bind only the world matrix to the material.
  99411. * @param world The world matrix to bind.
  99412. */
  99413. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99414. this._activeEffect.setMatrix("world", world);
  99415. };
  99416. /**
  99417. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99418. * @param world The world matrix to bind.
  99419. * @param subMesh The submesh to bind for.
  99420. */
  99421. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99422. var scene = this.getScene();
  99423. var defines = subMesh._materialDefines;
  99424. if (!defines) {
  99425. return;
  99426. }
  99427. var effect = subMesh.effect;
  99428. if (!effect) {
  99429. return;
  99430. }
  99431. this._activeEffect = effect;
  99432. // Matrices
  99433. this.bindOnlyWorldMatrix(world);
  99434. // Bones
  99435. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99436. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99437. if (mustRebind) {
  99438. this._uniformBuffer.bindToEffect(effect, "Material");
  99439. this.bindViewProjection(effect);
  99440. var reflectionTexture = this._reflectionTexture;
  99441. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99442. // Texture uniforms
  99443. if (scene.texturesEnabled) {
  99444. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99445. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99446. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99447. }
  99448. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99449. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99450. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99451. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99452. }
  99453. }
  99454. if (this.shadowLevel > 0) {
  99455. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99456. }
  99457. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99458. // Point size
  99459. if (this.pointsCloud) {
  99460. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99461. }
  99462. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99463. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99464. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99465. }
  99466. else {
  99467. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99468. }
  99469. }
  99470. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99471. // Textures
  99472. if (scene.texturesEnabled) {
  99473. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99474. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99475. }
  99476. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99477. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99478. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99479. }
  99480. else if (!defines.REFLECTIONBLUR) {
  99481. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99482. }
  99483. else {
  99484. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99485. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99486. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99487. }
  99488. if (defines.REFLECTIONFRESNEL) {
  99489. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99490. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99491. }
  99492. }
  99493. }
  99494. // Clip plane
  99495. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99496. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99497. }
  99498. if (mustRebind || !this.isFrozen) {
  99499. if (scene.lightsEnabled) {
  99500. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99501. }
  99502. // View
  99503. this.bindView(effect);
  99504. // Fog
  99505. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99506. // image processing
  99507. if (this._imageProcessingConfiguration) {
  99508. this._imageProcessingConfiguration.bind(this._activeEffect);
  99509. }
  99510. }
  99511. this._uniformBuffer.update();
  99512. this._afterBind(mesh);
  99513. };
  99514. /**
  99515. * Dispose the material.
  99516. * @param forceDisposeEffect Force disposal of the associated effect.
  99517. * @param forceDisposeTextures Force disposal of the associated textures.
  99518. */
  99519. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99520. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99521. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99522. if (forceDisposeTextures) {
  99523. if (this.diffuseTexture) {
  99524. this.diffuseTexture.dispose();
  99525. }
  99526. if (this.reflectionTexture) {
  99527. this.reflectionTexture.dispose();
  99528. }
  99529. }
  99530. this._renderTargets.dispose();
  99531. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99532. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99533. }
  99534. _super.prototype.dispose.call(this, forceDisposeEffect);
  99535. };
  99536. /**
  99537. * Clones the material.
  99538. * @param name The cloned name.
  99539. * @returns The cloned material.
  99540. */
  99541. BackgroundMaterial.prototype.clone = function (name) {
  99542. var _this = this;
  99543. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99544. };
  99545. /**
  99546. * Serializes the current material to its JSON representation.
  99547. * @returns The JSON representation.
  99548. */
  99549. BackgroundMaterial.prototype.serialize = function () {
  99550. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99551. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99552. return serializationObject;
  99553. };
  99554. /**
  99555. * Gets the class name of the material
  99556. * @returns "BackgroundMaterial"
  99557. */
  99558. BackgroundMaterial.prototype.getClassName = function () {
  99559. return "BackgroundMaterial";
  99560. };
  99561. /**
  99562. * Parse a JSON input to create back a background material.
  99563. * @param source The JSON data to parse
  99564. * @param scene The scene to create the parsed material in
  99565. * @param rootUrl The root url of the assets the material depends upon
  99566. * @returns the instantiated BackgroundMaterial.
  99567. */
  99568. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99569. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99570. };
  99571. /**
  99572. * Standard reflectance value at parallel view angle.
  99573. */
  99574. BackgroundMaterial.StandardReflectance0 = 0.05;
  99575. /**
  99576. * Standard reflectance value at grazing angle.
  99577. */
  99578. BackgroundMaterial.StandardReflectance90 = 0.5;
  99579. __decorate([
  99580. BABYLON.serializeAsColor3()
  99581. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99582. __decorate([
  99583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99584. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99585. __decorate([
  99586. BABYLON.serializeAsColor3()
  99587. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99588. __decorate([
  99589. BABYLON.serialize()
  99590. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99591. __decorate([
  99592. BABYLON.serialize()
  99593. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99594. __decorate([
  99595. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99596. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99597. __decorate([
  99598. BABYLON.serializeAsTexture()
  99599. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99600. __decorate([
  99601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99602. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99603. __decorate([
  99604. BABYLON.serialize()
  99605. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99606. __decorate([
  99607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99608. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99609. __decorate([
  99610. BABYLON.serializeAsTexture()
  99611. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99612. __decorate([
  99613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99614. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99615. __decorate([
  99616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99617. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99618. __decorate([
  99619. BABYLON.serialize()
  99620. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99621. __decorate([
  99622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99623. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99624. __decorate([
  99625. BABYLON.serializeAsVector3()
  99626. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99627. __decorate([
  99628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99629. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99630. __decorate([
  99631. BABYLON.serialize()
  99632. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99633. __decorate([
  99634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99635. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99636. __decorate([
  99637. BABYLON.serialize()
  99638. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99639. __decorate([
  99640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99641. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99642. __decorate([
  99643. BABYLON.serialize()
  99644. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99645. __decorate([
  99646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99647. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99648. __decorate([
  99649. BABYLON.serialize()
  99650. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99651. __decorate([
  99652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99653. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99654. __decorate([
  99655. BABYLON.serialize()
  99656. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99657. __decorate([
  99658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99659. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99660. __decorate([
  99661. BABYLON.serialize()
  99662. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99663. __decorate([
  99664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99665. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99666. __decorate([
  99667. BABYLON.serialize()
  99668. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99669. __decorate([
  99670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99671. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99672. __decorate([
  99673. BABYLON.serialize()
  99674. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99675. __decorate([
  99676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99677. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99678. __decorate([
  99679. BABYLON.serialize()
  99680. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99681. __decorate([
  99682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99683. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99684. __decorate([
  99685. BABYLON.serializeAsImageProcessingConfiguration()
  99686. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99687. return BackgroundMaterial;
  99688. }(BABYLON.PushMaterial));
  99689. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99690. })(BABYLON || (BABYLON = {}));
  99691. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99692. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99693. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99694. s = arguments[i];
  99695. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99696. t[p] = s[p];
  99697. }
  99698. return t;
  99699. };
  99700. var BABYLON;
  99701. (function (BABYLON) {
  99702. /**
  99703. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99704. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99705. * It also helps with the default setup of your imageProcessing configuration.
  99706. */
  99707. var EnvironmentHelper = /** @class */ (function () {
  99708. /**
  99709. * constructor
  99710. * @param options
  99711. * @param scene The scene to add the material to
  99712. */
  99713. function EnvironmentHelper(options, scene) {
  99714. var _this = this;
  99715. this._errorHandler = function (message, exception) {
  99716. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99717. };
  99718. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99719. this._scene = scene;
  99720. this.onErrorObservable = new BABYLON.Observable();
  99721. this._setupBackground();
  99722. this._setupImageProcessing();
  99723. }
  99724. /**
  99725. * Creates the default options for the helper.
  99726. */
  99727. EnvironmentHelper._getDefaultOptions = function () {
  99728. return {
  99729. createGround: true,
  99730. groundSize: 15,
  99731. groundTexture: this._groundTextureCDNUrl,
  99732. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99733. groundOpacity: 0.9,
  99734. enableGroundShadow: true,
  99735. groundShadowLevel: 0.5,
  99736. enableGroundMirror: false,
  99737. groundMirrorSizeRatio: 0.3,
  99738. groundMirrorBlurKernel: 64,
  99739. groundMirrorAmount: 1,
  99740. groundMirrorFresnelWeight: 1,
  99741. groundMirrorFallOffDistance: 0,
  99742. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99743. groundYBias: 0.00001,
  99744. createSkybox: true,
  99745. skyboxSize: 20,
  99746. skyboxTexture: this._skyboxTextureCDNUrl,
  99747. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99748. backgroundYRotation: 0,
  99749. sizeAuto: true,
  99750. rootPosition: BABYLON.Vector3.Zero(),
  99751. setupImageProcessing: true,
  99752. environmentTexture: this._environmentTextureCDNUrl,
  99753. cameraExposure: 0.8,
  99754. cameraContrast: 1.2,
  99755. toneMappingEnabled: true,
  99756. };
  99757. };
  99758. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99759. /**
  99760. * Gets the root mesh created by the helper.
  99761. */
  99762. get: function () {
  99763. return this._rootMesh;
  99764. },
  99765. enumerable: true,
  99766. configurable: true
  99767. });
  99768. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99769. /**
  99770. * Gets the skybox created by the helper.
  99771. */
  99772. get: function () {
  99773. return this._skybox;
  99774. },
  99775. enumerable: true,
  99776. configurable: true
  99777. });
  99778. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99779. /**
  99780. * Gets the skybox texture created by the helper.
  99781. */
  99782. get: function () {
  99783. return this._skyboxTexture;
  99784. },
  99785. enumerable: true,
  99786. configurable: true
  99787. });
  99788. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99789. /**
  99790. * Gets the skybox material created by the helper.
  99791. */
  99792. get: function () {
  99793. return this._skyboxMaterial;
  99794. },
  99795. enumerable: true,
  99796. configurable: true
  99797. });
  99798. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99799. /**
  99800. * Gets the ground mesh created by the helper.
  99801. */
  99802. get: function () {
  99803. return this._ground;
  99804. },
  99805. enumerable: true,
  99806. configurable: true
  99807. });
  99808. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99809. /**
  99810. * Gets the ground texture created by the helper.
  99811. */
  99812. get: function () {
  99813. return this._groundTexture;
  99814. },
  99815. enumerable: true,
  99816. configurable: true
  99817. });
  99818. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99819. /**
  99820. * Gets the ground mirror created by the helper.
  99821. */
  99822. get: function () {
  99823. return this._groundMirror;
  99824. },
  99825. enumerable: true,
  99826. configurable: true
  99827. });
  99828. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99829. /**
  99830. * Gets the ground mirror render list to helps pushing the meshes
  99831. * you wish in the ground reflection.
  99832. */
  99833. get: function () {
  99834. if (this._groundMirror) {
  99835. return this._groundMirror.renderList;
  99836. }
  99837. return null;
  99838. },
  99839. enumerable: true,
  99840. configurable: true
  99841. });
  99842. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99843. /**
  99844. * Gets the ground material created by the helper.
  99845. */
  99846. get: function () {
  99847. return this._groundMaterial;
  99848. },
  99849. enumerable: true,
  99850. configurable: true
  99851. });
  99852. /**
  99853. * Updates the background according to the new options
  99854. * @param options
  99855. */
  99856. EnvironmentHelper.prototype.updateOptions = function (options) {
  99857. var newOptions = __assign({}, this._options, options);
  99858. if (this._ground && !newOptions.createGround) {
  99859. this._ground.dispose();
  99860. this._ground = null;
  99861. }
  99862. if (this._groundMaterial && !newOptions.createGround) {
  99863. this._groundMaterial.dispose();
  99864. this._groundMaterial = null;
  99865. }
  99866. if (this._groundTexture) {
  99867. if (this._options.groundTexture != newOptions.groundTexture) {
  99868. this._groundTexture.dispose();
  99869. this._groundTexture = null;
  99870. }
  99871. }
  99872. if (this._skybox && !newOptions.createSkybox) {
  99873. this._skybox.dispose();
  99874. this._skybox = null;
  99875. }
  99876. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99877. this._skyboxMaterial.dispose();
  99878. this._skyboxMaterial = null;
  99879. }
  99880. if (this._skyboxTexture) {
  99881. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99882. this._skyboxTexture.dispose();
  99883. this._skyboxTexture = null;
  99884. }
  99885. }
  99886. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99887. this._groundMirror.dispose();
  99888. this._groundMirror = null;
  99889. }
  99890. if (this._scene.environmentTexture) {
  99891. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99892. this._scene.environmentTexture.dispose();
  99893. }
  99894. }
  99895. this._options = newOptions;
  99896. this._setupBackground();
  99897. this._setupImageProcessing();
  99898. };
  99899. /**
  99900. * Sets the primary color of all the available elements.
  99901. * @param color the main color to affect to the ground and the background
  99902. */
  99903. EnvironmentHelper.prototype.setMainColor = function (color) {
  99904. if (this.groundMaterial) {
  99905. this.groundMaterial.primaryColor = color;
  99906. }
  99907. if (this.skyboxMaterial) {
  99908. this.skyboxMaterial.primaryColor = color;
  99909. }
  99910. if (this.groundMirror) {
  99911. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99912. }
  99913. };
  99914. /**
  99915. * Setup the image processing according to the specified options.
  99916. */
  99917. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99918. if (this._options.setupImageProcessing) {
  99919. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99920. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99921. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99922. this._setupEnvironmentTexture();
  99923. }
  99924. };
  99925. /**
  99926. * Setup the environment texture according to the specified options.
  99927. */
  99928. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99929. if (this._scene.environmentTexture) {
  99930. return;
  99931. }
  99932. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99933. this._scene.environmentTexture = this._options.environmentTexture;
  99934. return;
  99935. }
  99936. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99937. this._scene.environmentTexture = environmentTexture;
  99938. };
  99939. /**
  99940. * Setup the background according to the specified options.
  99941. */
  99942. EnvironmentHelper.prototype._setupBackground = function () {
  99943. if (!this._rootMesh) {
  99944. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99945. }
  99946. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99947. var sceneSize = this._getSceneSize();
  99948. if (this._options.createGround) {
  99949. this._setupGround(sceneSize);
  99950. this._setupGroundMaterial();
  99951. this._setupGroundDiffuseTexture();
  99952. if (this._options.enableGroundMirror) {
  99953. this._setupGroundMirrorTexture(sceneSize);
  99954. }
  99955. this._setupMirrorInGroundMaterial();
  99956. }
  99957. if (this._options.createSkybox) {
  99958. this._setupSkybox(sceneSize);
  99959. this._setupSkyboxMaterial();
  99960. this._setupSkyboxReflectionTexture();
  99961. }
  99962. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99963. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99964. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99965. };
  99966. /**
  99967. * Get the scene sizes according to the setup.
  99968. */
  99969. EnvironmentHelper.prototype._getSceneSize = function () {
  99970. var _this = this;
  99971. var groundSize = this._options.groundSize;
  99972. var skyboxSize = this._options.skyboxSize;
  99973. var rootPosition = this._options.rootPosition;
  99974. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99975. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99976. }
  99977. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99978. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99979. });
  99980. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99981. if (this._options.sizeAuto) {
  99982. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99983. this._scene.activeCamera.upperRadiusLimit) {
  99984. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99985. skyboxSize = groundSize;
  99986. }
  99987. var sceneDiagonalLenght = sceneDiagonal.length();
  99988. if (sceneDiagonalLenght > groundSize) {
  99989. groundSize = sceneDiagonalLenght * 2;
  99990. skyboxSize = groundSize;
  99991. }
  99992. // 10 % bigger.
  99993. groundSize *= 1.1;
  99994. skyboxSize *= 1.5;
  99995. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99996. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99997. }
  99998. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99999. };
  100000. /**
  100001. * Setup the ground according to the specified options.
  100002. */
  100003. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100004. var _this = this;
  100005. if (!this._ground) {
  100006. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100007. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100008. this._ground.parent = this._rootMesh;
  100009. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100010. }
  100011. this._ground.receiveShadows = this._options.enableGroundShadow;
  100012. };
  100013. /**
  100014. * Setup the ground material according to the specified options.
  100015. */
  100016. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100017. if (!this._groundMaterial) {
  100018. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100019. }
  100020. this._groundMaterial.alpha = this._options.groundOpacity;
  100021. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100022. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100023. this._groundMaterial.primaryColor = this._options.groundColor;
  100024. this._groundMaterial.useRGBColor = false;
  100025. this._groundMaterial.enableNoise = true;
  100026. if (this._ground) {
  100027. this._ground.material = this._groundMaterial;
  100028. }
  100029. };
  100030. /**
  100031. * Setup the ground diffuse texture according to the specified options.
  100032. */
  100033. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100034. if (!this._groundMaterial) {
  100035. return;
  100036. }
  100037. if (this._groundTexture) {
  100038. return;
  100039. }
  100040. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100041. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  100042. return;
  100043. }
  100044. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100045. diffuseTexture.gammaSpace = false;
  100046. diffuseTexture.hasAlpha = true;
  100047. this._groundMaterial.diffuseTexture = diffuseTexture;
  100048. };
  100049. /**
  100050. * Setup the ground mirror texture according to the specified options.
  100051. */
  100052. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  100053. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100054. if (!this._groundMirror) {
  100055. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  100056. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  100057. this._groundMirror.anisotropicFilteringLevel = 1;
  100058. this._groundMirror.wrapU = wrapping;
  100059. this._groundMirror.wrapV = wrapping;
  100060. this._groundMirror.gammaSpace = false;
  100061. if (this._groundMirror.renderList) {
  100062. for (var i = 0; i < this._scene.meshes.length; i++) {
  100063. var mesh = this._scene.meshes[i];
  100064. if (mesh !== this._ground &&
  100065. mesh !== this._skybox &&
  100066. mesh !== this._rootMesh) {
  100067. this._groundMirror.renderList.push(mesh);
  100068. }
  100069. }
  100070. }
  100071. }
  100072. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  100073. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  100074. };
  100075. /**
  100076. * Setup the ground to receive the mirror texture.
  100077. */
  100078. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  100079. if (this._groundMaterial) {
  100080. this._groundMaterial.reflectionTexture = this._groundMirror;
  100081. this._groundMaterial.reflectionFresnel = true;
  100082. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  100083. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  100084. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  100085. }
  100086. };
  100087. /**
  100088. * Setup the skybox according to the specified options.
  100089. */
  100090. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  100091. var _this = this;
  100092. if (!this._skybox) {
  100093. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  100094. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  100095. }
  100096. this._skybox.parent = this._rootMesh;
  100097. };
  100098. /**
  100099. * Setup the skybox material according to the specified options.
  100100. */
  100101. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  100102. if (!this._skybox) {
  100103. return;
  100104. }
  100105. if (!this._skyboxMaterial) {
  100106. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  100107. }
  100108. this._skyboxMaterial.useRGBColor = false;
  100109. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  100110. this._skyboxMaterial.enableNoise = true;
  100111. this._skybox.material = this._skyboxMaterial;
  100112. };
  100113. /**
  100114. * Setup the skybox reflection texture according to the specified options.
  100115. */
  100116. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  100117. if (!this._skyboxMaterial) {
  100118. return;
  100119. }
  100120. if (this._skyboxTexture) {
  100121. return;
  100122. }
  100123. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  100124. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  100125. return;
  100126. }
  100127. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100128. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  100129. this._skyboxTexture.gammaSpace = false;
  100130. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  100131. };
  100132. /**
  100133. * Dispose all the elements created by the Helper.
  100134. */
  100135. EnvironmentHelper.prototype.dispose = function () {
  100136. if (this._groundMaterial) {
  100137. this._groundMaterial.dispose(true, true);
  100138. }
  100139. if (this._skyboxMaterial) {
  100140. this._skyboxMaterial.dispose(true, true);
  100141. }
  100142. this._rootMesh.dispose(false);
  100143. };
  100144. /**
  100145. * Default ground texture URL.
  100146. */
  100147. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  100148. /**
  100149. * Default skybox texture URL.
  100150. */
  100151. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  100152. /**
  100153. * Default environment texture URL.
  100154. */
  100155. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  100156. return EnvironmentHelper;
  100157. }());
  100158. BABYLON.EnvironmentHelper = EnvironmentHelper;
  100159. })(BABYLON || (BABYLON = {}));
  100160. //# sourceMappingURL=babylon.environmentHelper.js.map
  100161. var BABYLON;
  100162. (function (BABYLON) {
  100163. /**
  100164. * This class is made for on one-liner static method to help creating particle systems.
  100165. */
  100166. var ParticleHelper = /** @class */ (function () {
  100167. function ParticleHelper() {
  100168. }
  100169. /**
  100170. * This is the main static method (one-liner) of this helper to create different particle systems.
  100171. * @param type This string represents the type to the particle system to create
  100172. * @param emitter The object where the particle system will start to emit from.
  100173. * @param scene The scene where the particle system should live.
  100174. * @param gpu If the system will use gpu.
  100175. * @returns the ParticleSystem created.
  100176. */
  100177. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  100178. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  100179. if (gpu === void 0) { gpu = false; }
  100180. return new Promise(function (resolve, reject) {
  100181. if (!scene) {
  100182. scene = BABYLON.Engine.LastCreatedScene;
  100183. ;
  100184. }
  100185. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  100186. return reject("Particle system with GPU is not supported.");
  100187. }
  100188. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  100189. var newData = JSON.parse(data.toString());
  100190. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  100191. }, undefined, undefined, undefined, function (req, exception) {
  100192. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  100193. });
  100194. });
  100195. };
  100196. /**
  100197. * Static function used to create a new particle system from a IParticleSystemData
  100198. * @param data defines the source data
  100199. * @param scene defines the hosting scene
  100200. * @param emitter defines the particle emitter
  100201. * @returns a new ParticleSystem based on referenced data
  100202. */
  100203. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100204. // Create a particle system
  100205. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100206. // Where the particles come from
  100207. system.emitter = emitter; // the starting object, the emitter
  100208. ParticleHelper.UpdateSystem(system, data, scene);
  100209. return system;
  100210. };
  100211. /**
  100212. * Static function used to update a particle system from a IParticleSystemData
  100213. * @param system defines the particle system to update
  100214. * @param data defines the source data
  100215. * @param scene defines the hosting scene
  100216. */
  100217. ParticleHelper.UpdateSystem = function (system, data, scene) {
  100218. // Texture of each particle
  100219. if (data.textureFile) {
  100220. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  100221. }
  100222. // Colors of all particles
  100223. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  100224. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  100225. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  100226. // Size of each particle (random between...
  100227. system.minSize = data.minSize;
  100228. system.maxSize = data.maxSize;
  100229. system.minScaleX = data.minScaleX;
  100230. system.maxScaleX = data.maxScaleX;
  100231. system.minScaleY = data.minScaleY;
  100232. system.maxScaleY = data.maxScaleY;
  100233. // Life time of each particle (random between...
  100234. system.minLifeTime = data.minLifeTime;
  100235. system.maxLifeTime = data.maxLifeTime;
  100236. // Emission rate
  100237. system.emitRate = data.emitRate;
  100238. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100239. system.blendMode = data.blendMode;
  100240. // Set the gravity of all particles
  100241. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  100242. // Angular speed, in radians
  100243. system.minAngularSpeed = data.minAngularSpeed;
  100244. system.maxAngularSpeed = data.maxAngularSpeed;
  100245. // Speed
  100246. system.minEmitPower = data.minEmitPower;
  100247. system.maxEmitPower = data.maxEmitPower;
  100248. system.updateSpeed = data.updateSpeed;
  100249. switch (data.emitterType) {
  100250. case "box":
  100251. if (!data.direction1 || !data.direction2) {
  100252. throw new Error("Directions are missing in this particle system.");
  100253. }
  100254. if (!data.minEmitBox || !data.maxEmitBox) {
  100255. throw new Error("EmitBox is missing in this particle system.");
  100256. }
  100257. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  100258. break;
  100259. case "sphere":
  100260. system.createSphereEmitter(data.radius);
  100261. break;
  100262. case "directed_sphere":
  100263. if (!data.direction1 || !data.direction2) {
  100264. throw new Error("Directions are missing in this particle system.");
  100265. }
  100266. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  100267. break;
  100268. case "cone":
  100269. system.createConeEmitter(data.radius, data.angle);
  100270. break;
  100271. default:
  100272. break;
  100273. }
  100274. };
  100275. /**
  100276. * Static function used to export a particle system to a IParticleSystemData variable.
  100277. * Please note that texture file name is not exported and must be added manually
  100278. * @param system defines the particle system to export
  100279. */
  100280. ParticleHelper.ExportSystem = function (system) {
  100281. var outData = {};
  100282. // Colors of all particles
  100283. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  100284. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100285. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100286. // Size of each particle (random between...
  100287. outData.minSize = system.minSize;
  100288. outData.maxSize = system.maxSize;
  100289. outData.minScaleX = system.minScaleX;
  100290. outData.maxScaleX = system.maxScaleX;
  100291. outData.minScaleY = system.minScaleY;
  100292. outData.maxScaleY = system.maxScaleY;
  100293. // Life time of each particle (random between...
  100294. outData.minLifeTime = system.minLifeTime;
  100295. outData.maxLifeTime = system.maxLifeTime;
  100296. // Emission rate
  100297. outData.emitRate = system.emitRate;
  100298. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100299. outData.blendMode = system.blendMode;
  100300. // Set the gravity of all particles
  100301. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100302. // Angular speed, in radians
  100303. outData.minAngularSpeed = system.minAngularSpeed;
  100304. outData.maxAngularSpeed = system.maxAngularSpeed;
  100305. // Speed
  100306. outData.minEmitPower = system.minEmitPower;
  100307. outData.maxEmitPower = system.maxEmitPower;
  100308. outData.updateSpeed = system.updateSpeed;
  100309. switch (system.particleEmitterType.getClassName()) {
  100310. case "BoxEmitter":
  100311. outData.emitterType = "box";
  100312. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100313. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100314. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100315. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100316. break;
  100317. case "SphereParticleEmitter":
  100318. outData.emitterType = "sphere";
  100319. outData.radius = system.particleEmitterType.radius;
  100320. break;
  100321. case "SphereDirectedParticleEmitter":
  100322. outData.emitterType = "directed_sphere";
  100323. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100324. outData.radius = sphereDirectedParticleEmitter.radius;
  100325. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100326. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100327. break;
  100328. case "ConeEmitter":
  100329. outData.emitterType = "cone";
  100330. outData.radius = system.particleEmitterType.radius;
  100331. outData.angle = system.particleEmitterType.angle;
  100332. break;
  100333. default:
  100334. break;
  100335. }
  100336. return outData;
  100337. };
  100338. /**
  100339. * Base Assets URL.
  100340. */
  100341. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100342. return ParticleHelper;
  100343. }());
  100344. BABYLON.ParticleHelper = ParticleHelper;
  100345. })(BABYLON || (BABYLON = {}));
  100346. //# sourceMappingURL=babylon.particleHelper.js.map
  100347. var BABYLON;
  100348. (function (BABYLON) {
  100349. /**
  100350. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100351. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100352. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100353. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100354. */
  100355. var VideoDome = /** @class */ (function (_super) {
  100356. __extends(VideoDome, _super);
  100357. /**
  100358. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100359. * @param name Element's name, child elements will append suffixes for their own names.
  100360. * @param urlsOrVideo defines the url(s) or the video element to use
  100361. * @param options An object containing optional or exposed sub element properties
  100362. */
  100363. function VideoDome(name, urlsOrVideo, options, scene) {
  100364. var _this = _super.call(this, name, scene) || this;
  100365. // set defaults and manage values
  100366. name = name || "videoDome";
  100367. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100368. options.clickToPlay = Boolean(options.clickToPlay);
  100369. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100370. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100371. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100372. // create
  100373. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100374. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100375. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100376. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100377. flat: false,
  100378. radius: options.size,
  100379. subdivisions: options.resolution,
  100380. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100381. }, scene);
  100382. // configure material
  100383. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100384. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100385. material.reflectionTexture = _this._videoTexture;
  100386. material.useEquirectangularFOV = true;
  100387. material.fovMultiplier = 1.0;
  100388. // configure mesh
  100389. _this._mesh.material = material;
  100390. _this._mesh.parent = _this;
  100391. // optional configuration
  100392. if (options.clickToPlay) {
  100393. scene.onPointerUp = function () {
  100394. _this._videoTexture.video.play();
  100395. };
  100396. }
  100397. return _this;
  100398. }
  100399. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100400. /**
  100401. * Gets the video texture being displayed on the sphere
  100402. */
  100403. get: function () {
  100404. return this._videoTexture;
  100405. },
  100406. enumerable: true,
  100407. configurable: true
  100408. });
  100409. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100410. /**
  100411. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100412. * Also see the options.resolution property.
  100413. */
  100414. get: function () {
  100415. return this._material.fovMultiplier;
  100416. },
  100417. set: function (value) {
  100418. this._material.fovMultiplier = value;
  100419. },
  100420. enumerable: true,
  100421. configurable: true
  100422. });
  100423. /**
  100424. * Releases resources associated with this node.
  100425. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100426. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100427. */
  100428. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100429. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100430. this._videoTexture.dispose();
  100431. this._mesh.dispose();
  100432. this._material.dispose();
  100433. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100434. };
  100435. return VideoDome;
  100436. }(BABYLON.Node));
  100437. BABYLON.VideoDome = VideoDome;
  100438. })(BABYLON || (BABYLON = {}));
  100439. //# sourceMappingURL=babylon.videoDome.js.map
  100440. var BABYLON;
  100441. (function (BABYLON) {
  100442. /**
  100443. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100444. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100445. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100446. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100447. */
  100448. var PhotoDome = /** @class */ (function (_super) {
  100449. __extends(PhotoDome, _super);
  100450. /**
  100451. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100452. * @param name Element's name, child elements will append suffixes for their own names.
  100453. * @param urlsOfPhoto define the url of the photo to display
  100454. * @param options An object containing optional or exposed sub element properties
  100455. */
  100456. function PhotoDome(name, urlOfPhoto, options, scene) {
  100457. var _this = _super.call(this, name, scene) || this;
  100458. // set defaults and manage values
  100459. name = name || "photoDome";
  100460. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100461. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100462. // create
  100463. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100464. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100465. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100466. flat: false,
  100467. radius: options.size,
  100468. subdivisions: options.resolution,
  100469. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100470. }, scene);
  100471. // configure material
  100472. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100473. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100474. material.reflectionTexture = _this._photoTexture;
  100475. material.useEquirectangularFOV = true;
  100476. material.fovMultiplier = 1.0;
  100477. // configure mesh
  100478. _this._mesh.material = material;
  100479. _this._mesh.parent = _this;
  100480. return _this;
  100481. }
  100482. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100483. /**
  100484. * Gets the texture being displayed on the sphere
  100485. */
  100486. get: function () {
  100487. return this._photoTexture;
  100488. },
  100489. enumerable: true,
  100490. configurable: true
  100491. });
  100492. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100493. /**
  100494. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100495. * Also see the options.resolution property.
  100496. */
  100497. get: function () {
  100498. return this._material.fovMultiplier;
  100499. },
  100500. set: function (value) {
  100501. this._material.fovMultiplier = value;
  100502. },
  100503. enumerable: true,
  100504. configurable: true
  100505. });
  100506. /**
  100507. * Releases resources associated with this node.
  100508. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100509. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100510. */
  100511. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100512. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100513. this._photoTexture.dispose();
  100514. this._mesh.dispose();
  100515. this._material.dispose();
  100516. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100517. };
  100518. return PhotoDome;
  100519. }(BABYLON.Node));
  100520. BABYLON.PhotoDome = PhotoDome;
  100521. })(BABYLON || (BABYLON = {}));
  100522. //# sourceMappingURL=babylon.photoDome.js.map
  100523. 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\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 vec3 options;\nattribute vec2 size;\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; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\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); \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 vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\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 coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\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.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*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.rgb,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"};
  100524. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};"};