babylon.no-module.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375983769837798378983799838098381983829838398384983859838698387983889838998390983919839298393983949839598396983979839898399984009840198402984039840498405984069840798408984099841098411984129841398414984159841698417984189841998420984219842298423984249842598426984279842898429984309843198432984339843498435984369843798438984399844098441984429844398444984459844698447984489844998450984519845298453984549845598456984579845898459984609846198462984639846498465984669846798468984699847098471984729847398474984759847698477984789847998480984819848298483984849848598486984879848898489984909849198492984939849498495984969849798498984999850098501985029850398504985059850698507985089850998510985119851298513985149851598516985179851898519985209852198522985239852498525985269852798528985299853098531985329853398534985359853698537985389853998540985419854298543985449854598546985479854898549985509855198552985539855498555985569855798558985599856098561985629856398564985659856698567985689856998570985719857298573985749857598576985779857898579985809858198582985839858498585985869858798588985899859098591985929859398594985959859698597985989859998600986019860298603986049860598606986079860898609986109861198612986139861498615986169861798618986199862098621986229862398624986259862698627986289862998630986319863298633986349863598636986379863898639986409864198642986439864498645986469864798648986499865098651986529865398654986559865698657986589865998660986619866298663986649866598666986679866898669986709867198672986739867498675986769867798678986799868098681986829868398684986859868698687986889868998690986919869298693986949869598696986979869898699987009870198702987039870498705987069870798708987099871098711987129871398714987159871698717987189871998720987219872298723987249872598726987279872898729987309873198732987339873498735987369873798738987399874098741987429874398744987459874698747987489874998750987519875298753987549875598756987579875898759987609876198762987639876498765987669876798768987699877098771987729877398774987759877698777987789877998780987819878298783987849878598786987879878898789987909879198792987939879498795987969879798798987999880098801988029880398804988059880698807988089880998810988119881298813988149881598816988179881898819988209882198822988239882498825988269882798828988299883098831988329883398834988359883698837988389883998840988419884298843988449884598846988479884898849988509885198852988539885498855988569885798858988599886098861988629886398864988659886698867988689886998870988719887298873988749887598876988779887898879988809888198882988839888498885988869888798888988899889098891988929889398894988959889698897988989889998900989019890298903989049890598906989079890898909989109891198912989139891498915989169891798918989199892098921989229892398924989259892698927989289892998930989319893298933989349893598936989379893898939989409894198942989439894498945989469894798948989499895098951989529895398954989559895698957989589895998960989619896298963989649896598966989679896898969989709897198972989739897498975989769897798978989799898098981989829898398984989859898698987989889898998990989919899298993989949899598996989979899898999990009900199002990039900499005990069900799008990099901099011990129901399014990159901699017990189901999020990219902299023990249902599026990279902899029990309903199032990339903499035990369903799038990399904099041990429904399044990459904699047990489904999050990519905299053990549905599056990579905899059990609906199062990639906499065990669906799068990699907099071990729907399074990759907699077990789907999080990819908299083990849908599086990879908899089990909909199092990939909499095990969909799098990999910099101991029910399104991059910699107991089910999110991119911299113991149911599116991179911899119991209912199122991239912499125991269912799128991299913099131991329913399134991359913699137991389913999140991419914299143991449914599146991479914899149991509915199152991539915499155991569915799158991599916099161991629916399164991659916699167991689916999170991719917299173991749917599176991779917899179991809918199182991839918499185991869918799188991899919099191991929919399194991959919699197991989919999200992019920299203992049920599206992079920899209992109921199212992139921499215992169921799218992199922099221992229922399224992259922699227992289922999230992319923299233992349923599236992379923899239992409924199242992439924499245992469924799248992499925099251992529925399254992559925699257992589925999260992619926299263992649926599266992679926899269992709927199272992739927499275992769927799278992799928099281992829928399284992859928699287992889928999290992919929299293992949929599296992979929899299993009930199302993039930499305993069930799308993099931099311993129931399314993159931699317993189931999320993219932299323993249932599326993279932899329993309933199332993339933499335993369933799338993399934099341993429934399344993459934699347993489934999350993519935299353993549935599356993579935899359993609936199362993639936499365993669936799368993699937099371993729937399374993759937699377993789937999380993819938299383993849938599386993879938899389993909939199392993939939499395993969939799398993999940099401994029940399404994059940699407994089940999410994119941299413994149941599416994179941899419994209942199422994239942499425994269942799428994299943099431994329943399434994359943699437994389943999440994419944299443994449944599446994479944899449994509945199452994539945499455994569945799458994599946099461994629946399464994659946699467994689946999470994719947299473994749947599476994779947899479994809948199482994839948499485994869948799488994899949099491994929949399494994959949699497994989949999500995019950299503995049950599506995079950899509995109951199512995139951499515995169951799518995199952099521995229952399524995259952699527995289952999530995319953299533995349953599536995379953899539995409954199542995439954499545995469954799548995499955099551995529955399554995559955699557995589955999560995619956299563995649956599566995679956899569995709957199572995739957499575995769957799578995799958099581995829958399584995859958699587995889958999590995919959299593995949959599596995979959899599996009960199602996039960499605996069960799608996099961099611996129961399614996159961699617996189961999620996219962299623996249962599626996279962899629996309963199632996339963499635996369963799638996399964099641996429964399644996459964699647996489964999650996519965299653996549965599656996579965899659996609966199662996639966499665996669966799668996699967099671996729967399674996759967699677996789967999680996819968299683996849968599686996879968899689996909969199692996939969499695996969969799698996999970099701997029970399704997059970699707997089970999710997119971299713997149971599716997179971899719997209972199722997239972499725997269972799728997299973099731997329973399734997359973699737997389973999740997419974299743997449974599746997479974899749997509975199752997539975499755997569975799758997599976099761997629976399764997659976699767997689976999770997719977299773997749977599776997779977899779997809978199782997839978499785997869978799788997899979099791997929979399794997959979699797997989979999800998019980299803998049980599806998079980899809998109981199812998139981499815998169981799818998199982099821998229982399824998259982699827998289982999830998319983299833998349983599836998379983899839998409984199842998439984499845998469984799848998499985099851998529985399854998559985699857998589985999860998619986299863998649986599866998679986899869998709987199872998739987499875
  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, 0.0, 1.0)
  3308. * @returns a new forward Vector3
  3309. */
  3310. Vector3.Forward = function () {
  3311. return new Vector3(0.0, 0.0, 1.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3315. * @returns a new right Vector3
  3316. */
  3317. Vector3.Right = function () {
  3318. return new Vector3(1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3322. * @returns a new left Vector3
  3323. */
  3324. Vector3.Left = function () {
  3325. return new Vector3(-1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3329. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3330. * @param vector defines the Vector3 to transform
  3331. * @param transformation defines the transformation matrix
  3332. * @returns the transformed Vector3
  3333. */
  3334. Vector3.TransformCoordinates = function (vector, transformation) {
  3335. var result = Vector3.Zero();
  3336. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3337. return result;
  3338. };
  3339. /**
  3340. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @param result defines the Vector3 where to store the result
  3345. */
  3346. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3347. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3348. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3349. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3350. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3351. result.x = x / w;
  3352. result.y = y / w;
  3353. result.z = z / w;
  3354. };
  3355. /**
  3356. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3357. * This method computes tranformed coordinates only, not transformed direction vectors
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3366. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3367. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3368. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3369. result.x = rx / rw;
  3370. result.y = ry / rw;
  3371. result.z = rz / rw;
  3372. };
  3373. /**
  3374. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3375. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3376. * @param vector defines the Vector3 to transform
  3377. * @param transformation defines the transformation matrix
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.TransformNormal = function (vector, transformation) {
  3381. var result = Vector3.Zero();
  3382. Vector3.TransformNormalToRef(vector, transformation, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @param result defines the Vector3 where to store the result
  3391. */
  3392. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3395. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3396. result.x = x;
  3397. result.y = y;
  3398. result.z = z;
  3399. };
  3400. /**
  3401. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param x define the x coordinate of the source vector
  3404. * @param y define the y coordinate of the source vector
  3405. * @param z define the z coordinate of the source vector
  3406. * @param transformation defines the transformation matrix
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3410. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3411. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3412. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3416. * @param value1 defines the first control point
  3417. * @param value2 defines the second control point
  3418. * @param value3 defines the third control point
  3419. * @param value4 defines the fourth control point
  3420. * @param amount defines the amount on the spline to use
  3421. * @returns the new Vector3
  3422. */
  3423. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3424. var squared = amount * amount;
  3425. var cubed = amount * squared;
  3426. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3427. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3428. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3429. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3430. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3431. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3432. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3433. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3434. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * 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"
  3439. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3440. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3441. * @param value defines the current value
  3442. * @param min defines the lower range value
  3443. * @param max defines the upper range value
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.Clamp = function (value, min, max) {
  3447. var x = value.x;
  3448. x = (x > max.x) ? max.x : x;
  3449. x = (x < min.x) ? min.x : x;
  3450. var y = value.y;
  3451. y = (y > max.y) ? max.y : y;
  3452. y = (y < min.y) ? min.y : y;
  3453. var z = value.z;
  3454. z = (z > max.z) ? max.z : z;
  3455. z = (z < min.z) ? min.z : z;
  3456. return new Vector3(x, y, z);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3460. * @param value1 defines the first control point
  3461. * @param tangent1 defines the first tangent vector
  3462. * @param value2 defines the second control point
  3463. * @param tangent2 defines the second tangent vector
  3464. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3468. var squared = amount * amount;
  3469. var cubed = amount * squared;
  3470. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3471. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3472. var part3 = (cubed - (2.0 * squared)) + amount;
  3473. var part4 = cubed - squared;
  3474. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3475. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3476. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3477. return new Vector3(x, y, z);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3481. * @param start defines the start value
  3482. * @param end defines the end value
  3483. * @param amount max defines amount between both (between 0 and 1)
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.Lerp = function (start, end, amount) {
  3487. var result = new Vector3(0, 0, 0);
  3488. Vector3.LerpToRef(start, end, amount, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.LerpToRef = function (start, end, amount, result) {
  3499. result.x = start.x + ((end.x - start.x) * amount);
  3500. result.y = start.y + ((end.y - start.y) * amount);
  3501. result.z = start.z + ((end.z - start.z) * amount);
  3502. };
  3503. /**
  3504. * Returns the dot product (float) between the vectors "left" and "right"
  3505. * @param left defines the left operand
  3506. * @param right defines the right operand
  3507. * @returns the dot product
  3508. */
  3509. Vector3.Dot = function (left, right) {
  3510. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3511. };
  3512. /**
  3513. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3514. * The cross product is then orthogonal to both "left" and "right"
  3515. * @param left defines the left operand
  3516. * @param right defines the right operand
  3517. * @returns the cross product
  3518. */
  3519. Vector3.Cross = function (left, right) {
  3520. var result = Vector3.Zero();
  3521. Vector3.CrossToRef(left, right, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" with the cross product of "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @param result defines the Vector3 where to store the result
  3530. */
  3531. Vector3.CrossToRef = function (left, right, result) {
  3532. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3533. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3534. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3535. result.copyFrom(MathTmp.Vector3[0]);
  3536. };
  3537. /**
  3538. * Returns a new Vector3 as the normalization of the given vector
  3539. * @param vector defines the Vector3 to normalize
  3540. * @returns the new Vector3
  3541. */
  3542. Vector3.Normalize = function (vector) {
  3543. var result = Vector3.Zero();
  3544. Vector3.NormalizeToRef(vector, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the normalization of the given first vector
  3549. * @param vector defines the Vector3 to normalize
  3550. * @param result defines the Vector3 where to store the result
  3551. */
  3552. Vector3.NormalizeToRef = function (vector, result) {
  3553. result.copyFrom(vector);
  3554. result.normalize();
  3555. };
  3556. /**
  3557. * Project a Vector3 onto screen space
  3558. * @param vector defines the Vector3 to project
  3559. * @param world defines the world matrix to use
  3560. * @param transform defines the transform (view x projection) matrix to use
  3561. * @param viewport defines the screen viewport to use
  3562. * @returns the new Vector3
  3563. */
  3564. Vector3.Project = function (vector, world, transform, viewport) {
  3565. var cw = viewport.width;
  3566. var ch = viewport.height;
  3567. var cx = viewport.x;
  3568. var cy = viewport.y;
  3569. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3570. 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);
  3571. var matrix = MathTmp.Matrix[0];
  3572. world.multiplyToRef(transform, matrix);
  3573. matrix.multiplyToRef(viewportMatrix, matrix);
  3574. return Vector3.TransformCoordinates(vector, matrix);
  3575. };
  3576. /**
  3577. * Unproject from screen space to object space
  3578. * @param source defines the screen space Vector3 to use
  3579. * @param viewportWidth defines the current width of the viewport
  3580. * @param viewportHeight defines the current height of the viewport
  3581. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3582. * @param transform defines the transform (view x projection) matrix to use
  3583. * @returns the new Vector3
  3584. */
  3585. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3586. var matrix = MathTmp.Matrix[0];
  3587. world.multiplyToRef(transform, matrix);
  3588. matrix.invert();
  3589. source.x = source.x / viewportWidth * 2 - 1;
  3590. source.y = -(source.y / viewportHeight * 2 - 1);
  3591. var vector = Vector3.TransformCoordinates(source, matrix);
  3592. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3593. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3594. vector = vector.scale(1.0 / num);
  3595. }
  3596. return vector;
  3597. };
  3598. /**
  3599. * Unproject from screen space to object space
  3600. * @param source defines the screen space Vector3 to use
  3601. * @param viewportWidth defines the current width of the viewport
  3602. * @param viewportHeight defines the current height of the viewport
  3603. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3604. * @param view defines the view matrix to use
  3605. * @param projection defines the projection matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3609. var result = Vector3.Zero();
  3610. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Unproject from screen space to object space
  3615. * @param source defines the screen space Vector3 to use
  3616. * @param viewportWidth defines the current width of the viewport
  3617. * @param viewportHeight defines the current height of the viewport
  3618. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3619. * @param view defines the view matrix to use
  3620. * @param projection defines the projection matrix to use
  3621. * @param result defines the Vector3 where to store the result
  3622. */
  3623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3625. };
  3626. /**
  3627. * Unproject from screen space to object space
  3628. * @param sourceX defines the screen space x coordinate to use
  3629. * @param sourceY defines the screen space y coordinate to use
  3630. * @param sourceZ defines the screen space z coordinate to use
  3631. * @param viewportWidth defines the current width of the viewport
  3632. * @param viewportHeight defines the current height of the viewport
  3633. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3634. * @param view defines the view matrix to use
  3635. * @param projection defines the projection matrix to use
  3636. * @param result defines the Vector3 where to store the result
  3637. */
  3638. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3639. var matrix = MathTmp.Matrix[0];
  3640. world.multiplyToRef(view, matrix);
  3641. matrix.multiplyToRef(projection, matrix);
  3642. matrix.invert();
  3643. var screenSource = MathTmp.Vector3[0];
  3644. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3645. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3646. screenSource.z = 2 * sourceZ - 1.0;
  3647. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3648. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3649. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3650. result.scaleInPlace(1.0 / num);
  3651. }
  3652. };
  3653. /**
  3654. * Gets the minimal coordinate values between two Vector3
  3655. * @param left defines the first operand
  3656. * @param right defines the second operand
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Minimize = function (left, right) {
  3660. var min = left.clone();
  3661. min.minimizeInPlace(right);
  3662. return min;
  3663. };
  3664. /**
  3665. * Gets the maximal coordinate values between two Vector3
  3666. * @param left defines the first operand
  3667. * @param right defines the second operand
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Maximize = function (left, right) {
  3671. var max = left.clone();
  3672. max.maximizeInPlace(right);
  3673. return max;
  3674. };
  3675. /**
  3676. * Returns the distance between the vectors "value1" and "value2"
  3677. * @param value1 defines the first operand
  3678. * @param value2 defines the second operand
  3679. * @returns the distance
  3680. */
  3681. Vector3.Distance = function (value1, value2) {
  3682. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3683. };
  3684. /**
  3685. * Returns the squared distance between the vectors "value1" and "value2"
  3686. * @param value1 defines the first operand
  3687. * @param value2 defines the second operand
  3688. * @returns the squared distance
  3689. */
  3690. Vector3.DistanceSquared = function (value1, value2) {
  3691. var x = value1.x - value2.x;
  3692. var y = value1.y - value2.y;
  3693. var z = value1.z - value2.z;
  3694. return (x * x) + (y * y) + (z * z);
  3695. };
  3696. /**
  3697. * Returns a new Vector3 located at the center between "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the new Vector3
  3701. */
  3702. Vector3.Center = function (value1, value2) {
  3703. var center = value1.add(value2);
  3704. center.scaleInPlace(0.5);
  3705. return center;
  3706. };
  3707. /**
  3708. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3709. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3710. * to something in order to rotate it from its local system to the given target system
  3711. * Note: axis1, axis2 and axis3 are normalized during this operation
  3712. * @param axis1 defines the first axis
  3713. * @param axis2 defines the second axis
  3714. * @param axis3 defines the third axis
  3715. * @returns a new Vector3
  3716. */
  3717. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3718. var rotation = Vector3.Zero();
  3719. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3720. return rotation;
  3721. };
  3722. /**
  3723. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @param ref defines the Vector3 where to store the result
  3728. */
  3729. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3730. var quat = MathTmp.Quaternion[0];
  3731. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3732. quat.toEulerAnglesToRef(ref);
  3733. };
  3734. return Vector3;
  3735. }());
  3736. BABYLON.Vector3 = Vector3;
  3737. //Vector4 class created for EulerAngle class conversion to Quaternion
  3738. var Vector4 = /** @class */ (function () {
  3739. /**
  3740. * Creates a Vector4 object from the given floats.
  3741. */
  3742. function Vector4(x, y, z, w) {
  3743. this.x = x;
  3744. this.y = y;
  3745. this.z = z;
  3746. this.w = w;
  3747. }
  3748. /**
  3749. * Returns the string with the Vector4 coordinates.
  3750. */
  3751. Vector4.prototype.toString = function () {
  3752. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3753. };
  3754. /**
  3755. * Returns the string "Vector4".
  3756. */
  3757. Vector4.prototype.getClassName = function () {
  3758. return "Vector4";
  3759. };
  3760. /**
  3761. * Returns the Vector4 hash code.
  3762. */
  3763. Vector4.prototype.getHashCode = function () {
  3764. var hash = this.x || 0;
  3765. hash = (hash * 397) ^ (this.y || 0);
  3766. hash = (hash * 397) ^ (this.z || 0);
  3767. hash = (hash * 397) ^ (this.w || 0);
  3768. return hash;
  3769. };
  3770. // Operators
  3771. /**
  3772. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.asArray = function () {
  3775. var result = new Array();
  3776. this.toArray(result, 0);
  3777. return result;
  3778. };
  3779. /**
  3780. * Populates the given array from the given index with the Vector4 coordinates.
  3781. * Returns the Vector4.
  3782. */
  3783. Vector4.prototype.toArray = function (array, index) {
  3784. if (index === undefined) {
  3785. index = 0;
  3786. }
  3787. array[index] = this.x;
  3788. array[index + 1] = this.y;
  3789. array[index + 2] = this.z;
  3790. array[index + 3] = this.w;
  3791. return this;
  3792. };
  3793. /**
  3794. * Adds the given vector to the current Vector4.
  3795. * Returns the updated Vector4.
  3796. */
  3797. Vector4.prototype.addInPlace = function (otherVector) {
  3798. this.x += otherVector.x;
  3799. this.y += otherVector.y;
  3800. this.z += otherVector.z;
  3801. this.w += otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3806. */
  3807. Vector4.prototype.add = function (otherVector) {
  3808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3809. };
  3810. /**
  3811. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.addToRef = function (otherVector, result) {
  3815. result.x = this.x + otherVector.x;
  3816. result.y = this.y + otherVector.y;
  3817. result.z = this.z + otherVector.z;
  3818. result.w = this.w + otherVector.w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Subtract in place the given vector from the current Vector4.
  3823. * Returns the updated Vector4.
  3824. */
  3825. Vector4.prototype.subtractInPlace = function (otherVector) {
  3826. this.x -= otherVector.x;
  3827. this.y -= otherVector.y;
  3828. this.z -= otherVector.z;
  3829. this.w -= otherVector.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3834. */
  3835. Vector4.prototype.subtract = function (otherVector) {
  3836. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3837. };
  3838. /**
  3839. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3843. result.x = this.x - otherVector.x;
  3844. result.y = this.y - otherVector.y;
  3845. result.z = this.z - otherVector.z;
  3846. result.w = this.w - otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3851. */
  3852. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3853. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3854. };
  3855. /**
  3856. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3857. * Returns the current Vector4.
  3858. */
  3859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3860. result.x = this.x - x;
  3861. result.y = this.y - y;
  3862. result.z = this.z - z;
  3863. result.w = this.w - w;
  3864. return this;
  3865. };
  3866. /**
  3867. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3868. */
  3869. Vector4.prototype.negate = function () {
  3870. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3871. };
  3872. /**
  3873. * Multiplies the current Vector4 coordinates by scale (float).
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.scaleInPlace = function (scale) {
  3877. this.x *= scale;
  3878. this.y *= scale;
  3879. this.z *= scale;
  3880. this.w *= scale;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3885. */
  3886. Vector4.prototype.scale = function (scale) {
  3887. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3888. };
  3889. /**
  3890. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3891. * Returns the current Vector4.
  3892. */
  3893. Vector4.prototype.scaleToRef = function (scale, result) {
  3894. result.x = this.x * scale;
  3895. result.y = this.y * scale;
  3896. result.z = this.z * scale;
  3897. result.w = this.w * scale;
  3898. return this;
  3899. };
  3900. /**
  3901. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3902. * @param scale defines the scale factor
  3903. * @param result defines the Vector4 object where to store the result
  3904. * @returns the unmodified current Vector4
  3905. */
  3906. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3907. result.x += this.x * scale;
  3908. result.y += this.y * scale;
  3909. result.z += this.z * scale;
  3910. result.w += this.w * scale;
  3911. return this;
  3912. };
  3913. /**
  3914. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3915. */
  3916. Vector4.prototype.equals = function (otherVector) {
  3917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3918. };
  3919. /**
  3920. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3921. */
  3922. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3923. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3924. return otherVector
  3925. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3926. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3927. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3928. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3929. };
  3930. /**
  3931. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3932. */
  3933. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3934. return this.x === x && this.y === y && this.z === z && this.w === w;
  3935. };
  3936. /**
  3937. * Multiplies in place the current Vector4 by the given one.
  3938. * Returns the updated Vector4.
  3939. */
  3940. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3941. this.x *= otherVector.x;
  3942. this.y *= otherVector.y;
  3943. this.z *= otherVector.z;
  3944. this.w *= otherVector.w;
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3949. */
  3950. Vector4.prototype.multiply = function (otherVector) {
  3951. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3952. };
  3953. /**
  3954. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3955. * Returns the current Vector4.
  3956. */
  3957. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3958. result.x = this.x * otherVector.x;
  3959. result.y = this.y * otherVector.y;
  3960. result.z = this.z * otherVector.z;
  3961. result.w = this.w * otherVector.w;
  3962. return this;
  3963. };
  3964. /**
  3965. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3966. */
  3967. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3968. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3972. */
  3973. Vector4.prototype.divide = function (otherVector) {
  3974. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.divideToRef = function (otherVector, result) {
  3981. result.x = this.x / otherVector.x;
  3982. result.y = this.y / otherVector.y;
  3983. result.z = this.z / otherVector.z;
  3984. result.w = this.w / otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Divides the current Vector3 coordinates by the given ones.
  3989. * @returns the updated Vector3.
  3990. */
  3991. Vector4.prototype.divideInPlace = function (otherVector) {
  3992. return this.divideToRef(otherVector, this);
  3993. };
  3994. /**
  3995. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3996. * @param other defines the second operand
  3997. * @returns the current updated Vector4
  3998. */
  3999. Vector4.prototype.minimizeInPlace = function (other) {
  4000. if (other.x < this.x)
  4001. this.x = other.x;
  4002. if (other.y < this.y)
  4003. this.y = other.y;
  4004. if (other.z < this.z)
  4005. this.z = other.z;
  4006. if (other.w < this.w)
  4007. this.w = other.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4012. * @param other defines the second operand
  4013. * @returns the current updated Vector4
  4014. */
  4015. Vector4.prototype.maximizeInPlace = function (other) {
  4016. if (other.x > this.x)
  4017. this.x = other.x;
  4018. if (other.y > this.y)
  4019. this.y = other.y;
  4020. if (other.z > this.z)
  4021. this.z = other.z;
  4022. if (other.w > this.w)
  4023. this.w = other.w;
  4024. return this;
  4025. };
  4026. // Properties
  4027. /**
  4028. * Returns the Vector4 length (float).
  4029. */
  4030. Vector4.prototype.length = function () {
  4031. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4032. };
  4033. /**
  4034. * Returns the Vector4 squared length (float).
  4035. */
  4036. Vector4.prototype.lengthSquared = function () {
  4037. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4038. };
  4039. // Methods
  4040. /**
  4041. * Normalizes in place the Vector4.
  4042. * Returns the updated Vector4.
  4043. */
  4044. Vector4.prototype.normalize = function () {
  4045. var len = this.length();
  4046. if (len === 0)
  4047. return this;
  4048. var num = 1.0 / len;
  4049. this.x *= num;
  4050. this.y *= num;
  4051. this.z *= num;
  4052. this.w *= num;
  4053. return this;
  4054. };
  4055. /**
  4056. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4057. */
  4058. Vector4.prototype.toVector3 = function () {
  4059. return new Vector3(this.x, this.y, this.z);
  4060. };
  4061. /**
  4062. * Returns a new Vector4 copied from the current one.
  4063. */
  4064. Vector4.prototype.clone = function () {
  4065. return new Vector4(this.x, this.y, this.z, this.w);
  4066. };
  4067. /**
  4068. * Updates the current Vector4 with the given one coordinates.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.copyFrom = function (source) {
  4072. this.x = source.x;
  4073. this.y = source.y;
  4074. this.z = source.z;
  4075. this.w = source.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Updates the current Vector4 coordinates with the given floats.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4083. this.x = x;
  4084. this.y = y;
  4085. this.z = z;
  4086. this.w = w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Updates the current Vector4 coordinates with the given floats.
  4091. * Returns the updated Vector4.
  4092. */
  4093. Vector4.prototype.set = function (x, y, z, w) {
  4094. return this.copyFromFloats(x, y, z, w);
  4095. };
  4096. // Statics
  4097. /**
  4098. * Returns a new Vector4 set from the starting index of the given array.
  4099. */
  4100. Vector4.FromArray = function (array, offset) {
  4101. if (!offset) {
  4102. offset = 0;
  4103. }
  4104. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4105. };
  4106. /**
  4107. * Updates the given vector "result" from the starting index of the given array.
  4108. */
  4109. Vector4.FromArrayToRef = function (array, offset, result) {
  4110. result.x = array[offset];
  4111. result.y = array[offset + 1];
  4112. result.z = array[offset + 2];
  4113. result.w = array[offset + 3];
  4114. };
  4115. /**
  4116. * Updates the given vector "result" from the starting index of the given Float32Array.
  4117. */
  4118. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4119. Vector4.FromArrayToRef(array, offset, result);
  4120. };
  4121. /**
  4122. * Updates the given vector "result" coordinates from the given floats.
  4123. */
  4124. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4125. result.x = x;
  4126. result.y = y;
  4127. result.z = z;
  4128. result.w = w;
  4129. };
  4130. /**
  4131. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4132. */
  4133. Vector4.Zero = function () {
  4134. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4135. };
  4136. /**
  4137. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4138. */
  4139. Vector4.One = function () {
  4140. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4141. };
  4142. /**
  4143. * Returns a new normalized Vector4 from the given one.
  4144. */
  4145. Vector4.Normalize = function (vector) {
  4146. var result = Vector4.Zero();
  4147. Vector4.NormalizeToRef(vector, result);
  4148. return result;
  4149. };
  4150. /**
  4151. * Updates the given vector "result" from the normalization of the given one.
  4152. */
  4153. Vector4.NormalizeToRef = function (vector, result) {
  4154. result.copyFrom(vector);
  4155. result.normalize();
  4156. };
  4157. Vector4.Minimize = function (left, right) {
  4158. var min = left.clone();
  4159. min.minimizeInPlace(right);
  4160. return min;
  4161. };
  4162. Vector4.Maximize = function (left, right) {
  4163. var max = left.clone();
  4164. max.maximizeInPlace(right);
  4165. return max;
  4166. };
  4167. /**
  4168. * Returns the distance (float) between the vectors "value1" and "value2".
  4169. */
  4170. Vector4.Distance = function (value1, value2) {
  4171. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4172. };
  4173. /**
  4174. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4175. */
  4176. Vector4.DistanceSquared = function (value1, value2) {
  4177. var x = value1.x - value2.x;
  4178. var y = value1.y - value2.y;
  4179. var z = value1.z - value2.z;
  4180. var w = value1.w - value2.w;
  4181. return (x * x) + (y * y) + (z * z) + (w * w);
  4182. };
  4183. /**
  4184. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4185. */
  4186. Vector4.Center = function (value1, value2) {
  4187. var center = value1.add(value2);
  4188. center.scaleInPlace(0.5);
  4189. return center;
  4190. };
  4191. /**
  4192. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4193. * This methods computes transformed normalized direction vectors only.
  4194. */
  4195. Vector4.TransformNormal = function (vector, transformation) {
  4196. var result = Vector4.Zero();
  4197. Vector4.TransformNormalToRef(vector, transformation, result);
  4198. return result;
  4199. };
  4200. /**
  4201. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4202. * This methods computes transformed normalized direction vectors only.
  4203. */
  4204. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4205. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4206. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4207. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4208. result.x = x;
  4209. result.y = y;
  4210. result.z = z;
  4211. result.w = vector.w;
  4212. };
  4213. /**
  4214. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4215. * This methods computes transformed normalized direction vectors only.
  4216. */
  4217. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4218. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4219. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4220. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4221. result.w = w;
  4222. };
  4223. return Vector4;
  4224. }());
  4225. BABYLON.Vector4 = Vector4;
  4226. var Size = /** @class */ (function () {
  4227. /**
  4228. * Creates a Size object from the given width and height (floats).
  4229. */
  4230. function Size(width, height) {
  4231. this.width = width;
  4232. this.height = height;
  4233. }
  4234. // Returns a string with the Size width and height.
  4235. Size.prototype.toString = function () {
  4236. return "{W: " + this.width + ", H: " + this.height + "}";
  4237. };
  4238. /**
  4239. * Returns the string "Size"
  4240. */
  4241. Size.prototype.getClassName = function () {
  4242. return "Size";
  4243. };
  4244. /**
  4245. * Returns the Size hash code.
  4246. */
  4247. Size.prototype.getHashCode = function () {
  4248. var hash = this.width || 0;
  4249. hash = (hash * 397) ^ (this.height || 0);
  4250. return hash;
  4251. };
  4252. /**
  4253. * Updates the current size from the given one.
  4254. * Returns the updated Size.
  4255. */
  4256. Size.prototype.copyFrom = function (src) {
  4257. this.width = src.width;
  4258. this.height = src.height;
  4259. };
  4260. /**
  4261. * Updates in place the current Size from the given floats.
  4262. * Returns the updated Size.
  4263. */
  4264. Size.prototype.copyFromFloats = function (width, height) {
  4265. this.width = width;
  4266. this.height = height;
  4267. return this;
  4268. };
  4269. /**
  4270. * Updates in place the current Size from the given floats.
  4271. * Returns the updated Size.
  4272. */
  4273. Size.prototype.set = function (width, height) {
  4274. return this.copyFromFloats(width, height);
  4275. };
  4276. /**
  4277. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4278. */
  4279. Size.prototype.multiplyByFloats = function (w, h) {
  4280. return new Size(this.width * w, this.height * h);
  4281. };
  4282. /**
  4283. * Returns a new Size copied from the given one.
  4284. */
  4285. Size.prototype.clone = function () {
  4286. return new Size(this.width, this.height);
  4287. };
  4288. /**
  4289. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4290. */
  4291. Size.prototype.equals = function (other) {
  4292. if (!other) {
  4293. return false;
  4294. }
  4295. return (this.width === other.width) && (this.height === other.height);
  4296. };
  4297. Object.defineProperty(Size.prototype, "surface", {
  4298. /**
  4299. * Returns the surface of the Size : width * height (float).
  4300. */
  4301. get: function () {
  4302. return this.width * this.height;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. /**
  4308. * Returns a new Size set to (0.0, 0.0)
  4309. */
  4310. Size.Zero = function () {
  4311. return new Size(0.0, 0.0);
  4312. };
  4313. /**
  4314. * Returns a new Size set as the addition result of the current Size and the given one.
  4315. */
  4316. Size.prototype.add = function (otherSize) {
  4317. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4322. */
  4323. Size.prototype.subtract = 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 at the linear interpolation "amount" between "start" and "end".
  4329. */
  4330. Size.Lerp = function (start, end, amount) {
  4331. var w = start.width + ((end.width - start.width) * amount);
  4332. var h = start.height + ((end.height - start.height) * amount);
  4333. return new Size(w, h);
  4334. };
  4335. return Size;
  4336. }());
  4337. BABYLON.Size = Size;
  4338. /**
  4339. * Class used to store quaternion data
  4340. * @see https://en.wikipedia.org/wiki/Quaternion
  4341. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4342. */
  4343. var Quaternion = /** @class */ (function () {
  4344. /**
  4345. * Creates a new Quaternion from the given floats
  4346. * @param x defines the first component (0 by default)
  4347. * @param y defines the second component (0 by default)
  4348. * @param z defines the third component (0 by default)
  4349. * @param w defines the fourth component (1.0 by default)
  4350. */
  4351. function Quaternion(
  4352. /** defines the first component (0 by default) */
  4353. x,
  4354. /** defines the second component (0 by default) */
  4355. y,
  4356. /** defines the third component (0 by default) */
  4357. z,
  4358. /** defines the fourth component (1.0 by default) */
  4359. w) {
  4360. if (x === void 0) { x = 0.0; }
  4361. if (y === void 0) { y = 0.0; }
  4362. if (z === void 0) { z = 0.0; }
  4363. if (w === void 0) { w = 1.0; }
  4364. this.x = x;
  4365. this.y = y;
  4366. this.z = z;
  4367. this.w = w;
  4368. }
  4369. /**
  4370. * Gets a string representation for the current quaternion
  4371. * @returns a string with the Quaternion coordinates
  4372. */
  4373. Quaternion.prototype.toString = function () {
  4374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4375. };
  4376. /**
  4377. * Gets the class name of the quaternion
  4378. * @returns the string "Quaternion"
  4379. */
  4380. Quaternion.prototype.getClassName = function () {
  4381. return "Quaternion";
  4382. };
  4383. /**
  4384. * Gets a hash code for this quaternion
  4385. * @returns the quaternion hash code
  4386. */
  4387. Quaternion.prototype.getHashCode = function () {
  4388. var hash = this.x || 0;
  4389. hash = (hash * 397) ^ (this.y || 0);
  4390. hash = (hash * 397) ^ (this.z || 0);
  4391. hash = (hash * 397) ^ (this.w || 0);
  4392. return hash;
  4393. };
  4394. /**
  4395. * Copy the quaternion to an array
  4396. * @returns a new array populated with 4 elements from the quaternion coordinates
  4397. */
  4398. Quaternion.prototype.asArray = function () {
  4399. return [this.x, this.y, this.z, this.w];
  4400. };
  4401. /**
  4402. * Check if two quaternions are equals
  4403. * @param otherQuaternion defines the second operand
  4404. * @return true if the current quaternion and the given one coordinates are strictly equals
  4405. */
  4406. Quaternion.prototype.equals = function (otherQuaternion) {
  4407. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4408. };
  4409. /**
  4410. * Clone the current quaternion
  4411. * @returns a new quaternion copied from the current one
  4412. */
  4413. Quaternion.prototype.clone = function () {
  4414. return new Quaternion(this.x, this.y, this.z, this.w);
  4415. };
  4416. /**
  4417. * Copy a quaternion to the current one
  4418. * @param other defines the other quaternion
  4419. * @returns the updated current quaternion
  4420. */
  4421. Quaternion.prototype.copyFrom = function (other) {
  4422. this.x = other.x;
  4423. this.y = other.y;
  4424. this.z = other.z;
  4425. this.w = other.w;
  4426. return this;
  4427. };
  4428. /**
  4429. * Updates the current quaternion with the given float coordinates
  4430. * @param x defines the x coordinate
  4431. * @param y defines the y coordinate
  4432. * @param z defines the z coordinate
  4433. * @param w defines the w coordinate
  4434. * @returns the updated current quaternion
  4435. */
  4436. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4437. this.x = x;
  4438. this.y = y;
  4439. this.z = z;
  4440. this.w = w;
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current quaternion from the given float coordinates
  4445. * @param x defines the x coordinate
  4446. * @param y defines the y coordinate
  4447. * @param z defines the z coordinate
  4448. * @param w defines the w coordinate
  4449. * @returns the updated current quaternion
  4450. */
  4451. Quaternion.prototype.set = function (x, y, z, w) {
  4452. return this.copyFromFloats(x, y, z, w);
  4453. };
  4454. /**
  4455. * Adds two quaternions
  4456. * @param other defines the second operand
  4457. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4458. */
  4459. Quaternion.prototype.add = function (other) {
  4460. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4461. };
  4462. /**
  4463. * Add a quaternion to the current one
  4464. * @param other defines the quaternion to add
  4465. * @returns the current quaternion
  4466. */
  4467. Quaternion.prototype.addInPlace = function (other) {
  4468. this.x += other.x;
  4469. this.y += other.y;
  4470. this.z += other.z;
  4471. this.w += other.w;
  4472. return this;
  4473. };
  4474. /**
  4475. * Subtract two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the subtraction result of the given one from the current one
  4478. */
  4479. Quaternion.prototype.subtract = function (other) {
  4480. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4481. };
  4482. /**
  4483. * Multiplies the current quaternion by a scale factor
  4484. * @param value defines the scale factor
  4485. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4486. */
  4487. Quaternion.prototype.scale = function (value) {
  4488. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4489. };
  4490. /**
  4491. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current quaternion
  4495. */
  4496. Quaternion.prototype.scaleToRef = function (scale, result) {
  4497. result.x = this.x * scale;
  4498. result.y = this.y * scale;
  4499. result.z = this.z * scale;
  4500. result.w = this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Multiplies in place the current quaternion by a scale factor
  4505. * @param value defines the scale factor
  4506. * @returns the current modified quaternion
  4507. */
  4508. Quaternion.prototype.scaleInPlace = function (value) {
  4509. this.x *= value;
  4510. this.y *= value;
  4511. this.z *= value;
  4512. this.w *= value;
  4513. return this;
  4514. };
  4515. /**
  4516. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4517. * @param scale defines the scale factor
  4518. * @param result defines the Quaternion object where to store the result
  4519. * @returns the unmodified current quaternion
  4520. */
  4521. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4522. result.x += this.x * scale;
  4523. result.y += this.y * scale;
  4524. result.z += this.z * scale;
  4525. result.w += this.w * scale;
  4526. return this;
  4527. };
  4528. /**
  4529. * Multiplies two quaternions
  4530. * @param q1 defines the second operand
  4531. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4532. */
  4533. Quaternion.prototype.multiply = function (q1) {
  4534. var result = new Quaternion(0, 0, 0, 1.0);
  4535. this.multiplyToRef(q1, result);
  4536. return result;
  4537. };
  4538. /**
  4539. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4540. * @param q1 defines the second operand
  4541. * @param result defines the target quaternion
  4542. * @returns the current quaternion
  4543. */
  4544. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4545. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4546. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4547. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4548. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4549. result.copyFromFloats(x, y, z, w);
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4554. * @param q1 defines the second operand
  4555. * @returns the currentupdated quaternion
  4556. */
  4557. Quaternion.prototype.multiplyInPlace = function (q1) {
  4558. this.multiplyToRef(q1, this);
  4559. return this;
  4560. };
  4561. /**
  4562. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4563. * @param ref defines the target quaternion
  4564. * @returns the current quaternion
  4565. */
  4566. Quaternion.prototype.conjugateToRef = function (ref) {
  4567. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4568. return this;
  4569. };
  4570. /**
  4571. * Conjugates in place (1-q) the current quaternion
  4572. * @returns the current updated quaternion
  4573. */
  4574. Quaternion.prototype.conjugateInPlace = function () {
  4575. this.x *= -1;
  4576. this.y *= -1;
  4577. this.z *= -1;
  4578. return this;
  4579. };
  4580. /**
  4581. * Conjugates in place (1-q) the current quaternion
  4582. * @returns a new quaternion
  4583. */
  4584. Quaternion.prototype.conjugate = function () {
  4585. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4586. return result;
  4587. };
  4588. /**
  4589. * Gets length of current quaternion
  4590. * @returns the quaternion length (float)
  4591. */
  4592. Quaternion.prototype.length = function () {
  4593. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4594. };
  4595. /**
  4596. * Normalize in place the current quaternion
  4597. * @returns the current updated quaternion
  4598. */
  4599. Quaternion.prototype.normalize = function () {
  4600. var length = 1.0 / this.length();
  4601. this.x *= length;
  4602. this.y *= length;
  4603. this.z *= length;
  4604. this.w *= length;
  4605. return this;
  4606. };
  4607. /**
  4608. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4609. * @param order is a reserved parameter and is ignore for now
  4610. * @returns a new Vector3 containing the Euler angles
  4611. */
  4612. Quaternion.prototype.toEulerAngles = function (order) {
  4613. if (order === void 0) { order = "YZX"; }
  4614. var result = Vector3.Zero();
  4615. this.toEulerAnglesToRef(result, order);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4620. * @param result defines the vector which will be filled with the Euler angles
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns the current unchanged quaternion
  4623. */
  4624. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var qz = this.z;
  4627. var qx = this.x;
  4628. var qy = this.y;
  4629. var qw = this.w;
  4630. var sqw = qw * qw;
  4631. var sqz = qz * qz;
  4632. var sqx = qx * qx;
  4633. var sqy = qy * qy;
  4634. var zAxisY = qy * qz - qx * qw;
  4635. var limit = .4999999;
  4636. if (zAxisY < -limit) {
  4637. result.y = 2 * Math.atan2(qy, qw);
  4638. result.x = Math.PI / 2;
  4639. result.z = 0;
  4640. }
  4641. else if (zAxisY > limit) {
  4642. result.y = 2 * Math.atan2(qy, qw);
  4643. result.x = -Math.PI / 2;
  4644. result.z = 0;
  4645. }
  4646. else {
  4647. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4648. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4649. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4650. }
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the given rotation matrix with the current quaternion values
  4655. * @param result defines the target matrix
  4656. * @returns the current unchanged quaternion
  4657. */
  4658. Quaternion.prototype.toRotationMatrix = function (result) {
  4659. var xx = this.x * this.x;
  4660. var yy = this.y * this.y;
  4661. var zz = this.z * this.z;
  4662. var xy = this.x * this.y;
  4663. var zw = this.z * this.w;
  4664. var zx = this.z * this.x;
  4665. var yw = this.y * this.w;
  4666. var yz = this.y * this.z;
  4667. var xw = this.x * this.w;
  4668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4669. result.m[1] = 2.0 * (xy + zw);
  4670. result.m[2] = 2.0 * (zx - yw);
  4671. result.m[3] = 0;
  4672. result.m[4] = 2.0 * (xy - zw);
  4673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4674. result.m[6] = 2.0 * (yz + xw);
  4675. result.m[7] = 0;
  4676. result.m[8] = 2.0 * (zx + yw);
  4677. result.m[9] = 2.0 * (yz - xw);
  4678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4679. result.m[11] = 0;
  4680. result.m[12] = 0;
  4681. result.m[13] = 0;
  4682. result.m[14] = 0;
  4683. result.m[15] = 1.0;
  4684. result._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the current quaternion from the given rotation matrix values
  4689. * @param matrix defines the source matrix
  4690. * @returns the current updated quaternion
  4691. */
  4692. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4693. Quaternion.FromRotationMatrixToRef(matrix, this);
  4694. return this;
  4695. };
  4696. // Statics
  4697. /**
  4698. * Creates a new quaternion from a rotation matrix
  4699. * @param matrix defines the source matrix
  4700. * @returns a new quaternion created from the given rotation matrix values
  4701. */
  4702. Quaternion.FromRotationMatrix = function (matrix) {
  4703. var result = new Quaternion();
  4704. Quaternion.FromRotationMatrixToRef(matrix, result);
  4705. return result;
  4706. };
  4707. /**
  4708. * Updates the given quaternion with the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @param result defines the target quaternion
  4711. */
  4712. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4713. var data = matrix.m;
  4714. var m11 = data[0], m12 = data[4], m13 = data[8];
  4715. var m21 = data[1], m22 = data[5], m23 = data[9];
  4716. var m31 = data[2], m32 = data[6], m33 = data[10];
  4717. var trace = m11 + m22 + m33;
  4718. var s;
  4719. if (trace > 0) {
  4720. s = 0.5 / Math.sqrt(trace + 1.0);
  4721. result.w = 0.25 / s;
  4722. result.x = (m32 - m23) * s;
  4723. result.y = (m13 - m31) * s;
  4724. result.z = (m21 - m12) * s;
  4725. }
  4726. else if (m11 > m22 && m11 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4728. result.w = (m32 - m23) / s;
  4729. result.x = 0.25 * s;
  4730. result.y = (m12 + m21) / s;
  4731. result.z = (m13 + m31) / s;
  4732. }
  4733. else if (m22 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4735. result.w = (m13 - m31) / s;
  4736. result.x = (m12 + m21) / s;
  4737. result.y = 0.25 * s;
  4738. result.z = (m23 + m32) / s;
  4739. }
  4740. else {
  4741. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4742. result.w = (m21 - m12) / s;
  4743. result.x = (m13 + m31) / s;
  4744. result.y = (m23 + m32) / s;
  4745. result.z = 0.25 * s;
  4746. }
  4747. };
  4748. /**
  4749. * Returns the dot product (float) between the quaternions "left" and "right"
  4750. * @param left defines the left operand
  4751. * @param right defines the right operand
  4752. * @returns the dot product
  4753. */
  4754. Quaternion.Dot = function (left, right) {
  4755. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4756. };
  4757. /**
  4758. * Checks if the two quaternions are close to each other
  4759. * @param quat0 defines the first quaternion to check
  4760. * @param quat1 defines the second quaternion to check
  4761. * @returns true if the two quaternions are close to each other
  4762. */
  4763. Quaternion.AreClose = function (quat0, quat1) {
  4764. var dot = Quaternion.Dot(quat0, quat1);
  4765. return dot >= 0;
  4766. };
  4767. /**
  4768. * Creates an empty quaternion
  4769. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4770. */
  4771. Quaternion.Zero = function () {
  4772. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4773. };
  4774. /**
  4775. * Inverse a given quaternion
  4776. * @param q defines the source quaternion
  4777. * @returns a new quaternion as the inverted current quaternion
  4778. */
  4779. Quaternion.Inverse = function (q) {
  4780. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4781. };
  4782. /**
  4783. * Creates an identity quaternion
  4784. * @returns the identity quaternion
  4785. */
  4786. Quaternion.Identity = function () {
  4787. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4788. };
  4789. /**
  4790. * Gets a boolean indicating if the given quaternion is identity
  4791. * @param quaternion defines the quaternion to check
  4792. * @returns true if the quaternion is identity
  4793. */
  4794. Quaternion.IsIdentity = function (quaternion) {
  4795. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4796. };
  4797. /**
  4798. * Creates a quaternion from a rotation around an axis
  4799. * @param axis defines the axis to use
  4800. * @param angle defines the angle to use
  4801. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4802. */
  4803. Quaternion.RotationAxis = function (axis, angle) {
  4804. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4805. };
  4806. /**
  4807. * Creates a rotation around an axis and stores it into the given quaternion
  4808. * @param axis defines the axis to use
  4809. * @param angle defines the angle to use
  4810. * @param result defines the target quaternion
  4811. * @returns the target quaternion
  4812. */
  4813. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4814. var sin = Math.sin(angle / 2);
  4815. axis.normalize();
  4816. result.w = Math.cos(angle / 2);
  4817. result.x = axis.x * sin;
  4818. result.y = axis.y * sin;
  4819. result.z = axis.z * sin;
  4820. return result;
  4821. };
  4822. /**
  4823. * Creates a new quaternion from data stored into an array
  4824. * @param array defines the data source
  4825. * @param offset defines the offset in the source array where the data starts
  4826. * @returns a new quaternion
  4827. */
  4828. Quaternion.FromArray = function (array, offset) {
  4829. if (!offset) {
  4830. offset = 0;
  4831. }
  4832. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4833. };
  4834. /**
  4835. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4836. * @param yaw defines the rotation around Y axis
  4837. * @param pitch defines the rotation around X axis
  4838. * @param roll defines the rotation around Z axis
  4839. * @returns the new quaternion
  4840. */
  4841. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4842. var q = new Quaternion();
  4843. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4844. return q;
  4845. };
  4846. /**
  4847. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @param result defines the target quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4854. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4855. var halfRoll = roll * 0.5;
  4856. var halfPitch = pitch * 0.5;
  4857. var halfYaw = yaw * 0.5;
  4858. var sinRoll = Math.sin(halfRoll);
  4859. var cosRoll = Math.cos(halfRoll);
  4860. var sinPitch = Math.sin(halfPitch);
  4861. var cosPitch = Math.cos(halfPitch);
  4862. var sinYaw = Math.sin(halfYaw);
  4863. var cosYaw = Math.cos(halfYaw);
  4864. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4865. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4866. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4867. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4868. };
  4869. /**
  4870. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4871. * @param alpha defines the rotation around first axis
  4872. * @param beta defines the rotation around second axis
  4873. * @param gamma defines the rotation around third axis
  4874. * @returns the new quaternion
  4875. */
  4876. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4877. var result = new Quaternion();
  4878. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4879. return result;
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @param result defines the target quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4889. // Produces a quaternion from Euler angles in the z-x-z orientation
  4890. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4891. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4892. var halfBeta = beta * 0.5;
  4893. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4894. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4896. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. };
  4898. /**
  4899. * 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)
  4900. * @param axis1 defines the first axis
  4901. * @param axis2 defines the second axis
  4902. * @param axis3 defines the third axis
  4903. * @returns the new quaternion
  4904. */
  4905. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4906. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4907. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4908. return quat;
  4909. };
  4910. /**
  4911. * 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
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @param ref defines the target quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4918. var rotMat = MathTmp.Matrix[0];
  4919. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4920. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4921. };
  4922. /**
  4923. * Interpolates between two quaternions
  4924. * @param left defines first quaternion
  4925. * @param right defines second quaternion
  4926. * @param amount defines the gradient to use
  4927. * @returns the new interpolated quaternion
  4928. */
  4929. Quaternion.Slerp = function (left, right, amount) {
  4930. var result = Quaternion.Identity();
  4931. Quaternion.SlerpToRef(left, right, amount, result);
  4932. return result;
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions and stores it into a target quaternion
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @param result defines the target quaternion
  4940. */
  4941. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4942. var num2;
  4943. var num3;
  4944. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4945. var flag = false;
  4946. if (num4 < 0) {
  4947. flag = true;
  4948. num4 = -num4;
  4949. }
  4950. if (num4 > 0.999999) {
  4951. num3 = 1 - amount;
  4952. num2 = flag ? -amount : amount;
  4953. }
  4954. else {
  4955. var num5 = Math.acos(num4);
  4956. var num6 = (1.0 / Math.sin(num5));
  4957. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4958. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4959. }
  4960. result.x = (num3 * left.x) + (num2 * right.x);
  4961. result.y = (num3 * left.y) + (num2 * right.y);
  4962. result.z = (num3 * left.z) + (num2 * right.z);
  4963. result.w = (num3 * left.w) + (num2 * right.w);
  4964. };
  4965. /**
  4966. * Interpolate between two quaternions using Hermite interpolation
  4967. * @param value1 defines first quaternion
  4968. * @param tangent1 defines the incoming tangent
  4969. * @param value2 defines second quaternion
  4970. * @param tangent2 defines the outgoing tangent
  4971. * @param amount defines the target quaternion
  4972. * @returns the new interpolated quaternion
  4973. */
  4974. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4975. var squared = amount * amount;
  4976. var cubed = amount * squared;
  4977. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4978. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4979. var part3 = (cubed - (2.0 * squared)) + amount;
  4980. var part4 = cubed - squared;
  4981. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4982. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4983. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4984. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4985. return new Quaternion(x, y, z, w);
  4986. };
  4987. return Quaternion;
  4988. }());
  4989. BABYLON.Quaternion = Quaternion;
  4990. /**
  4991. * Class used to store matrix data (4x4)
  4992. */
  4993. var Matrix = /** @class */ (function () {
  4994. /**
  4995. * Creates an empty matrix (filled with zeros)
  4996. */
  4997. function Matrix() {
  4998. this._isIdentity = false;
  4999. this._isIdentityDirty = true;
  5000. /**
  5001. * Gets or sets the internal data of the matrix
  5002. */
  5003. this.m = new Float32Array(16);
  5004. this._markAsUpdated();
  5005. }
  5006. /** @hidden */
  5007. Matrix.prototype._markAsUpdated = function () {
  5008. this.updateFlag = Matrix._updateFlagSeed++;
  5009. this._isIdentityDirty = true;
  5010. };
  5011. // Properties
  5012. /**
  5013. * Check if the current matrix is indentity
  5014. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5015. * @returns true is the matrix is the identity matrix
  5016. */
  5017. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5018. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5019. if (this._isIdentityDirty) {
  5020. this._isIdentityDirty = false;
  5021. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5022. this._isIdentity = false;
  5023. }
  5024. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5025. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5026. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5027. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5028. this._isIdentity = false;
  5029. }
  5030. else {
  5031. this._isIdentity = true;
  5032. }
  5033. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. }
  5037. return this._isIdentity;
  5038. };
  5039. /**
  5040. * Gets the determinant of the matrix
  5041. * @returns the matrix determinant
  5042. */
  5043. Matrix.prototype.determinant = function () {
  5044. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5045. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5046. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5047. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5048. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5049. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5050. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5051. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5052. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5053. };
  5054. // Methods
  5055. /**
  5056. * Returns the matrix as a Float32Array
  5057. * @returns the matrix underlying array
  5058. */
  5059. Matrix.prototype.toArray = function () {
  5060. return this.m;
  5061. };
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array.
  5065. */
  5066. Matrix.prototype.asArray = function () {
  5067. return this.toArray();
  5068. };
  5069. /**
  5070. * Inverts the current matrix in place
  5071. * @returns the current inverted matrix
  5072. */
  5073. Matrix.prototype.invert = function () {
  5074. this.invertToRef(this);
  5075. return this;
  5076. };
  5077. /**
  5078. * Sets all the matrix elements to zero
  5079. * @returns the current matrix
  5080. */
  5081. Matrix.prototype.reset = function () {
  5082. for (var index = 0; index < 16; index++) {
  5083. this.m[index] = 0.0;
  5084. }
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Adds the current matrix with a second one
  5090. * @param other defines the matrix to add
  5091. * @returns a new matrix as the addition of the current matrix and the given one
  5092. */
  5093. Matrix.prototype.add = function (other) {
  5094. var result = new Matrix();
  5095. this.addToRef(other, result);
  5096. return result;
  5097. };
  5098. /**
  5099. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5100. * @param other defines the matrix to add
  5101. * @param result defines the target matrix
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.addToRef = function (other, result) {
  5105. for (var index = 0; index < 16; index++) {
  5106. result.m[index] = this.m[index] + other.m[index];
  5107. }
  5108. result._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds in place the given matrix to the current matrix
  5113. * @param other defines the second operand
  5114. * @returns the current updated matrix
  5115. */
  5116. Matrix.prototype.addToSelf = function (other) {
  5117. for (var index = 0; index < 16; index++) {
  5118. this.m[index] += other.m[index];
  5119. }
  5120. this._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Sets the given matrix to the current inverted Matrix
  5125. * @param other defines the target matrix
  5126. * @returns the unmodified current matrix
  5127. */
  5128. Matrix.prototype.invertToRef = function (other) {
  5129. var l1 = this.m[0];
  5130. var l2 = this.m[1];
  5131. var l3 = this.m[2];
  5132. var l4 = this.m[3];
  5133. var l5 = this.m[4];
  5134. var l6 = this.m[5];
  5135. var l7 = this.m[6];
  5136. var l8 = this.m[7];
  5137. var l9 = this.m[8];
  5138. var l10 = this.m[9];
  5139. var l11 = this.m[10];
  5140. var l12 = this.m[11];
  5141. var l13 = this.m[12];
  5142. var l14 = this.m[13];
  5143. var l15 = this.m[14];
  5144. var l16 = this.m[15];
  5145. var l17 = (l11 * l16) - (l12 * l15);
  5146. var l18 = (l10 * l16) - (l12 * l14);
  5147. var l19 = (l10 * l15) - (l11 * l14);
  5148. var l20 = (l9 * l16) - (l12 * l13);
  5149. var l21 = (l9 * l15) - (l11 * l13);
  5150. var l22 = (l9 * l14) - (l10 * l13);
  5151. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5152. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5153. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5154. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5155. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5156. var l28 = (l7 * l16) - (l8 * l15);
  5157. var l29 = (l6 * l16) - (l8 * l14);
  5158. var l30 = (l6 * l15) - (l7 * l14);
  5159. var l31 = (l5 * l16) - (l8 * l13);
  5160. var l32 = (l5 * l15) - (l7 * l13);
  5161. var l33 = (l5 * l14) - (l6 * l13);
  5162. var l34 = (l7 * l12) - (l8 * l11);
  5163. var l35 = (l6 * l12) - (l8 * l10);
  5164. var l36 = (l6 * l11) - (l7 * l10);
  5165. var l37 = (l5 * l12) - (l8 * l9);
  5166. var l38 = (l5 * l11) - (l7 * l9);
  5167. var l39 = (l5 * l10) - (l6 * l9);
  5168. other.m[0] = l23 * l27;
  5169. other.m[4] = l24 * l27;
  5170. other.m[8] = l25 * l27;
  5171. other.m[12] = l26 * l27;
  5172. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5173. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5174. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5175. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5176. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5177. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5178. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5179. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5180. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5181. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5182. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5183. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5184. other._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Inserts the translation vector (using 3 floats) in the current matrix
  5189. * @param x defines the 1st component of the translation
  5190. * @param y defines the 2nd component of the translation
  5191. * @param z defines the 3rd component of the translation
  5192. * @returns the current updated matrix
  5193. */
  5194. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5195. this.m[12] = x;
  5196. this.m[13] = y;
  5197. this.m[14] = z;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Inserts the translation vector in the current matrix
  5203. * @param vector3 defines the translation to insert
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslation = function (vector3) {
  5207. this.m[12] = vector3.x;
  5208. this.m[13] = vector3.y;
  5209. this.m[14] = vector3.z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Gets the translation value of the current matrix
  5215. * @returns a new Vector3 as the extracted translation from the matrix
  5216. */
  5217. Matrix.prototype.getTranslation = function () {
  5218. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5219. };
  5220. /**
  5221. * Fill a Vector3 with the extracted translation from the matrix
  5222. * @param result defines the Vector3 where to store the translation
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.getTranslationToRef = function (result) {
  5226. result.x = this.m[12];
  5227. result.y = this.m[13];
  5228. result.z = this.m[14];
  5229. return this;
  5230. };
  5231. /**
  5232. * Remove rotation and scaling part from the matrix
  5233. * @returns the updated matrix
  5234. */
  5235. Matrix.prototype.removeRotationAndScaling = function () {
  5236. this.setRowFromFloats(0, 1, 0, 0, 0);
  5237. this.setRowFromFloats(1, 0, 1, 0, 0);
  5238. this.setRowFromFloats(2, 0, 0, 1, 0);
  5239. return this;
  5240. };
  5241. /**
  5242. * Multiply two matrices
  5243. * @param other defines the second operand
  5244. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5245. */
  5246. Matrix.prototype.multiply = function (other) {
  5247. var result = new Matrix();
  5248. this.multiplyToRef(other, result);
  5249. return result;
  5250. };
  5251. /**
  5252. * Copy the current matrix from the given one
  5253. * @param other defines the source matrix
  5254. * @returns the current updated matrix
  5255. */
  5256. Matrix.prototype.copyFrom = function (other) {
  5257. for (var index = 0; index < 16; index++) {
  5258. this.m[index] = other.m[index];
  5259. }
  5260. this._markAsUpdated();
  5261. return this;
  5262. };
  5263. /**
  5264. * Populates the given array from the starting index with the current matrix values
  5265. * @param array defines the target array
  5266. * @param offset defines the offset in the target array where to start storing values
  5267. * @returns the current matrix
  5268. */
  5269. Matrix.prototype.copyToArray = function (array, offset) {
  5270. if (offset === void 0) { offset = 0; }
  5271. for (var index = 0; index < 16; index++) {
  5272. array[offset + index] = this.m[index];
  5273. }
  5274. return this;
  5275. };
  5276. /**
  5277. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5278. * @param other defines the second operand
  5279. * @param result defines the matrix where to store the multiplication
  5280. * @returns the current matrix
  5281. */
  5282. Matrix.prototype.multiplyToRef = function (other, result) {
  5283. this.multiplyToArray(other, result.m, 0);
  5284. result._markAsUpdated();
  5285. return this;
  5286. };
  5287. /**
  5288. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5289. * @param other defines the second operand
  5290. * @param result defines the array where to store the multiplication
  5291. * @param offset defines the offset in the target array where to start storing values
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5295. var tm0 = this.m[0];
  5296. var tm1 = this.m[1];
  5297. var tm2 = this.m[2];
  5298. var tm3 = this.m[3];
  5299. var tm4 = this.m[4];
  5300. var tm5 = this.m[5];
  5301. var tm6 = this.m[6];
  5302. var tm7 = this.m[7];
  5303. var tm8 = this.m[8];
  5304. var tm9 = this.m[9];
  5305. var tm10 = this.m[10];
  5306. var tm11 = this.m[11];
  5307. var tm12 = this.m[12];
  5308. var tm13 = this.m[13];
  5309. var tm14 = this.m[14];
  5310. var tm15 = this.m[15];
  5311. var om0 = other.m[0];
  5312. var om1 = other.m[1];
  5313. var om2 = other.m[2];
  5314. var om3 = other.m[3];
  5315. var om4 = other.m[4];
  5316. var om5 = other.m[5];
  5317. var om6 = other.m[6];
  5318. var om7 = other.m[7];
  5319. var om8 = other.m[8];
  5320. var om9 = other.m[9];
  5321. var om10 = other.m[10];
  5322. var om11 = other.m[11];
  5323. var om12 = other.m[12];
  5324. var om13 = other.m[13];
  5325. var om14 = other.m[14];
  5326. var om15 = other.m[15];
  5327. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5328. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5329. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5330. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5331. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5332. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5333. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5334. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5335. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5336. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5337. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5338. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5339. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5340. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5341. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5342. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5343. return this;
  5344. };
  5345. /**
  5346. * Check equality between this matrix and a second one
  5347. * @param value defines the second matrix to compare
  5348. * @returns true is the current matrix and the given one values are strictly equal
  5349. */
  5350. Matrix.prototype.equals = function (value) {
  5351. return value &&
  5352. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5353. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5354. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5355. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5356. };
  5357. /**
  5358. * Clone the current matrix
  5359. * @returns a new matrix from the current matrix
  5360. */
  5361. Matrix.prototype.clone = function () {
  5362. 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]);
  5363. };
  5364. /**
  5365. * Returns the name of the current matrix class
  5366. * @returns the string "Matrix"
  5367. */
  5368. Matrix.prototype.getClassName = function () {
  5369. return "Matrix";
  5370. };
  5371. /**
  5372. * Gets the hash code of the current matrix
  5373. * @returns the hash code
  5374. */
  5375. Matrix.prototype.getHashCode = function () {
  5376. var hash = this.m[0] || 0;
  5377. for (var i = 1; i < 16; i++) {
  5378. hash = (hash * 397) ^ (this.m[i] || 0);
  5379. }
  5380. return hash;
  5381. };
  5382. /**
  5383. * Decomposes the current Matrix into a translation, rotation and scaling components
  5384. * @param scale defines the scale vector3 given as a reference to update
  5385. * @param rotation defines the rotation quaternion given as a reference to update
  5386. * @param translation defines the translation vector3 given as a reference to update
  5387. * @returns true if operation was successful
  5388. */
  5389. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5390. if (translation) {
  5391. translation.x = this.m[12];
  5392. translation.y = this.m[13];
  5393. translation.z = this.m[14];
  5394. }
  5395. scale = scale || MathTmp.Vector3[0];
  5396. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5397. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5398. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5399. if (this.determinant() <= 0) {
  5400. scale.y *= -1;
  5401. }
  5402. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5403. if (rotation) {
  5404. rotation.x = 0;
  5405. rotation.y = 0;
  5406. rotation.z = 0;
  5407. rotation.w = 1;
  5408. }
  5409. return false;
  5410. }
  5411. if (rotation) {
  5412. 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]);
  5413. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5414. }
  5415. return true;
  5416. };
  5417. /**
  5418. * Gets specific row of the matrix
  5419. * @param index defines the number of the row to get
  5420. * @returns the index-th row of the current matrix as a new Vector4
  5421. */
  5422. Matrix.prototype.getRow = function (index) {
  5423. if (index < 0 || index > 3) {
  5424. return null;
  5425. }
  5426. var i = index * 4;
  5427. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5428. };
  5429. /**
  5430. * Sets the index-th row of the current matrix to the vector4 values
  5431. * @param index defines the number of the row to set
  5432. * @param row defines the target vector4
  5433. * @returns the updated current matrix
  5434. */
  5435. Matrix.prototype.setRow = function (index, row) {
  5436. if (index < 0 || index > 3) {
  5437. return this;
  5438. }
  5439. var i = index * 4;
  5440. this.m[i + 0] = row.x;
  5441. this.m[i + 1] = row.y;
  5442. this.m[i + 2] = row.z;
  5443. this.m[i + 3] = row.w;
  5444. this._markAsUpdated();
  5445. return this;
  5446. };
  5447. /**
  5448. * Compute the transpose of the matrix
  5449. * @returns the new transposed matrix
  5450. */
  5451. Matrix.prototype.transpose = function () {
  5452. return Matrix.Transpose(this);
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix and store it in a given matrix
  5456. * @param result defines the target matrix
  5457. * @returns the current matrix
  5458. */
  5459. Matrix.prototype.transposeToRef = function (result) {
  5460. Matrix.TransposeToRef(this, result);
  5461. return this;
  5462. };
  5463. /**
  5464. * Sets the index-th row of the current matrix with the given 4 x float values
  5465. * @param index defines the row index
  5466. * @param x defines the x component to set
  5467. * @param y defines the y component to set
  5468. * @param z defines the z component to set
  5469. * @param w defines the w component to set
  5470. * @returns the updated current matrix
  5471. */
  5472. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5473. if (index < 0 || index > 3) {
  5474. return this;
  5475. }
  5476. var i = index * 4;
  5477. this.m[i + 0] = x;
  5478. this.m[i + 1] = y;
  5479. this.m[i + 2] = z;
  5480. this.m[i + 3] = w;
  5481. this._markAsUpdated();
  5482. return this;
  5483. };
  5484. /**
  5485. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5486. * @param scale defines the scale factor
  5487. * @returns a new matrix
  5488. */
  5489. Matrix.prototype.scale = function (scale) {
  5490. var result = new Matrix();
  5491. this.scaleToRef(scale, result);
  5492. return result;
  5493. };
  5494. /**
  5495. * Scale the current matrix values by a factor to a given result matrix
  5496. * @param scale defines the scale factor
  5497. * @param result defines the matrix to store the result
  5498. * @returns the current matrix
  5499. */
  5500. Matrix.prototype.scaleToRef = function (scale, result) {
  5501. for (var index = 0; index < 16; index++) {
  5502. result.m[index] = this.m[index] * scale;
  5503. }
  5504. result._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Scale the current matrix values by a factor and add the result to a given matrix
  5509. * @param scale defines the scale factor
  5510. * @param result defines the Matrix to store the result
  5511. * @returns the current matrix
  5512. */
  5513. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5514. for (var index = 0; index < 16; index++) {
  5515. result.m[index] += this.m[index] * scale;
  5516. }
  5517. result._markAsUpdated();
  5518. return this;
  5519. };
  5520. /**
  5521. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5522. * @param ref matrix to store the result
  5523. */
  5524. Matrix.prototype.toNormalMatrix = function (ref) {
  5525. this.invertToRef(ref);
  5526. ref.transpose();
  5527. var m = ref.m;
  5528. 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);
  5529. };
  5530. /**
  5531. * Gets only rotation part of the current matrix
  5532. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5533. */
  5534. Matrix.prototype.getRotationMatrix = function () {
  5535. var result = Matrix.Identity();
  5536. this.getRotationMatrixToRef(result);
  5537. return result;
  5538. };
  5539. /**
  5540. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5541. * @param result defines the target matrix to store data to
  5542. * @returns the current matrix
  5543. */
  5544. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5545. var m = this.m;
  5546. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5547. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5548. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5549. if (this.determinant() <= 0) {
  5550. sy *= -1;
  5551. }
  5552. if (sx === 0 || sy === 0 || sz === 0) {
  5553. Matrix.IdentityToRef(result);
  5554. }
  5555. else {
  5556. 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);
  5557. }
  5558. return this;
  5559. };
  5560. // Statics
  5561. /**
  5562. * Creates a matrix from an array
  5563. * @param array defines the source array
  5564. * @param offset defines an offset in the source array
  5565. * @returns a new Matrix set from the starting index of the given array
  5566. */
  5567. Matrix.FromArray = function (array, offset) {
  5568. var result = new Matrix();
  5569. if (!offset) {
  5570. offset = 0;
  5571. }
  5572. Matrix.FromArrayToRef(array, offset, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Copy the content of an array into a given matrix
  5577. * @param array defines the source array
  5578. * @param offset defines an offset in the source array
  5579. * @param result defines the target matrix
  5580. */
  5581. Matrix.FromArrayToRef = function (array, offset, result) {
  5582. for (var index = 0; index < 16; index++) {
  5583. result.m[index] = array[index + offset];
  5584. }
  5585. result._markAsUpdated();
  5586. };
  5587. /**
  5588. * Stores an array into a matrix after having multiplied each component by a given factor
  5589. * @param array defines the source array
  5590. * @param offset defines the offset in the source array
  5591. * @param scale defines the scaling factor
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5595. for (var index = 0; index < 16; index++) {
  5596. result.m[index] = array[index + offset] * scale;
  5597. }
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Stores a list of values (16) inside a given matrix
  5602. * @param initialM11 defines 1st value of 1st row
  5603. * @param initialM12 defines 2nd value of 1st row
  5604. * @param initialM13 defines 3rd value of 1st row
  5605. * @param initialM14 defines 4th value of 1st row
  5606. * @param initialM21 defines 1st value of 2nd row
  5607. * @param initialM22 defines 2nd value of 2nd row
  5608. * @param initialM23 defines 3rd value of 2nd row
  5609. * @param initialM24 defines 4th value of 2nd row
  5610. * @param initialM31 defines 1st value of 3rd row
  5611. * @param initialM32 defines 2nd value of 3rd row
  5612. * @param initialM33 defines 3rd value of 3rd row
  5613. * @param initialM34 defines 4th value of 3rd row
  5614. * @param initialM41 defines 1st value of 4th row
  5615. * @param initialM42 defines 2nd value of 4th row
  5616. * @param initialM43 defines 3rd value of 4th row
  5617. * @param initialM44 defines 4th value of 4th row
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5621. result.m[0] = initialM11;
  5622. result.m[1] = initialM12;
  5623. result.m[2] = initialM13;
  5624. result.m[3] = initialM14;
  5625. result.m[4] = initialM21;
  5626. result.m[5] = initialM22;
  5627. result.m[6] = initialM23;
  5628. result.m[7] = initialM24;
  5629. result.m[8] = initialM31;
  5630. result.m[9] = initialM32;
  5631. result.m[10] = initialM33;
  5632. result.m[11] = initialM34;
  5633. result.m[12] = initialM41;
  5634. result.m[13] = initialM42;
  5635. result.m[14] = initialM43;
  5636. result.m[15] = initialM44;
  5637. result._markAsUpdated();
  5638. };
  5639. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5640. /**
  5641. * Gets an identity matrix that must not be updated
  5642. */
  5643. get: function () {
  5644. return Matrix._identityReadOnly;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. /**
  5650. * Creates new matrix from a list of values (16)
  5651. * @param initialM11 defines 1st value of 1st row
  5652. * @param initialM12 defines 2nd value of 1st row
  5653. * @param initialM13 defines 3rd value of 1st row
  5654. * @param initialM14 defines 4th value of 1st row
  5655. * @param initialM21 defines 1st value of 2nd row
  5656. * @param initialM22 defines 2nd value of 2nd row
  5657. * @param initialM23 defines 3rd value of 2nd row
  5658. * @param initialM24 defines 4th value of 2nd row
  5659. * @param initialM31 defines 1st value of 3rd row
  5660. * @param initialM32 defines 2nd value of 3rd row
  5661. * @param initialM33 defines 3rd value of 3rd row
  5662. * @param initialM34 defines 4th value of 3rd row
  5663. * @param initialM41 defines 1st value of 4th row
  5664. * @param initialM42 defines 2nd value of 4th row
  5665. * @param initialM43 defines 3rd value of 4th row
  5666. * @param initialM44 defines 4th value of 4th row
  5667. * @returns the new matrix
  5668. */
  5669. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5670. var result = new Matrix();
  5671. result.m[0] = initialM11;
  5672. result.m[1] = initialM12;
  5673. result.m[2] = initialM13;
  5674. result.m[3] = initialM14;
  5675. result.m[4] = initialM21;
  5676. result.m[5] = initialM22;
  5677. result.m[6] = initialM23;
  5678. result.m[7] = initialM24;
  5679. result.m[8] = initialM31;
  5680. result.m[9] = initialM32;
  5681. result.m[10] = initialM33;
  5682. result.m[11] = initialM34;
  5683. result.m[12] = initialM41;
  5684. result.m[13] = initialM42;
  5685. result.m[14] = initialM43;
  5686. result.m[15] = initialM44;
  5687. return result;
  5688. };
  5689. /**
  5690. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5691. * @param scale defines the scale vector3
  5692. * @param rotation defines the rotation quaternion
  5693. * @param translation defines the translation vector3
  5694. * @returns a new matrix
  5695. */
  5696. Matrix.Compose = function (scale, rotation, translation) {
  5697. var result = Matrix.Identity();
  5698. Matrix.ComposeToRef(scale, rotation, translation, result);
  5699. return result;
  5700. };
  5701. /**
  5702. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @param result defines the target matrix
  5707. */
  5708. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5709. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5710. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5711. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5712. result.setTranslation(translation);
  5713. };
  5714. /**
  5715. * Creates a new identity matrix
  5716. * @returns a new identity matrix
  5717. */
  5718. Matrix.Identity = function () {
  5719. 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);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix and stores the result in a given matrix
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.IdentityToRef = function (result) {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new zero matrix
  5730. * @returns a new zero matrix
  5731. */
  5732. Matrix.Zero = function () {
  5733. 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);
  5734. };
  5735. /**
  5736. * Creates a new rotation matrix for "angle" radians around the X axis
  5737. * @param angle defines the angle (in radians) to use
  5738. * @return the new matrix
  5739. */
  5740. Matrix.RotationX = function (angle) {
  5741. var result = new Matrix();
  5742. Matrix.RotationXToRef(angle, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Creates a new matrix as the invert of a given matrix
  5747. * @param source defines the source matrix
  5748. * @returns the new matrix
  5749. */
  5750. Matrix.Invert = function (source) {
  5751. var result = new Matrix();
  5752. source.invertToRef(result);
  5753. return result;
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5757. * @param angle defines the angle (in radians) to use
  5758. * @param result defines the target matrix
  5759. */
  5760. Matrix.RotationXToRef = function (angle, result) {
  5761. var s = Math.sin(angle);
  5762. var c = Math.cos(angle);
  5763. result.m[0] = 1.0;
  5764. result.m[15] = 1.0;
  5765. result.m[5] = c;
  5766. result.m[10] = c;
  5767. result.m[9] = -s;
  5768. result.m[6] = s;
  5769. result.m[1] = 0.0;
  5770. result.m[2] = 0.0;
  5771. result.m[3] = 0.0;
  5772. result.m[4] = 0.0;
  5773. result.m[7] = 0.0;
  5774. result.m[8] = 0.0;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = 0.0;
  5777. result.m[13] = 0.0;
  5778. result.m[14] = 0.0;
  5779. result._markAsUpdated();
  5780. };
  5781. /**
  5782. * Creates a new rotation matrix for "angle" radians around the Y axis
  5783. * @param angle defines the angle (in radians) to use
  5784. * @return the new matrix
  5785. */
  5786. Matrix.RotationY = function (angle) {
  5787. var result = new Matrix();
  5788. Matrix.RotationYToRef(angle, result);
  5789. return result;
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5793. * @param angle defines the angle (in radians) to use
  5794. * @param result defines the target matrix
  5795. */
  5796. Matrix.RotationYToRef = function (angle, result) {
  5797. var s = Math.sin(angle);
  5798. var c = Math.cos(angle);
  5799. result.m[5] = 1.0;
  5800. result.m[15] = 1.0;
  5801. result.m[0] = c;
  5802. result.m[2] = -s;
  5803. result.m[8] = s;
  5804. result.m[10] = c;
  5805. result.m[1] = 0.0;
  5806. result.m[3] = 0.0;
  5807. result.m[4] = 0.0;
  5808. result.m[6] = 0.0;
  5809. result.m[7] = 0.0;
  5810. result.m[9] = 0.0;
  5811. result.m[11] = 0.0;
  5812. result.m[12] = 0.0;
  5813. result.m[13] = 0.0;
  5814. result.m[14] = 0.0;
  5815. result._markAsUpdated();
  5816. };
  5817. /**
  5818. * Creates a new rotation matrix for "angle" radians around the Z axis
  5819. * @param angle defines the angle (in radians) to use
  5820. * @return the new matrix
  5821. */
  5822. Matrix.RotationZ = function (angle) {
  5823. var result = new Matrix();
  5824. Matrix.RotationZToRef(angle, result);
  5825. return result;
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5829. * @param angle defines the angle (in radians) to use
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.RotationZToRef = function (angle, result) {
  5833. var s = Math.sin(angle);
  5834. var c = Math.cos(angle);
  5835. result.m[10] = 1.0;
  5836. result.m[15] = 1.0;
  5837. result.m[0] = c;
  5838. result.m[1] = s;
  5839. result.m[4] = -s;
  5840. result.m[5] = c;
  5841. result.m[2] = 0.0;
  5842. result.m[3] = 0.0;
  5843. result.m[6] = 0.0;
  5844. result.m[7] = 0.0;
  5845. result.m[8] = 0.0;
  5846. result.m[9] = 0.0;
  5847. result.m[11] = 0.0;
  5848. result.m[12] = 0.0;
  5849. result.m[13] = 0.0;
  5850. result.m[14] = 0.0;
  5851. result._markAsUpdated();
  5852. };
  5853. /**
  5854. * Creates a new rotation matrix for "angle" radians around the given axis
  5855. * @param axis defines the axis to use
  5856. * @param angle defines the angle (in radians) to use
  5857. * @return the new matrix
  5858. */
  5859. Matrix.RotationAxis = function (axis, angle) {
  5860. var result = Matrix.Zero();
  5861. Matrix.RotationAxisToRef(axis, angle, result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5866. * @param axis defines the axis to use
  5867. * @param angle defines the angle (in radians) to use
  5868. * @param result defines the target matrix
  5869. */
  5870. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5871. var s = Math.sin(-angle);
  5872. var c = Math.cos(-angle);
  5873. var c1 = 1 - c;
  5874. axis.normalize();
  5875. result.m[0] = (axis.x * axis.x) * c1 + c;
  5876. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5877. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5878. result.m[3] = 0.0;
  5879. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5880. result.m[5] = (axis.y * axis.y) * c1 + c;
  5881. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5882. result.m[7] = 0.0;
  5883. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5884. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5885. result.m[10] = (axis.z * axis.z) * c1 + c;
  5886. result.m[11] = 0.0;
  5887. result.m[15] = 1.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a rotation matrix
  5892. * @param yaw defines the yaw angle in radians (Y axis)
  5893. * @param pitch defines the pitch angle in radians (X axis)
  5894. * @param roll defines the roll angle in radians (X axis)
  5895. * @returns the new rotation matrix
  5896. */
  5897. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5898. var result = new Matrix();
  5899. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5900. return result;
  5901. };
  5902. /**
  5903. * Creates a rotation matrix and stores it in a given matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5910. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5911. this._tempQuaternion.toRotationMatrix(result);
  5912. };
  5913. /**
  5914. * Creates a scaling matrix
  5915. * @param x defines the scale factor on X axis
  5916. * @param y defines the scale factor on Y axis
  5917. * @param z defines the scale factor on Z axis
  5918. * @returns the new matrix
  5919. */
  5920. Matrix.Scaling = function (x, y, z) {
  5921. var result = Matrix.Zero();
  5922. Matrix.ScalingToRef(x, y, z, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a scaling matrix and stores it in a given matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.ScalingToRef = function (x, y, z, result) {
  5933. result.m[0] = x;
  5934. result.m[1] = 0.0;
  5935. result.m[2] = 0.0;
  5936. result.m[3] = 0.0;
  5937. result.m[4] = 0.0;
  5938. result.m[5] = y;
  5939. result.m[6] = 0.0;
  5940. result.m[7] = 0.0;
  5941. result.m[8] = 0.0;
  5942. result.m[9] = 0.0;
  5943. result.m[10] = z;
  5944. result.m[11] = 0.0;
  5945. result.m[12] = 0.0;
  5946. result.m[13] = 0.0;
  5947. result.m[14] = 0.0;
  5948. result.m[15] = 1.0;
  5949. result._markAsUpdated();
  5950. };
  5951. /**
  5952. * Creates a translation matrix
  5953. * @param x defines the translation on X axis
  5954. * @param y defines the translation on Y axis
  5955. * @param z defines the translationon Z axis
  5956. * @returns the new matrix
  5957. */
  5958. Matrix.Translation = function (x, y, z) {
  5959. var result = Matrix.Identity();
  5960. Matrix.TranslationToRef(x, y, z, result);
  5961. return result;
  5962. };
  5963. /**
  5964. * Creates a translation matrix and stores it in a given matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @param result defines the target matrix
  5969. */
  5970. Matrix.TranslationToRef = function (x, y, z, result) {
  5971. 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);
  5972. };
  5973. /**
  5974. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5975. * @param startValue defines the start value
  5976. * @param endValue defines the end value
  5977. * @param gradient defines the gradient factor
  5978. * @returns the new matrix
  5979. */
  5980. Matrix.Lerp = function (startValue, endValue, gradient) {
  5981. var result = Matrix.Zero();
  5982. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @param result defines the Matrix object where to store data
  5991. */
  5992. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5993. for (var index = 0; index < 16; index++) {
  5994. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5995. }
  5996. result._markAsUpdated();
  5997. };
  5998. /**
  5999. * Builds a new matrix whose values are computed by:
  6000. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6001. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6002. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6003. * @param startValue defines the first matrix
  6004. * @param endValue defines the second matrix
  6005. * @param gradient defines the gradient between the two matrices
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6009. var result = Matrix.Zero();
  6010. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6011. return result;
  6012. };
  6013. /**
  6014. * Update a matrix to values which are computed by:
  6015. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6016. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6017. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6018. * @param startValue defines the first matrix
  6019. * @param endValue defines the second matrix
  6020. * @param gradient defines the gradient between the two matrices
  6021. * @param result defines the target matrix
  6022. */
  6023. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6024. var startScale = MathTmp.Vector3[0];
  6025. var startRotation = MathTmp.Quaternion[0];
  6026. var startTranslation = MathTmp.Vector3[1];
  6027. startValue.decompose(startScale, startRotation, startTranslation);
  6028. var endScale = MathTmp.Vector3[2];
  6029. var endRotation = MathTmp.Quaternion[1];
  6030. var endTranslation = MathTmp.Vector3[3];
  6031. endValue.decompose(endScale, endRotation, endTranslation);
  6032. var resultScale = MathTmp.Vector3[4];
  6033. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6034. var resultRotation = MathTmp.Quaternion[2];
  6035. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6036. var resultTranslation = MathTmp.Vector3[5];
  6037. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6038. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6039. };
  6040. /**
  6041. * 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"
  6042. * This function works in left handed mode
  6043. * @param eye defines the final position of the entity
  6044. * @param target defines where the entity should look at
  6045. * @param up defines the up vector for the entity
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.LookAtLH = function (eye, target, up) {
  6049. var result = Matrix.Zero();
  6050. Matrix.LookAtLHToRef(eye, target, up, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * 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".
  6055. * This function works in left handed mode
  6056. * @param eye defines the final position of the entity
  6057. * @param target defines where the entity should look at
  6058. * @param up defines the up vector for the entity
  6059. * @param result defines the target matrix
  6060. */
  6061. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6062. // Z axis
  6063. target.subtractToRef(eye, this._zAxis);
  6064. this._zAxis.normalize();
  6065. // X axis
  6066. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6067. if (this._xAxis.lengthSquared() === 0) {
  6068. this._xAxis.x = 1.0;
  6069. }
  6070. else {
  6071. this._xAxis.normalize();
  6072. }
  6073. // Y axis
  6074. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6075. this._yAxis.normalize();
  6076. // Eye angles
  6077. var ex = -Vector3.Dot(this._xAxis, eye);
  6078. var ey = -Vector3.Dot(this._yAxis, eye);
  6079. var ez = -Vector3.Dot(this._zAxis, eye);
  6080. 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);
  6081. };
  6082. /**
  6083. * 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"
  6084. * This function works in right handed mode
  6085. * @param eye defines the final position of the entity
  6086. * @param target defines where the entity should look at
  6087. * @param up defines the up vector for the entity
  6088. * @returns the new matrix
  6089. */
  6090. Matrix.LookAtRH = function (eye, target, up) {
  6091. var result = Matrix.Zero();
  6092. Matrix.LookAtRHToRef(eye, target, up, result);
  6093. return result;
  6094. };
  6095. /**
  6096. * 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".
  6097. * This function works in right handed mode
  6098. * @param eye defines the final position of the entity
  6099. * @param target defines where the entity should look at
  6100. * @param up defines the up vector for the entity
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6104. // Z axis
  6105. eye.subtractToRef(target, this._zAxis);
  6106. this._zAxis.normalize();
  6107. // X axis
  6108. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6109. if (this._xAxis.lengthSquared() === 0) {
  6110. this._xAxis.x = 1.0;
  6111. }
  6112. else {
  6113. this._xAxis.normalize();
  6114. }
  6115. // Y axis
  6116. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6117. this._yAxis.normalize();
  6118. // Eye angles
  6119. var ex = -Vector3.Dot(this._xAxis, eye);
  6120. var ey = -Vector3.Dot(this._yAxis, eye);
  6121. var ez = -Vector3.Dot(this._zAxis, eye);
  6122. 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);
  6123. };
  6124. /**
  6125. * Create a left-handed orthographic projection matrix
  6126. * @param width defines the viewport width
  6127. * @param height defines the viewport height
  6128. * @param znear defines the near clip plane
  6129. * @param zfar defines the far clip plane
  6130. * @returns a new matrix as a left-handed orthographic projection matrix
  6131. */
  6132. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6133. var matrix = Matrix.Zero();
  6134. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6135. return matrix;
  6136. };
  6137. /**
  6138. * Store a left-handed orthographic projection to a given matrix
  6139. * @param width defines the viewport width
  6140. * @param height defines the viewport height
  6141. * @param znear defines the near clip plane
  6142. * @param zfar defines the far clip plane
  6143. * @param result defines the target matrix
  6144. */
  6145. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6146. var n = znear;
  6147. var f = zfar;
  6148. var a = 2.0 / width;
  6149. var b = 2.0 / height;
  6150. var c = 2.0 / (f - n);
  6151. var d = -(f + n) / (f - n);
  6152. 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);
  6153. };
  6154. /**
  6155. * Create a left-handed orthographic projection matrix
  6156. * @param left defines the viewport left coordinate
  6157. * @param right defines the viewport right coordinate
  6158. * @param bottom defines the viewport bottom coordinate
  6159. * @param top defines the viewport top coordinate
  6160. * @param znear defines the near clip plane
  6161. * @param zfar defines the far clip plane
  6162. * @returns a new matrix as a left-handed orthographic projection matrix
  6163. */
  6164. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6165. var matrix = Matrix.Zero();
  6166. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6167. return matrix;
  6168. };
  6169. /**
  6170. * Stores a left-handed orthographic projection into a given matrix
  6171. * @param left defines the viewport left coordinate
  6172. * @param right defines the viewport right coordinate
  6173. * @param bottom defines the viewport bottom coordinate
  6174. * @param top defines the viewport top coordinate
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6180. var n = znear;
  6181. var f = zfar;
  6182. var a = 2.0 / (right - left);
  6183. var b = 2.0 / (top - bottom);
  6184. var c = 2.0 / (f - n);
  6185. var d = -(f + n) / (f - n);
  6186. var i0 = (left + right) / (left - right);
  6187. var i1 = (top + bottom) / (bottom - top);
  6188. 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);
  6189. };
  6190. /**
  6191. * Creates a right-handed orthographic projection matrix
  6192. * @param left defines the viewport left coordinate
  6193. * @param right defines the viewport right coordinate
  6194. * @param bottom defines the viewport bottom coordinate
  6195. * @param top defines the viewport top coordinate
  6196. * @param znear defines the near clip plane
  6197. * @param zfar defines the far clip plane
  6198. * @returns a new matrix as a right-handed orthographic projection matrix
  6199. */
  6200. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6201. var matrix = Matrix.Zero();
  6202. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6203. return matrix;
  6204. };
  6205. /**
  6206. * Stores a right-handed orthographic projection into a given matrix
  6207. * @param left defines the viewport left coordinate
  6208. * @param right defines the viewport right coordinate
  6209. * @param bottom defines the viewport bottom coordinate
  6210. * @param top defines the viewport top coordinate
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @param result defines the target matrix
  6214. */
  6215. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6216. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6217. result.m[10] *= -1.0;
  6218. };
  6219. /**
  6220. * Creates a left-handed perspective projection matrix
  6221. * @param width defines the viewport width
  6222. * @param height defines the viewport height
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a left-handed perspective projection matrix
  6226. */
  6227. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 * n / width;
  6232. var b = 2.0 * n / height;
  6233. var c = (f + n) / (f - n);
  6234. var d = -2.0 * f * n / (f - n);
  6235. 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);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Creates a left-handed perspective projection matrix
  6240. * @param fov defines the horizontal field of view
  6241. * @param aspect defines the aspect ratio
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @returns a new matrix as a left-handed perspective projection matrix
  6245. */
  6246. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6247. var matrix = Matrix.Zero();
  6248. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6249. return matrix;
  6250. };
  6251. /**
  6252. * Stores a left-handed perspective projection into a given matrix
  6253. * @param fov defines the horizontal field of view
  6254. * @param aspect defines the aspect ratio
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6259. */
  6260. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6261. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6262. var n = znear;
  6263. var f = zfar;
  6264. var t = 1.0 / (Math.tan(fov * 0.5));
  6265. var a = isVerticalFovFixed ? (t / aspect) : t;
  6266. var b = isVerticalFovFixed ? t : (t * aspect);
  6267. var c = (f + n) / (f - n);
  6268. var d = -2.0 * f * n / (f - n);
  6269. 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);
  6270. };
  6271. /**
  6272. * Creates a right-handed perspective projection matrix
  6273. * @param fov defines the horizontal field of view
  6274. * @param aspect defines the aspect ratio
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @returns a new matrix as a right-handed perspective projection matrix
  6278. */
  6279. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6280. var matrix = Matrix.Zero();
  6281. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6282. return matrix;
  6283. };
  6284. /**
  6285. * Stores a right-handed perspective projection into a given matrix
  6286. * @param fov defines the horizontal field of view
  6287. * @param aspect defines the aspect ratio
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6292. */
  6293. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6294. //alternatively this could be expressed as:
  6295. // m = PerspectiveFovLHToRef
  6296. // m[10] *= -1.0;
  6297. // m[11] *= -1.0;
  6298. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6299. var n = znear;
  6300. var f = zfar;
  6301. var t = 1.0 / (Math.tan(fov * 0.5));
  6302. var a = isVerticalFovFixed ? (t / aspect) : t;
  6303. var b = isVerticalFovFixed ? t : (t * aspect);
  6304. var c = -(f + n) / (f - n);
  6305. var d = -2 * f * n / (f - n);
  6306. 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);
  6307. };
  6308. /**
  6309. * Stores a perspective projection for WebVR info a given matrix
  6310. * @param fov defines the field of view
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6315. */
  6316. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6317. if (rightHanded === void 0) { rightHanded = false; }
  6318. var rightHandedFactor = rightHanded ? -1 : 1;
  6319. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6320. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6321. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6322. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6323. var xScale = 2.0 / (leftTan + rightTan);
  6324. var yScale = 2.0 / (upTan + downTan);
  6325. result.m[0] = xScale;
  6326. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6327. result.m[5] = yScale;
  6328. result.m[6] = result.m[7] = 0.0;
  6329. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6330. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6331. result.m[10] = -zfar / (znear - zfar);
  6332. result.m[11] = 1.0 * rightHandedFactor;
  6333. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6334. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Computes a complete transformation matrix
  6339. * @param viewport defines the viewport to use
  6340. * @param world defines the world matrix
  6341. * @param view defines the view matrix
  6342. * @param projection defines the projection matrix
  6343. * @param zmin defines the near clip plane
  6344. * @param zmax defines the far clip plane
  6345. * @returns the transformation matrix
  6346. */
  6347. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6348. var cw = viewport.width;
  6349. var ch = viewport.height;
  6350. var cx = viewport.x;
  6351. var cy = viewport.y;
  6352. 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);
  6353. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6354. };
  6355. /**
  6356. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6357. * @param matrix defines the matrix to use
  6358. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6359. */
  6360. Matrix.GetAsMatrix2x2 = function (matrix) {
  6361. return new Float32Array([
  6362. matrix.m[0], matrix.m[1],
  6363. matrix.m[4], matrix.m[5]
  6364. ]);
  6365. };
  6366. /**
  6367. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6368. * @param matrix defines the matrix to use
  6369. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6370. */
  6371. Matrix.GetAsMatrix3x3 = function (matrix) {
  6372. return new Float32Array([
  6373. matrix.m[0], matrix.m[1], matrix.m[2],
  6374. matrix.m[4], matrix.m[5], matrix.m[6],
  6375. matrix.m[8], matrix.m[9], matrix.m[10]
  6376. ]);
  6377. };
  6378. /**
  6379. * Compute the transpose of a given matrix
  6380. * @param matrix defines the matrix to transpose
  6381. * @returns the new matrix
  6382. */
  6383. Matrix.Transpose = function (matrix) {
  6384. var result = new Matrix();
  6385. Matrix.TransposeToRef(matrix, result);
  6386. return result;
  6387. };
  6388. /**
  6389. * Compute the transpose of a matrix and store it in a target matrix
  6390. * @param matrix defines the matrix to transpose
  6391. * @param result defines the target matrix
  6392. */
  6393. Matrix.TransposeToRef = function (matrix, result) {
  6394. result.m[0] = matrix.m[0];
  6395. result.m[1] = matrix.m[4];
  6396. result.m[2] = matrix.m[8];
  6397. result.m[3] = matrix.m[12];
  6398. result.m[4] = matrix.m[1];
  6399. result.m[5] = matrix.m[5];
  6400. result.m[6] = matrix.m[9];
  6401. result.m[7] = matrix.m[13];
  6402. result.m[8] = matrix.m[2];
  6403. result.m[9] = matrix.m[6];
  6404. result.m[10] = matrix.m[10];
  6405. result.m[11] = matrix.m[14];
  6406. result.m[12] = matrix.m[3];
  6407. result.m[13] = matrix.m[7];
  6408. result.m[14] = matrix.m[11];
  6409. result.m[15] = matrix.m[15];
  6410. };
  6411. /**
  6412. * Computes a reflection matrix from a plane
  6413. * @param plane defines the reflection plane
  6414. * @returns a new matrix
  6415. */
  6416. Matrix.Reflection = function (plane) {
  6417. var matrix = new Matrix();
  6418. Matrix.ReflectionToRef(plane, matrix);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Computes a reflection matrix from a plane
  6423. * @param plane defines the reflection plane
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.ReflectionToRef = function (plane, result) {
  6427. plane.normalize();
  6428. var x = plane.normal.x;
  6429. var y = plane.normal.y;
  6430. var z = plane.normal.z;
  6431. var temp = -2 * x;
  6432. var temp2 = -2 * y;
  6433. var temp3 = -2 * z;
  6434. result.m[0] = (temp * x) + 1;
  6435. result.m[1] = temp2 * x;
  6436. result.m[2] = temp3 * x;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = temp * y;
  6439. result.m[5] = (temp2 * y) + 1;
  6440. result.m[6] = temp3 * y;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = temp * z;
  6443. result.m[9] = temp2 * z;
  6444. result.m[10] = (temp3 * z) + 1;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = temp * plane.d;
  6447. result.m[13] = temp2 * plane.d;
  6448. result.m[14] = temp3 * plane.d;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6454. * @param xaxis defines the value of the 1st axis
  6455. * @param yaxis defines the value of the 2nd axis
  6456. * @param zaxis defines the value of the 3rd axis
  6457. * @param result defines the target matrix
  6458. */
  6459. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6460. result.m[0] = xaxis.x;
  6461. result.m[1] = xaxis.y;
  6462. result.m[2] = xaxis.z;
  6463. result.m[3] = 0.0;
  6464. result.m[4] = yaxis.x;
  6465. result.m[5] = yaxis.y;
  6466. result.m[6] = yaxis.z;
  6467. result.m[7] = 0.0;
  6468. result.m[8] = zaxis.x;
  6469. result.m[9] = zaxis.y;
  6470. result.m[10] = zaxis.z;
  6471. result.m[11] = 0.0;
  6472. result.m[12] = 0.0;
  6473. result.m[13] = 0.0;
  6474. result.m[14] = 0.0;
  6475. result.m[15] = 1.0;
  6476. result._markAsUpdated();
  6477. };
  6478. /**
  6479. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6480. * @param quat defines the quaternion to use
  6481. * @param result defines the target matrix
  6482. */
  6483. Matrix.FromQuaternionToRef = function (quat, result) {
  6484. var xx = quat.x * quat.x;
  6485. var yy = quat.y * quat.y;
  6486. var zz = quat.z * quat.z;
  6487. var xy = quat.x * quat.y;
  6488. var zw = quat.z * quat.w;
  6489. var zx = quat.z * quat.x;
  6490. var yw = quat.y * quat.w;
  6491. var yz = quat.y * quat.z;
  6492. var xw = quat.x * quat.w;
  6493. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6494. result.m[1] = 2.0 * (xy + zw);
  6495. result.m[2] = 2.0 * (zx - yw);
  6496. result.m[3] = 0.0;
  6497. result.m[4] = 2.0 * (xy - zw);
  6498. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6499. result.m[6] = 2.0 * (yz + xw);
  6500. result.m[7] = 0.0;
  6501. result.m[8] = 2.0 * (zx + yw);
  6502. result.m[9] = 2.0 * (yz - xw);
  6503. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6504. result.m[11] = 0.0;
  6505. result.m[12] = 0.0;
  6506. result.m[13] = 0.0;
  6507. result.m[14] = 0.0;
  6508. result.m[15] = 1.0;
  6509. result._markAsUpdated();
  6510. };
  6511. Matrix._tempQuaternion = new Quaternion();
  6512. Matrix._xAxis = Vector3.Zero();
  6513. Matrix._yAxis = Vector3.Zero();
  6514. Matrix._zAxis = Vector3.Zero();
  6515. Matrix._updateFlagSeed = 0;
  6516. Matrix._identityReadOnly = Matrix.Identity();
  6517. return Matrix;
  6518. }());
  6519. BABYLON.Matrix = Matrix;
  6520. var Plane = /** @class */ (function () {
  6521. /**
  6522. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6523. */
  6524. function Plane(a, b, c, d) {
  6525. this.normal = new Vector3(a, b, c);
  6526. this.d = d;
  6527. }
  6528. /**
  6529. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6530. */
  6531. Plane.prototype.asArray = function () {
  6532. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6533. };
  6534. // Methods
  6535. /**
  6536. * Returns a new plane copied from the current Plane.
  6537. */
  6538. Plane.prototype.clone = function () {
  6539. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6540. };
  6541. /**
  6542. * Returns the string "Plane".
  6543. */
  6544. Plane.prototype.getClassName = function () {
  6545. return "Plane";
  6546. };
  6547. /**
  6548. * Returns the Plane hash code.
  6549. */
  6550. Plane.prototype.getHashCode = function () {
  6551. var hash = this.normal.getHashCode();
  6552. hash = (hash * 397) ^ (this.d || 0);
  6553. return hash;
  6554. };
  6555. /**
  6556. * Normalize the current Plane in place.
  6557. * Returns the updated Plane.
  6558. */
  6559. Plane.prototype.normalize = function () {
  6560. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6561. var magnitude = 0.0;
  6562. if (norm !== 0) {
  6563. magnitude = 1.0 / norm;
  6564. }
  6565. this.normal.x *= magnitude;
  6566. this.normal.y *= magnitude;
  6567. this.normal.z *= magnitude;
  6568. this.d *= magnitude;
  6569. return this;
  6570. };
  6571. /**
  6572. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6573. */
  6574. Plane.prototype.transform = function (transformation) {
  6575. var transposedMatrix = Matrix.Transpose(transformation);
  6576. var x = this.normal.x;
  6577. var y = this.normal.y;
  6578. var z = this.normal.z;
  6579. var d = this.d;
  6580. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6581. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6582. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6583. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6584. return new Plane(normalX, normalY, normalZ, finalD);
  6585. };
  6586. /**
  6587. * Returns the dot product (float) of the point coordinates and the plane normal.
  6588. */
  6589. Plane.prototype.dotCoordinate = function (point) {
  6590. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6591. };
  6592. /**
  6593. * Updates the current Plane from the plane defined by the three given points.
  6594. * Returns the updated Plane.
  6595. */
  6596. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6597. var x1 = point2.x - point1.x;
  6598. var y1 = point2.y - point1.y;
  6599. var z1 = point2.z - point1.z;
  6600. var x2 = point3.x - point1.x;
  6601. var y2 = point3.y - point1.y;
  6602. var z2 = point3.z - point1.z;
  6603. var yz = (y1 * z2) - (z1 * y2);
  6604. var xz = (z1 * x2) - (x1 * z2);
  6605. var xy = (x1 * y2) - (y1 * x2);
  6606. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6607. var invPyth;
  6608. if (pyth !== 0) {
  6609. invPyth = 1.0 / pyth;
  6610. }
  6611. else {
  6612. invPyth = 0.0;
  6613. }
  6614. this.normal.x = yz * invPyth;
  6615. this.normal.y = xz * invPyth;
  6616. this.normal.z = xy * invPyth;
  6617. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6618. return this;
  6619. };
  6620. /**
  6621. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6622. */
  6623. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6624. var dot = Vector3.Dot(this.normal, direction);
  6625. return (dot <= epsilon);
  6626. };
  6627. /**
  6628. * Returns the signed distance (float) from the given point to the Plane.
  6629. */
  6630. Plane.prototype.signedDistanceTo = function (point) {
  6631. return Vector3.Dot(point, this.normal) + this.d;
  6632. };
  6633. // Statics
  6634. /**
  6635. * Returns a new Plane from the given array.
  6636. */
  6637. Plane.FromArray = function (array) {
  6638. return new Plane(array[0], array[1], array[2], array[3]);
  6639. };
  6640. /**
  6641. * Returns a new Plane defined by the three given points.
  6642. */
  6643. Plane.FromPoints = function (point1, point2, point3) {
  6644. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6645. result.copyFromPoints(point1, point2, point3);
  6646. return result;
  6647. };
  6648. /**
  6649. * Returns a new Plane the normal vector to this plane at the given origin point.
  6650. * Note : the vector "normal" is updated because normalized.
  6651. */
  6652. Plane.FromPositionAndNormal = function (origin, normal) {
  6653. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6654. normal.normalize();
  6655. result.normal = normal;
  6656. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6657. return result;
  6658. };
  6659. /**
  6660. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6661. */
  6662. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6663. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return Vector3.Dot(point, normal) + d;
  6665. };
  6666. return Plane;
  6667. }());
  6668. BABYLON.Plane = Plane;
  6669. var Viewport = /** @class */ (function () {
  6670. /**
  6671. * Creates a Viewport object located at (x, y) and sized (width, height).
  6672. */
  6673. function Viewport(x, y, width, height) {
  6674. this.x = x;
  6675. this.y = y;
  6676. this.width = width;
  6677. this.height = height;
  6678. }
  6679. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6680. if (renderWidthOrEngine.getRenderWidth) {
  6681. var engine = renderWidthOrEngine;
  6682. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6683. }
  6684. var renderWidth = renderWidthOrEngine;
  6685. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6686. };
  6687. /**
  6688. * Returns a new Viewport copied from the current one.
  6689. */
  6690. Viewport.prototype.clone = function () {
  6691. return new Viewport(this.x, this.y, this.width, this.height);
  6692. };
  6693. return Viewport;
  6694. }());
  6695. BABYLON.Viewport = Viewport;
  6696. var Frustum = /** @class */ (function () {
  6697. function Frustum() {
  6698. }
  6699. /**
  6700. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6701. */
  6702. Frustum.GetPlanes = function (transform) {
  6703. var frustumPlanes = [];
  6704. for (var index = 0; index < 6; index++) {
  6705. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6706. }
  6707. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6708. return frustumPlanes;
  6709. };
  6710. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6711. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6712. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6713. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6714. frustumPlane.d = transform.m[15] + transform.m[14];
  6715. frustumPlane.normalize();
  6716. };
  6717. Frustum.GetFarPlaneToRef = 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.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6726. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6727. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6728. frustumPlane.d = transform.m[15] + transform.m[12];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetRightPlaneToRef = 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.GetTopPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6742. frustumPlane.d = transform.m[15] - transform.m[13];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetBottomPlaneToRef = 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. /**
  6753. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6754. */
  6755. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6756. // Near
  6757. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6758. // Far
  6759. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6760. // Left
  6761. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6762. // Right
  6763. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6764. // Top
  6765. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6766. // Bottom
  6767. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6768. };
  6769. return Frustum;
  6770. }());
  6771. BABYLON.Frustum = Frustum;
  6772. /** Defines supported spaces */
  6773. var Space;
  6774. (function (Space) {
  6775. /** Local (object) space */
  6776. Space[Space["LOCAL"] = 0] = "LOCAL";
  6777. /** World space */
  6778. Space[Space["WORLD"] = 1] = "WORLD";
  6779. /** Bone space */
  6780. Space[Space["BONE"] = 2] = "BONE";
  6781. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6782. /** Defines the 3 main axes */
  6783. var Axis = /** @class */ (function () {
  6784. function Axis() {
  6785. }
  6786. /** X axis */
  6787. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6788. /** Y axis */
  6789. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6790. /** Z axis */
  6791. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6792. return Axis;
  6793. }());
  6794. BABYLON.Axis = Axis;
  6795. ;
  6796. var BezierCurve = /** @class */ (function () {
  6797. function BezierCurve() {
  6798. }
  6799. /**
  6800. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6801. */
  6802. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6803. // Extract X (which is equal to time here)
  6804. var f0 = 1 - 3 * x2 + 3 * x1;
  6805. var f1 = 3 * x2 - 6 * x1;
  6806. var f2 = 3 * x1;
  6807. var refinedT = t;
  6808. for (var i = 0; i < 5; i++) {
  6809. var refinedT2 = refinedT * refinedT;
  6810. var refinedT3 = refinedT2 * refinedT;
  6811. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6812. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6813. refinedT -= (x - t) * slope;
  6814. refinedT = Math.min(1, Math.max(0, refinedT));
  6815. }
  6816. // Resolve cubic bezier for the given x
  6817. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6818. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6819. Math.pow(refinedT, 3);
  6820. };
  6821. return BezierCurve;
  6822. }());
  6823. BABYLON.BezierCurve = BezierCurve;
  6824. /**
  6825. * Defines potential orientation for back face culling
  6826. */
  6827. var Orientation;
  6828. (function (Orientation) {
  6829. /**
  6830. * Clockwise
  6831. */
  6832. Orientation[Orientation["CW"] = 0] = "CW";
  6833. /** Counter clockwise */
  6834. Orientation[Orientation["CCW"] = 1] = "CCW";
  6835. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6836. /**
  6837. * Defines angle representation
  6838. */
  6839. var Angle = /** @class */ (function () {
  6840. /**
  6841. * Creates an Angle object of "radians" radians (float).
  6842. */
  6843. function Angle(radians) {
  6844. this._radians = radians;
  6845. if (this._radians < 0.0)
  6846. this._radians += (2.0 * Math.PI);
  6847. }
  6848. /**
  6849. * Get value in degrees
  6850. * @returns the Angle value in degrees (float)
  6851. */
  6852. Angle.prototype.degrees = function () {
  6853. return this._radians * 180.0 / Math.PI;
  6854. };
  6855. /**
  6856. * Get value in radians
  6857. * @returns the Angle value in radians (float)
  6858. */
  6859. Angle.prototype.radians = function () {
  6860. return this._radians;
  6861. };
  6862. /**
  6863. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6864. * @param a defines first vector
  6865. * @param b defines second vector
  6866. * @returns a new Angle
  6867. */
  6868. Angle.BetweenTwoPoints = function (a, b) {
  6869. var delta = b.subtract(a);
  6870. var theta = Math.atan2(delta.y, delta.x);
  6871. return new Angle(theta);
  6872. };
  6873. /**
  6874. * Gets a new Angle object from the given float in radians
  6875. * @param radians defines the angle value in radians
  6876. * @returns a new Angle
  6877. */
  6878. Angle.FromRadians = function (radians) {
  6879. return new Angle(radians);
  6880. };
  6881. /**
  6882. * Gets a new Angle object from the given float in degrees
  6883. * @param degrees defines the angle value in degrees
  6884. * @returns a new Angle
  6885. */
  6886. Angle.FromDegrees = function (degrees) {
  6887. return new Angle(degrees * Math.PI / 180.0);
  6888. };
  6889. return Angle;
  6890. }());
  6891. BABYLON.Angle = Angle;
  6892. var Arc2 = /** @class */ (function () {
  6893. /**
  6894. * Creates an Arc object from the three given points : start, middle and end.
  6895. */
  6896. function Arc2(startPoint, midPoint, endPoint) {
  6897. this.startPoint = startPoint;
  6898. this.midPoint = midPoint;
  6899. this.endPoint = endPoint;
  6900. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6901. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6902. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6903. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6904. 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);
  6905. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6906. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6907. var a1 = this.startAngle.degrees();
  6908. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6909. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6910. // angles correction
  6911. if (a2 - a1 > +180.0)
  6912. a2 -= 360.0;
  6913. if (a2 - a1 < -180.0)
  6914. a2 += 360.0;
  6915. if (a3 - a2 > +180.0)
  6916. a3 -= 360.0;
  6917. if (a3 - a2 < -180.0)
  6918. a3 += 360.0;
  6919. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6920. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6921. }
  6922. return Arc2;
  6923. }());
  6924. BABYLON.Arc2 = Arc2;
  6925. var Path2 = /** @class */ (function () {
  6926. /**
  6927. * Creates a Path2 object from the starting 2D coordinates x and y.
  6928. */
  6929. function Path2(x, y) {
  6930. this._points = new Array();
  6931. this._length = 0.0;
  6932. this.closed = false;
  6933. this._points.push(new Vector2(x, y));
  6934. }
  6935. /**
  6936. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6937. * Returns the updated Path2.
  6938. */
  6939. Path2.prototype.addLineTo = function (x, y) {
  6940. if (this.closed) {
  6941. return this;
  6942. }
  6943. var newPoint = new Vector2(x, y);
  6944. var previousPoint = this._points[this._points.length - 1];
  6945. this._points.push(newPoint);
  6946. this._length += newPoint.subtract(previousPoint).length();
  6947. return this;
  6948. };
  6949. /**
  6950. * 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.
  6951. * Returns the updated Path2.
  6952. */
  6953. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6954. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6955. if (this.closed) {
  6956. return this;
  6957. }
  6958. var startPoint = this._points[this._points.length - 1];
  6959. var midPoint = new Vector2(midX, midY);
  6960. var endPoint = new Vector2(endX, endY);
  6961. var arc = new Arc2(startPoint, midPoint, endPoint);
  6962. var increment = arc.angle.radians() / numberOfSegments;
  6963. if (arc.orientation === Orientation.CW)
  6964. increment *= -1;
  6965. var currentAngle = arc.startAngle.radians() + increment;
  6966. for (var i = 0; i < numberOfSegments; i++) {
  6967. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6968. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6969. this.addLineTo(x, y);
  6970. currentAngle += increment;
  6971. }
  6972. return this;
  6973. };
  6974. /**
  6975. * Closes the Path2.
  6976. * Returns the Path2.
  6977. */
  6978. Path2.prototype.close = function () {
  6979. this.closed = true;
  6980. return this;
  6981. };
  6982. /**
  6983. * Returns the Path2 total length (float).
  6984. */
  6985. Path2.prototype.length = function () {
  6986. var result = this._length;
  6987. if (!this.closed) {
  6988. var lastPoint = this._points[this._points.length - 1];
  6989. var firstPoint = this._points[0];
  6990. result += (firstPoint.subtract(lastPoint).length());
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns the Path2 internal array of points.
  6996. */
  6997. Path2.prototype.getPoints = function () {
  6998. return this._points;
  6999. };
  7000. /**
  7001. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7002. */
  7003. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7004. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7005. return Vector2.Zero();
  7006. }
  7007. var lengthPosition = normalizedLengthPosition * this.length();
  7008. var previousOffset = 0;
  7009. for (var i = 0; i < this._points.length; i++) {
  7010. var j = (i + 1) % this._points.length;
  7011. var a = this._points[i];
  7012. var b = this._points[j];
  7013. var bToA = b.subtract(a);
  7014. var nextOffset = (bToA.length() + previousOffset);
  7015. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7016. var dir = bToA.normalize();
  7017. var localOffset = lengthPosition - previousOffset;
  7018. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7019. }
  7020. previousOffset = nextOffset;
  7021. }
  7022. return Vector2.Zero();
  7023. };
  7024. /**
  7025. * Returns a new Path2 starting at the coordinates (x, y).
  7026. */
  7027. Path2.StartingAt = function (x, y) {
  7028. return new Path2(x, y);
  7029. };
  7030. return Path2;
  7031. }());
  7032. BABYLON.Path2 = Path2;
  7033. var Path3D = /** @class */ (function () {
  7034. /**
  7035. * new Path3D(path, normal, raw)
  7036. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7037. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7038. * path : an array of Vector3, the curve axis of the Path3D
  7039. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7040. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7041. */
  7042. function Path3D(path, firstNormal, raw) {
  7043. if (firstNormal === void 0) { firstNormal = null; }
  7044. this.path = path;
  7045. this._curve = new Array();
  7046. this._distances = new Array();
  7047. this._tangents = new Array();
  7048. this._normals = new Array();
  7049. this._binormals = new Array();
  7050. for (var p = 0; p < path.length; p++) {
  7051. this._curve[p] = path[p].clone(); // hard copy
  7052. }
  7053. this._raw = raw || false;
  7054. this._compute(firstNormal);
  7055. }
  7056. /**
  7057. * Returns the Path3D array of successive Vector3 designing its curve.
  7058. */
  7059. Path3D.prototype.getCurve = function () {
  7060. return this._curve;
  7061. };
  7062. /**
  7063. * Returns an array populated with tangent vectors on each Path3D curve point.
  7064. */
  7065. Path3D.prototype.getTangents = function () {
  7066. return this._tangents;
  7067. };
  7068. /**
  7069. * Returns an array populated with normal vectors on each Path3D curve point.
  7070. */
  7071. Path3D.prototype.getNormals = function () {
  7072. return this._normals;
  7073. };
  7074. /**
  7075. * Returns an array populated with binormal vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getBinormals = function () {
  7078. return this._binormals;
  7079. };
  7080. /**
  7081. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7082. */
  7083. Path3D.prototype.getDistances = function () {
  7084. return this._distances;
  7085. };
  7086. /**
  7087. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7088. * Returns the same object updated.
  7089. */
  7090. Path3D.prototype.update = function (path, firstNormal) {
  7091. if (firstNormal === void 0) { firstNormal = null; }
  7092. for (var p = 0; p < path.length; p++) {
  7093. this._curve[p].x = path[p].x;
  7094. this._curve[p].y = path[p].y;
  7095. this._curve[p].z = path[p].z;
  7096. }
  7097. this._compute(firstNormal);
  7098. return this;
  7099. };
  7100. // private function compute() : computes tangents, normals and binormals
  7101. Path3D.prototype._compute = function (firstNormal) {
  7102. var l = this._curve.length;
  7103. // first and last tangents
  7104. this._tangents[0] = this._getFirstNonNullVector(0);
  7105. if (!this._raw) {
  7106. this._tangents[0].normalize();
  7107. }
  7108. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7109. if (!this._raw) {
  7110. this._tangents[l - 1].normalize();
  7111. }
  7112. // normals and binormals at first point : arbitrary vector with _normalVector()
  7113. var tg0 = this._tangents[0];
  7114. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7115. this._normals[0] = pp0;
  7116. if (!this._raw) {
  7117. this._normals[0].normalize();
  7118. }
  7119. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7120. if (!this._raw) {
  7121. this._binormals[0].normalize();
  7122. }
  7123. this._distances[0] = 0.0;
  7124. // normals and binormals : next points
  7125. var prev; // previous vector (segment)
  7126. var cur; // current vector (segment)
  7127. var curTang; // current tangent
  7128. // previous normal
  7129. var prevBinor; // previous binormal
  7130. for (var i = 1; i < l; i++) {
  7131. // tangents
  7132. prev = this._getLastNonNullVector(i);
  7133. if (i < l - 1) {
  7134. cur = this._getFirstNonNullVector(i);
  7135. this._tangents[i] = prev.add(cur);
  7136. this._tangents[i].normalize();
  7137. }
  7138. this._distances[i] = this._distances[i - 1] + prev.length();
  7139. // normals and binormals
  7140. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7141. curTang = this._tangents[i];
  7142. prevBinor = this._binormals[i - 1];
  7143. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7144. if (!this._raw) {
  7145. this._normals[i].normalize();
  7146. }
  7147. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7148. if (!this._raw) {
  7149. this._binormals[i].normalize();
  7150. }
  7151. }
  7152. };
  7153. // private function getFirstNonNullVector(index)
  7154. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7155. Path3D.prototype._getFirstNonNullVector = function (index) {
  7156. var i = 1;
  7157. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7158. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7159. i++;
  7160. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7161. }
  7162. return nNVector;
  7163. };
  7164. // private function getLastNonNullVector(index)
  7165. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7166. Path3D.prototype._getLastNonNullVector = function (index) {
  7167. var i = 1;
  7168. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7169. while (nLVector.length() === 0 && index > i + 1) {
  7170. i++;
  7171. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7172. }
  7173. return nLVector;
  7174. };
  7175. // private function normalVector(v0, vt, va) :
  7176. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7177. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7178. Path3D.prototype._normalVector = function (v0, vt, va) {
  7179. var normal0;
  7180. var tgl = vt.length();
  7181. if (tgl === 0.0) {
  7182. tgl = 1.0;
  7183. }
  7184. if (va === undefined || va === null) {
  7185. var point;
  7186. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7187. point = new Vector3(0.0, -1.0, 0.0);
  7188. }
  7189. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7190. point = new Vector3(1.0, 0.0, 0.0);
  7191. }
  7192. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7193. point = new Vector3(0.0, 0.0, 1.0);
  7194. }
  7195. else {
  7196. point = Vector3.Zero();
  7197. }
  7198. normal0 = Vector3.Cross(vt, point);
  7199. }
  7200. else {
  7201. normal0 = Vector3.Cross(vt, va);
  7202. Vector3.CrossToRef(normal0, vt, normal0);
  7203. }
  7204. normal0.normalize();
  7205. return normal0;
  7206. };
  7207. return Path3D;
  7208. }());
  7209. BABYLON.Path3D = Path3D;
  7210. var Curve3 = /** @class */ (function () {
  7211. /**
  7212. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7213. * A Curve3 is designed from a series of successive Vector3.
  7214. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7215. */
  7216. function Curve3(points) {
  7217. this._length = 0.0;
  7218. this._points = points;
  7219. this._length = this._computeLength(points);
  7220. }
  7221. /**
  7222. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7223. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7224. * @param v1 (Vector3) the control point
  7225. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7226. * @param nbPoints (integer) the wanted number of points in the curve
  7227. */
  7228. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7229. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7230. var bez = new Array();
  7231. var equation = function (t, val0, val1, val2) {
  7232. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7233. return res;
  7234. };
  7235. for (var i = 0; i <= nbPoints; i++) {
  7236. 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)));
  7237. }
  7238. return new Curve3(bez);
  7239. };
  7240. /**
  7241. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7242. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7243. * @param v1 (Vector3) the first control point
  7244. * @param v2 (Vector3) the second control point
  7245. * @param v3 (Vector3) the end point of the Cubic Bezier
  7246. * @param nbPoints (integer) the wanted number of points in the curve
  7247. */
  7248. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7249. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7250. var bez = new Array();
  7251. var equation = function (t, val0, val1, val2, val3) {
  7252. 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;
  7253. return res;
  7254. };
  7255. for (var i = 0; i <= nbPoints; i++) {
  7256. 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)));
  7257. }
  7258. return new Curve3(bez);
  7259. };
  7260. /**
  7261. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7262. * @param p1 (Vector3) the origin point of the Hermite Spline
  7263. * @param t1 (Vector3) the tangent vector at the origin point
  7264. * @param p2 (Vector3) the end point of the Hermite Spline
  7265. * @param t2 (Vector3) the tangent vector at the end point
  7266. * @param nbPoints (integer) the wanted number of points in the curve
  7267. */
  7268. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7269. var hermite = new Array();
  7270. var step = 1.0 / nbPoints;
  7271. for (var i = 0; i <= nbPoints; i++) {
  7272. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7273. }
  7274. return new Curve3(hermite);
  7275. };
  7276. /**
  7277. * Returns a Curve3 object along a CatmullRom Spline curve :
  7278. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7279. * @param nbPoints (integer) the wanted number of points between each curve control points
  7280. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7283. var catmullRom = new Array();
  7284. var step = 1.0 / nbPoints;
  7285. var amount = 0.0;
  7286. if (closed) {
  7287. var pointsCount = points.length;
  7288. for (var i = 0; i < pointsCount; i++) {
  7289. amount = 0;
  7290. for (var c = 0; c < nbPoints; c++) {
  7291. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7292. amount += step;
  7293. }
  7294. }
  7295. catmullRom.push(catmullRom[0]);
  7296. }
  7297. else {
  7298. var totalPoints = new Array();
  7299. totalPoints.push(points[0].clone());
  7300. Array.prototype.push.apply(totalPoints, points);
  7301. totalPoints.push(points[points.length - 1].clone());
  7302. for (var i = 0; i < totalPoints.length - 3; i++) {
  7303. amount = 0;
  7304. for (var c = 0; c < nbPoints; c++) {
  7305. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7306. amount += step;
  7307. }
  7308. }
  7309. i--;
  7310. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7311. }
  7312. return new Curve3(catmullRom);
  7313. };
  7314. /**
  7315. * Returns the Curve3 stored array of successive Vector3
  7316. */
  7317. Curve3.prototype.getPoints = function () {
  7318. return this._points;
  7319. };
  7320. /**
  7321. * Returns the computed length (float) of the curve.
  7322. */
  7323. Curve3.prototype.length = function () {
  7324. return this._length;
  7325. };
  7326. /**
  7327. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7328. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7329. * curveA and curveB keep unchanged.
  7330. */
  7331. Curve3.prototype.continue = function (curve) {
  7332. var lastPoint = this._points[this._points.length - 1];
  7333. var continuedPoints = this._points.slice();
  7334. var curvePoints = curve.getPoints();
  7335. for (var i = 1; i < curvePoints.length; i++) {
  7336. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7337. }
  7338. var continuedCurve = new Curve3(continuedPoints);
  7339. return continuedCurve;
  7340. };
  7341. Curve3.prototype._computeLength = function (path) {
  7342. var l = 0;
  7343. for (var i = 1; i < path.length; i++) {
  7344. l += (path[i].subtract(path[i - 1])).length();
  7345. }
  7346. return l;
  7347. };
  7348. return Curve3;
  7349. }());
  7350. BABYLON.Curve3 = Curve3;
  7351. // Vertex formats
  7352. var PositionNormalVertex = /** @class */ (function () {
  7353. function PositionNormalVertex(position, normal) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. this.position = position;
  7357. this.normal = normal;
  7358. }
  7359. PositionNormalVertex.prototype.clone = function () {
  7360. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7361. };
  7362. return PositionNormalVertex;
  7363. }());
  7364. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7365. var PositionNormalTextureVertex = /** @class */ (function () {
  7366. function PositionNormalTextureVertex(position, normal, uv) {
  7367. if (position === void 0) { position = Vector3.Zero(); }
  7368. if (normal === void 0) { normal = Vector3.Up(); }
  7369. if (uv === void 0) { uv = Vector2.Zero(); }
  7370. this.position = position;
  7371. this.normal = normal;
  7372. this.uv = uv;
  7373. }
  7374. PositionNormalTextureVertex.prototype.clone = function () {
  7375. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7376. };
  7377. return PositionNormalTextureVertex;
  7378. }());
  7379. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7380. // Temporary pre-allocated objects for engine internal use
  7381. // usage in any internal function :
  7382. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7383. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7384. var Tmp = /** @class */ (function () {
  7385. function Tmp() {
  7386. }
  7387. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7388. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7389. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7390. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7391. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7392. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7393. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7394. Matrix.Zero(), Matrix.Zero(),
  7395. Matrix.Zero(), Matrix.Zero(),
  7396. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7397. return Tmp;
  7398. }());
  7399. BABYLON.Tmp = Tmp;
  7400. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7401. var MathTmp = /** @class */ (function () {
  7402. function MathTmp() {
  7403. }
  7404. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7405. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7406. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7407. return MathTmp;
  7408. }());
  7409. })(BABYLON || (BABYLON = {}));
  7410. //# sourceMappingURL=babylon.math.js.map
  7411. var BABYLON;
  7412. (function (BABYLON) {
  7413. var Scalar = /** @class */ (function () {
  7414. function Scalar() {
  7415. }
  7416. /**
  7417. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7418. */
  7419. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7420. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7421. var num = a - b;
  7422. return -epsilon <= num && num <= epsilon;
  7423. };
  7424. /**
  7425. * Returns a string : the upper case translation of the number i to hexadecimal.
  7426. */
  7427. Scalar.ToHex = function (i) {
  7428. var str = i.toString(16);
  7429. if (i <= 15) {
  7430. return ("0" + str).toUpperCase();
  7431. }
  7432. return str.toUpperCase();
  7433. };
  7434. /**
  7435. * Returns -1 if value is negative and +1 is value is positive.
  7436. * Returns the value itself if it's equal to zero.
  7437. */
  7438. Scalar.Sign = function (value) {
  7439. value = +value; // convert to a number
  7440. if (value === 0 || isNaN(value))
  7441. return value;
  7442. return value > 0 ? 1 : -1;
  7443. };
  7444. /**
  7445. * Returns the value itself if it's between min and max.
  7446. * Returns min if the value is lower than min.
  7447. * Returns max if the value is greater than max.
  7448. */
  7449. Scalar.Clamp = function (value, min, max) {
  7450. if (min === void 0) { min = 0; }
  7451. if (max === void 0) { max = 1; }
  7452. return Math.min(max, Math.max(min, value));
  7453. };
  7454. /**
  7455. * Returns the log2 of value.
  7456. */
  7457. Scalar.Log2 = function (value) {
  7458. return Math.log(value) * Math.LOG2E;
  7459. };
  7460. /**
  7461. * Loops the value, so that it is never larger than length and never smaller than 0.
  7462. *
  7463. * This is similar to the modulo operator but it works with floating point numbers.
  7464. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7465. * With t = 5 and length = 2.5, the result would be 0.0.
  7466. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7467. */
  7468. Scalar.Repeat = function (value, length) {
  7469. return value - Math.floor(value / length) * length;
  7470. };
  7471. /**
  7472. * Normalize the value between 0.0 and 1.0 using min and max values
  7473. */
  7474. Scalar.Normalize = function (value, min, max) {
  7475. return (value - min) / (max - min);
  7476. };
  7477. /**
  7478. * Denormalize the value from 0.0 and 1.0 using min and max values
  7479. */
  7480. Scalar.Denormalize = function (normalized, min, max) {
  7481. return (normalized * (max - min) + min);
  7482. };
  7483. /**
  7484. * Calculates the shortest difference between two given angles given in degrees.
  7485. */
  7486. Scalar.DeltaAngle = function (current, target) {
  7487. var num = Scalar.Repeat(target - current, 360.0);
  7488. if (num > 180.0) {
  7489. num -= 360.0;
  7490. }
  7491. return num;
  7492. };
  7493. /**
  7494. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7495. *
  7496. * The returned value will move back and forth between 0 and length
  7497. */
  7498. Scalar.PingPong = function (tx, length) {
  7499. var t = Scalar.Repeat(tx, length * 2.0);
  7500. return length - Math.abs(t - length);
  7501. };
  7502. /**
  7503. * Interpolates between min and max with smoothing at the limits.
  7504. *
  7505. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7506. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7507. */
  7508. Scalar.SmoothStep = function (from, to, tx) {
  7509. var t = Scalar.Clamp(tx);
  7510. t = -2.0 * t * t * t + 3.0 * t * t;
  7511. return to * t + from * (1.0 - t);
  7512. };
  7513. /**
  7514. * Moves a value current towards target.
  7515. *
  7516. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7517. * Negative values of maxDelta pushes the value away from target.
  7518. */
  7519. Scalar.MoveTowards = function (current, target, maxDelta) {
  7520. var result = 0;
  7521. if (Math.abs(target - current) <= maxDelta) {
  7522. result = target;
  7523. }
  7524. else {
  7525. result = current + Scalar.Sign(target - current) * maxDelta;
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7531. *
  7532. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7533. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7534. */
  7535. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7536. var num = Scalar.DeltaAngle(current, target);
  7537. var result = 0;
  7538. if (-maxDelta < num && num < maxDelta) {
  7539. result = target;
  7540. }
  7541. else {
  7542. target = current + num;
  7543. result = Scalar.MoveTowards(current, target, maxDelta);
  7544. }
  7545. return result;
  7546. };
  7547. /**
  7548. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7549. */
  7550. Scalar.Lerp = function (start, end, amount) {
  7551. return start + ((end - start) * amount);
  7552. };
  7553. /**
  7554. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7555. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7556. */
  7557. Scalar.LerpAngle = function (start, end, amount) {
  7558. var num = Scalar.Repeat(end - start, 360.0);
  7559. if (num > 180.0) {
  7560. num -= 360.0;
  7561. }
  7562. return start + num * Scalar.Clamp(amount);
  7563. };
  7564. /**
  7565. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7566. */
  7567. Scalar.InverseLerp = function (a, b, value) {
  7568. var result = 0;
  7569. if (a != b) {
  7570. result = Scalar.Clamp((value - a) / (b - a));
  7571. }
  7572. else {
  7573. result = 0.0;
  7574. }
  7575. return result;
  7576. };
  7577. /**
  7578. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7579. */
  7580. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7581. var squared = amount * amount;
  7582. var cubed = amount * squared;
  7583. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7584. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7585. var part3 = (cubed - (2.0 * squared)) + amount;
  7586. var part4 = cubed - squared;
  7587. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7588. };
  7589. /**
  7590. * Returns a random float number between and min and max values
  7591. */
  7592. Scalar.RandomRange = function (min, max) {
  7593. if (min === max)
  7594. return min;
  7595. return ((Math.random() * (max - min)) + min);
  7596. };
  7597. /**
  7598. * This function returns percentage of a number in a given range.
  7599. *
  7600. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7601. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7602. */
  7603. Scalar.RangeToPercent = function (number, min, max) {
  7604. return ((number - min) / (max - min));
  7605. };
  7606. /**
  7607. * This function returns number that corresponds to the percentage in a given range.
  7608. *
  7609. * PercentToRange(0.34,0,100) will return 34.
  7610. */
  7611. Scalar.PercentToRange = function (percent, min, max) {
  7612. return ((max - min) * percent + min);
  7613. };
  7614. /**
  7615. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7616. * @param angle The angle to normalize in radian.
  7617. * @return The converted angle.
  7618. */
  7619. Scalar.NormalizeRadians = function (angle) {
  7620. // More precise but slower version kept for reference.
  7621. // angle = angle % Tools.TwoPi;
  7622. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7623. //if (angle > Math.PI) {
  7624. // angle -= Tools.TwoPi;
  7625. //}
  7626. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7627. return angle;
  7628. };
  7629. /**
  7630. * Two pi constants convenient for computation.
  7631. */
  7632. Scalar.TwoPi = Math.PI * 2;
  7633. return Scalar;
  7634. }());
  7635. BABYLON.Scalar = Scalar;
  7636. })(BABYLON || (BABYLON = {}));
  7637. //# sourceMappingURL=babylon.math.scalar.js.map
  7638. //# sourceMappingURL=babylon.mixins.js.map
  7639. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7640. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7641. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7642. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7643. //# sourceMappingURL=babylon.webgl2.js.map
  7644. var BABYLON;
  7645. (function (BABYLON) {
  7646. var __decoratorInitialStore = {};
  7647. var __mergedStore = {};
  7648. var _copySource = function (creationFunction, source, instanciate) {
  7649. var destination = creationFunction();
  7650. // Tags
  7651. if (BABYLON.Tags) {
  7652. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7653. }
  7654. var classStore = getMergedStore(destination);
  7655. // Properties
  7656. for (var property in classStore) {
  7657. var propertyDescriptor = classStore[property];
  7658. var sourceProperty = source[property];
  7659. var propertyType = propertyDescriptor.type;
  7660. if (sourceProperty !== undefined && sourceProperty !== null) {
  7661. switch (propertyType) {
  7662. case 0: // Value
  7663. case 6: // Mesh reference
  7664. case 11: // Camera reference
  7665. destination[property] = sourceProperty;
  7666. break;
  7667. case 1: // Texture
  7668. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7669. break;
  7670. case 2: // Color3
  7671. case 3: // FresnelParameters
  7672. case 4: // Vector2
  7673. case 5: // Vector3
  7674. case 7: // Color Curves
  7675. case 10: // Quaternion
  7676. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7677. break;
  7678. }
  7679. }
  7680. }
  7681. return destination;
  7682. };
  7683. function getDirectStore(target) {
  7684. var classKey = target.getClassName();
  7685. if (!__decoratorInitialStore[classKey]) {
  7686. __decoratorInitialStore[classKey] = {};
  7687. }
  7688. return __decoratorInitialStore[classKey];
  7689. }
  7690. /**
  7691. * Return the list of properties flagged as serializable
  7692. * @param target: host object
  7693. */
  7694. function getMergedStore(target) {
  7695. var classKey = target.getClassName();
  7696. if (__mergedStore[classKey]) {
  7697. return __mergedStore[classKey];
  7698. }
  7699. __mergedStore[classKey] = {};
  7700. var store = __mergedStore[classKey];
  7701. var currentTarget = target;
  7702. var currentKey = classKey;
  7703. while (currentKey) {
  7704. var initialStore = __decoratorInitialStore[currentKey];
  7705. for (var property in initialStore) {
  7706. store[property] = initialStore[property];
  7707. }
  7708. var parent_1 = void 0;
  7709. var done = false;
  7710. do {
  7711. parent_1 = Object.getPrototypeOf(currentTarget);
  7712. if (!parent_1.getClassName) {
  7713. done = true;
  7714. break;
  7715. }
  7716. if (parent_1.getClassName() !== currentKey) {
  7717. break;
  7718. }
  7719. currentTarget = parent_1;
  7720. } while (parent_1);
  7721. if (done) {
  7722. break;
  7723. }
  7724. currentKey = parent_1.getClassName();
  7725. currentTarget = parent_1;
  7726. }
  7727. return store;
  7728. }
  7729. function generateSerializableMember(type, sourceName) {
  7730. return function (target, propertyKey) {
  7731. var classStore = getDirectStore(target);
  7732. if (!classStore[propertyKey]) {
  7733. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7734. }
  7735. };
  7736. }
  7737. function generateExpandMember(setCallback, targetKey) {
  7738. if (targetKey === void 0) { targetKey = null; }
  7739. return function (target, propertyKey) {
  7740. var key = targetKey || ("_" + propertyKey);
  7741. Object.defineProperty(target, propertyKey, {
  7742. get: function () {
  7743. return this[key];
  7744. },
  7745. set: function (value) {
  7746. if (this[key] === value) {
  7747. return;
  7748. }
  7749. this[key] = value;
  7750. target[setCallback].apply(this);
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. };
  7756. }
  7757. function expandToProperty(callback, targetKey) {
  7758. if (targetKey === void 0) { targetKey = null; }
  7759. return generateExpandMember(callback, targetKey);
  7760. }
  7761. BABYLON.expandToProperty = expandToProperty;
  7762. function serialize(sourceName) {
  7763. return generateSerializableMember(0, sourceName); // value member
  7764. }
  7765. BABYLON.serialize = serialize;
  7766. function serializeAsTexture(sourceName) {
  7767. return generateSerializableMember(1, sourceName); // texture member
  7768. }
  7769. BABYLON.serializeAsTexture = serializeAsTexture;
  7770. function serializeAsColor3(sourceName) {
  7771. return generateSerializableMember(2, sourceName); // color3 member
  7772. }
  7773. BABYLON.serializeAsColor3 = serializeAsColor3;
  7774. function serializeAsFresnelParameters(sourceName) {
  7775. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7776. }
  7777. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7778. function serializeAsVector2(sourceName) {
  7779. return generateSerializableMember(4, sourceName); // vector2 member
  7780. }
  7781. BABYLON.serializeAsVector2 = serializeAsVector2;
  7782. function serializeAsVector3(sourceName) {
  7783. return generateSerializableMember(5, sourceName); // vector3 member
  7784. }
  7785. BABYLON.serializeAsVector3 = serializeAsVector3;
  7786. function serializeAsMeshReference(sourceName) {
  7787. return generateSerializableMember(6, sourceName); // mesh reference member
  7788. }
  7789. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7790. function serializeAsColorCurves(sourceName) {
  7791. return generateSerializableMember(7, sourceName); // color curves
  7792. }
  7793. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7794. function serializeAsColor4(sourceName) {
  7795. return generateSerializableMember(8, sourceName); // color 4
  7796. }
  7797. BABYLON.serializeAsColor4 = serializeAsColor4;
  7798. function serializeAsImageProcessingConfiguration(sourceName) {
  7799. return generateSerializableMember(9, sourceName); // image processing
  7800. }
  7801. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7802. function serializeAsQuaternion(sourceName) {
  7803. return generateSerializableMember(10, sourceName); // quaternion member
  7804. }
  7805. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7806. /**
  7807. * Decorator used to define property that can be serialized as reference to a camera
  7808. * @param sourceName defines the name of the property to decorate
  7809. */
  7810. function serializeAsCameraReference(sourceName) {
  7811. return generateSerializableMember(11, sourceName); // camera reference member
  7812. }
  7813. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7814. var SerializationHelper = /** @class */ (function () {
  7815. function SerializationHelper() {
  7816. }
  7817. SerializationHelper.Serialize = function (entity, serializationObject) {
  7818. if (!serializationObject) {
  7819. serializationObject = {};
  7820. }
  7821. // Tags
  7822. if (BABYLON.Tags) {
  7823. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7824. }
  7825. var serializedProperties = getMergedStore(entity);
  7826. // Properties
  7827. for (var property in serializedProperties) {
  7828. var propertyDescriptor = serializedProperties[property];
  7829. var targetPropertyName = propertyDescriptor.sourceName || property;
  7830. var propertyType = propertyDescriptor.type;
  7831. var sourceProperty = entity[property];
  7832. if (sourceProperty !== undefined && sourceProperty !== null) {
  7833. switch (propertyType) {
  7834. case 0: // Value
  7835. serializationObject[targetPropertyName] = sourceProperty;
  7836. break;
  7837. case 1: // Texture
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 2: // Color3
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 3: // FresnelParameters
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 4: // Vector2
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 5: // Vector3
  7850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7851. break;
  7852. case 6: // Mesh reference
  7853. serializationObject[targetPropertyName] = sourceProperty.id;
  7854. break;
  7855. case 7: // Color Curves
  7856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7857. break;
  7858. case 8: // Color 4
  7859. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7860. break;
  7861. case 9: // Image Processing
  7862. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7863. break;
  7864. case 10: // Quaternion
  7865. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7866. break;
  7867. case 11: // Camera reference
  7868. serializationObject[targetPropertyName] = sourceProperty.id;
  7869. break;
  7870. }
  7871. }
  7872. }
  7873. return serializationObject;
  7874. };
  7875. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7876. if (rootUrl === void 0) { rootUrl = null; }
  7877. var destination = creationFunction();
  7878. if (!rootUrl) {
  7879. rootUrl = "";
  7880. }
  7881. // Tags
  7882. if (BABYLON.Tags) {
  7883. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7884. }
  7885. var classStore = getMergedStore(destination);
  7886. // Properties
  7887. for (var property in classStore) {
  7888. var propertyDescriptor = classStore[property];
  7889. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7890. var propertyType = propertyDescriptor.type;
  7891. if (sourceProperty !== undefined && sourceProperty !== null) {
  7892. var dest = destination;
  7893. switch (propertyType) {
  7894. case 0: // Value
  7895. dest[property] = sourceProperty;
  7896. break;
  7897. case 1: // Texture
  7898. if (scene) {
  7899. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7900. }
  7901. break;
  7902. case 2: // Color3
  7903. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7904. break;
  7905. case 3: // FresnelParameters
  7906. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7907. break;
  7908. case 4: // Vector2
  7909. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7910. break;
  7911. case 5: // Vector3
  7912. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7913. break;
  7914. case 6: // Mesh reference
  7915. if (scene) {
  7916. dest[property] = scene.getLastMeshByID(sourceProperty);
  7917. }
  7918. break;
  7919. case 7: // Color Curves
  7920. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7921. break;
  7922. case 8: // Color 4
  7923. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7924. break;
  7925. case 9: // Image Processing
  7926. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7927. break;
  7928. case 10: // Quaternion
  7929. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7930. break;
  7931. case 11: // Camera reference
  7932. if (scene) {
  7933. dest[property] = scene.getCameraByID(sourceProperty);
  7934. }
  7935. break;
  7936. }
  7937. }
  7938. }
  7939. return destination;
  7940. };
  7941. SerializationHelper.Clone = function (creationFunction, source) {
  7942. return _copySource(creationFunction, source, false);
  7943. };
  7944. SerializationHelper.Instanciate = function (creationFunction, source) {
  7945. return _copySource(creationFunction, source, true);
  7946. };
  7947. return SerializationHelper;
  7948. }());
  7949. BABYLON.SerializationHelper = SerializationHelper;
  7950. })(BABYLON || (BABYLON = {}));
  7951. //# sourceMappingURL=babylon.decorators.js.map
  7952. var BABYLON;
  7953. (function (BABYLON) {
  7954. /**
  7955. * Wrapper class for promise with external resolve and reject.
  7956. */
  7957. var Deferred = /** @class */ (function () {
  7958. /**
  7959. * Constructor for this deferred object.
  7960. */
  7961. function Deferred() {
  7962. var _this = this;
  7963. this.promise = new Promise(function (resolve, reject) {
  7964. _this._resolve = resolve;
  7965. _this._reject = reject;
  7966. });
  7967. }
  7968. Object.defineProperty(Deferred.prototype, "resolve", {
  7969. /**
  7970. * The resolve method of the promise associated with this deferred object.
  7971. */
  7972. get: function () {
  7973. return this._resolve;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Deferred.prototype, "reject", {
  7979. /**
  7980. * The reject method of the promise associated with this deferred object.
  7981. */
  7982. get: function () {
  7983. return this._reject;
  7984. },
  7985. enumerable: true,
  7986. configurable: true
  7987. });
  7988. return Deferred;
  7989. }());
  7990. BABYLON.Deferred = Deferred;
  7991. })(BABYLON || (BABYLON = {}));
  7992. //# sourceMappingURL=babylon.deferred.js.map
  7993. var BABYLON;
  7994. (function (BABYLON) {
  7995. /**
  7996. * A class serves as a medium between the observable and its observers
  7997. */
  7998. var EventState = /** @class */ (function () {
  7999. /**
  8000. * Create a new EventState
  8001. * @param mask defines the mask associated with this state
  8002. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8003. * @param target defines the original target of the state
  8004. * @param currentTarget defines the current target of the state
  8005. */
  8006. function EventState(mask, skipNextObservers, target, currentTarget) {
  8007. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8008. this.initalize(mask, skipNextObservers, target, currentTarget);
  8009. }
  8010. /**
  8011. * Initialize the current event state
  8012. * @param mask defines the mask associated with this state
  8013. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8014. * @param target defines the original target of the state
  8015. * @param currentTarget defines the current target of the state
  8016. * @returns the current event state
  8017. */
  8018. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8019. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8020. this.mask = mask;
  8021. this.skipNextObservers = skipNextObservers;
  8022. this.target = target;
  8023. this.currentTarget = currentTarget;
  8024. return this;
  8025. };
  8026. return EventState;
  8027. }());
  8028. BABYLON.EventState = EventState;
  8029. /**
  8030. * Represent an Observer registered to a given Observable object.
  8031. */
  8032. var Observer = /** @class */ (function () {
  8033. /**
  8034. * Creates a new observer
  8035. * @param callback defines the callback to call when the observer is notified
  8036. * @param mask defines the mask of the observer (used to filter notifications)
  8037. * @param scope defines the current scope used to restore the JS context
  8038. */
  8039. function Observer(
  8040. /**
  8041. * Defines the callback to call when the observer is notified
  8042. */
  8043. callback,
  8044. /**
  8045. * Defines the mask of the observer (used to filter notifications)
  8046. */
  8047. mask,
  8048. /**
  8049. * Defines the current scope used to restore the JS context
  8050. */
  8051. scope) {
  8052. if (scope === void 0) { scope = null; }
  8053. this.callback = callback;
  8054. this.mask = mask;
  8055. this.scope = scope;
  8056. /** @hidden */
  8057. this._willBeUnregistered = false;
  8058. /**
  8059. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8060. */
  8061. this.unregisterOnNextCall = false;
  8062. }
  8063. return Observer;
  8064. }());
  8065. BABYLON.Observer = Observer;
  8066. /**
  8067. * Represent a list of observers registered to multiple Observables object.
  8068. */
  8069. var MultiObserver = /** @class */ (function () {
  8070. function MultiObserver() {
  8071. }
  8072. /**
  8073. * Release associated resources
  8074. */
  8075. MultiObserver.prototype.dispose = function () {
  8076. if (this._observers && this._observables) {
  8077. for (var index = 0; index < this._observers.length; index++) {
  8078. this._observables[index].remove(this._observers[index]);
  8079. }
  8080. }
  8081. this._observers = null;
  8082. this._observables = null;
  8083. };
  8084. /**
  8085. * Raise a callback when one of the observable will notify
  8086. * @param observables defines a list of observables to watch
  8087. * @param callback defines the callback to call on notification
  8088. * @param mask defines the mask used to filter notifications
  8089. * @param scope defines the current scope used to restore the JS context
  8090. * @returns the new MultiObserver
  8091. */
  8092. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8093. if (mask === void 0) { mask = -1; }
  8094. if (scope === void 0) { scope = null; }
  8095. var result = new MultiObserver();
  8096. result._observers = new Array();
  8097. result._observables = observables;
  8098. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8099. var observable = observables_1[_i];
  8100. var observer = observable.add(callback, mask, false, scope);
  8101. if (observer) {
  8102. result._observers.push(observer);
  8103. }
  8104. }
  8105. return result;
  8106. };
  8107. return MultiObserver;
  8108. }());
  8109. BABYLON.MultiObserver = MultiObserver;
  8110. /**
  8111. * The Observable class is a simple implementation of the Observable pattern.
  8112. *
  8113. * 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.
  8114. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8115. * 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).
  8116. * 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.
  8117. */
  8118. var Observable = /** @class */ (function () {
  8119. /**
  8120. * Creates a new observable
  8121. * @param onObserverAdded defines a callback to call when a new observer is added
  8122. */
  8123. function Observable(onObserverAdded) {
  8124. this._observers = new Array();
  8125. this._eventState = new EventState(0);
  8126. if (onObserverAdded) {
  8127. this._onObserverAdded = onObserverAdded;
  8128. }
  8129. }
  8130. /**
  8131. * Create a new Observer with the specified callback
  8132. * @param callback the callback that will be executed for that Observer
  8133. * @param mask the mask used to filter observers
  8134. * @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.
  8135. * @param scope optional scope for the callback to be called from
  8136. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8137. * @returns the new observer created for the callback
  8138. */
  8139. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8140. if (mask === void 0) { mask = -1; }
  8141. if (insertFirst === void 0) { insertFirst = false; }
  8142. if (scope === void 0) { scope = null; }
  8143. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8144. if (!callback) {
  8145. return null;
  8146. }
  8147. var observer = new Observer(callback, mask, scope);
  8148. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8149. if (insertFirst) {
  8150. this._observers.unshift(observer);
  8151. }
  8152. else {
  8153. this._observers.push(observer);
  8154. }
  8155. if (this._onObserverAdded) {
  8156. this._onObserverAdded(observer);
  8157. }
  8158. return observer;
  8159. };
  8160. /**
  8161. * Create a new Observer with the specified callback and unregisters after the next notification
  8162. * @param callback the callback that will be executed for that Observer
  8163. * @returns the new observer created for the callback
  8164. */
  8165. Observable.prototype.addOnce = function (callback) {
  8166. return this.add(callback, undefined, undefined, undefined, true);
  8167. };
  8168. /**
  8169. * Remove an Observer from the Observable object
  8170. * @param observer the instance of the Observer to remove
  8171. * @returns false if it doesn't belong to this Observable
  8172. */
  8173. Observable.prototype.remove = function (observer) {
  8174. if (!observer) {
  8175. return false;
  8176. }
  8177. var index = this._observers.indexOf(observer);
  8178. if (index !== -1) {
  8179. this._observers.splice(index, 1);
  8180. return true;
  8181. }
  8182. return false;
  8183. };
  8184. /**
  8185. * Remove a callback from the Observable object
  8186. * @param callback the callback to remove
  8187. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8188. * @returns false if it doesn't belong to this Observable
  8189. */
  8190. Observable.prototype.removeCallback = function (callback, scope) {
  8191. for (var index = 0; index < this._observers.length; index++) {
  8192. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8193. this._observers.splice(index, 1);
  8194. return true;
  8195. }
  8196. }
  8197. return false;
  8198. };
  8199. Observable.prototype._deferUnregister = function (observer) {
  8200. var _this = this;
  8201. observer.unregisterOnNextCall = false;
  8202. observer._willBeUnregistered = true;
  8203. BABYLON.Tools.SetImmediate(function () {
  8204. _this.remove(observer);
  8205. });
  8206. };
  8207. /**
  8208. * Notify all Observers by calling their respective callback with the given data
  8209. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8210. * @param eventData defines the data to send to all observers
  8211. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8215. */
  8216. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8217. if (mask === void 0) { mask = -1; }
  8218. if (!this._observers.length) {
  8219. return true;
  8220. }
  8221. var state = this._eventState;
  8222. state.mask = mask;
  8223. state.target = target;
  8224. state.currentTarget = currentTarget;
  8225. state.skipNextObservers = false;
  8226. state.lastReturnValue = eventData;
  8227. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8228. var obs = _a[_i];
  8229. if (obs._willBeUnregistered) {
  8230. continue;
  8231. }
  8232. if (obs.mask & mask) {
  8233. if (obs.scope) {
  8234. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8235. }
  8236. else {
  8237. state.lastReturnValue = obs.callback(eventData, state);
  8238. }
  8239. if (obs.unregisterOnNextCall) {
  8240. this._deferUnregister(obs);
  8241. }
  8242. }
  8243. if (state.skipNextObservers) {
  8244. return false;
  8245. }
  8246. }
  8247. return true;
  8248. };
  8249. /**
  8250. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8251. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8252. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8253. * and it is crucial that all callbacks will be executed.
  8254. * The order of the callbacks is kept, callbacks are not executed parallel.
  8255. *
  8256. * @param eventData The data to be sent to each callback
  8257. * @param mask is used to filter observers defaults to -1
  8258. * @param target defines the callback target (see EventState)
  8259. * @param currentTarget defines he current object in the bubbling phase
  8260. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8261. */
  8262. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8263. var _this = this;
  8264. if (mask === void 0) { mask = -1; }
  8265. // create an empty promise
  8266. var p = Promise.resolve(eventData);
  8267. // no observers? return this promise.
  8268. if (!this._observers.length) {
  8269. return p;
  8270. }
  8271. var state = this._eventState;
  8272. state.mask = mask;
  8273. state.target = target;
  8274. state.currentTarget = currentTarget;
  8275. state.skipNextObservers = false;
  8276. // execute one callback after another (not using Promise.all, the order is important)
  8277. this._observers.forEach(function (obs) {
  8278. if (state.skipNextObservers) {
  8279. return;
  8280. }
  8281. if (obs._willBeUnregistered) {
  8282. return;
  8283. }
  8284. if (obs.mask & mask) {
  8285. if (obs.scope) {
  8286. p = p.then(function (lastReturnedValue) {
  8287. state.lastReturnValue = lastReturnedValue;
  8288. return obs.callback.apply(obs.scope, [eventData, state]);
  8289. });
  8290. }
  8291. else {
  8292. p = p.then(function (lastReturnedValue) {
  8293. state.lastReturnValue = lastReturnedValue;
  8294. return obs.callback(eventData, state);
  8295. });
  8296. }
  8297. if (obs.unregisterOnNextCall) {
  8298. _this._deferUnregister(obs);
  8299. }
  8300. }
  8301. });
  8302. // return the eventData
  8303. return p.then(function () { return eventData; });
  8304. };
  8305. /**
  8306. * Notify a specific observer
  8307. * @param observer defines the observer to notify
  8308. * @param eventData defines the data to be sent to each callback
  8309. * @param mask is used to filter observers defaults to -1
  8310. */
  8311. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8312. if (mask === void 0) { mask = -1; }
  8313. var state = this._eventState;
  8314. state.mask = mask;
  8315. state.skipNextObservers = false;
  8316. observer.callback(eventData, state);
  8317. };
  8318. /**
  8319. * Gets a boolean indicating if the observable has at least one observer
  8320. * @returns true is the Observable has at least one Observer registered
  8321. */
  8322. Observable.prototype.hasObservers = function () {
  8323. return this._observers.length > 0;
  8324. };
  8325. /**
  8326. * Clear the list of observers
  8327. */
  8328. Observable.prototype.clear = function () {
  8329. this._observers = new Array();
  8330. this._onObserverAdded = null;
  8331. };
  8332. /**
  8333. * Clone the current observable
  8334. * @returns a new observable
  8335. */
  8336. Observable.prototype.clone = function () {
  8337. var result = new Observable();
  8338. result._observers = this._observers.slice(0);
  8339. return result;
  8340. };
  8341. /**
  8342. * Does this observable handles observer registered with a given mask
  8343. * @param mask defines the mask to be tested
  8344. * @return whether or not one observer registered with the given mask is handeled
  8345. **/
  8346. Observable.prototype.hasSpecificMask = function (mask) {
  8347. if (mask === void 0) { mask = -1; }
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs.mask & mask || obs.mask === mask) {
  8351. return true;
  8352. }
  8353. }
  8354. return false;
  8355. };
  8356. return Observable;
  8357. }());
  8358. BABYLON.Observable = Observable;
  8359. })(BABYLON || (BABYLON = {}));
  8360. //# sourceMappingURL=babylon.observable.js.map
  8361. var BABYLON;
  8362. (function (BABYLON) {
  8363. var SmartArray = /** @class */ (function () {
  8364. function SmartArray(capacity) {
  8365. this.length = 0;
  8366. this.data = new Array(capacity);
  8367. this._id = SmartArray._GlobalId++;
  8368. }
  8369. SmartArray.prototype.push = function (value) {
  8370. this.data[this.length++] = value;
  8371. if (this.length > this.data.length) {
  8372. this.data.length *= 2;
  8373. }
  8374. };
  8375. SmartArray.prototype.forEach = function (func) {
  8376. for (var index = 0; index < this.length; index++) {
  8377. func(this.data[index]);
  8378. }
  8379. };
  8380. SmartArray.prototype.sort = function (compareFn) {
  8381. this.data.sort(compareFn);
  8382. };
  8383. SmartArray.prototype.reset = function () {
  8384. this.length = 0;
  8385. };
  8386. SmartArray.prototype.dispose = function () {
  8387. this.reset();
  8388. if (this.data) {
  8389. this.data.length = 0;
  8390. this.data = [];
  8391. }
  8392. };
  8393. SmartArray.prototype.concat = function (array) {
  8394. if (array.length === 0) {
  8395. return;
  8396. }
  8397. if (this.length + array.length > this.data.length) {
  8398. this.data.length = (this.length + array.length) * 2;
  8399. }
  8400. for (var index = 0; index < array.length; index++) {
  8401. this.data[this.length++] = (array.data || array)[index];
  8402. }
  8403. };
  8404. SmartArray.prototype.indexOf = function (value) {
  8405. var position = this.data.indexOf(value);
  8406. if (position >= this.length) {
  8407. return -1;
  8408. }
  8409. return position;
  8410. };
  8411. SmartArray.prototype.contains = function (value) {
  8412. return this.data.indexOf(value) !== -1;
  8413. };
  8414. // Statics
  8415. SmartArray._GlobalId = 0;
  8416. return SmartArray;
  8417. }());
  8418. BABYLON.SmartArray = SmartArray;
  8419. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8420. __extends(SmartArrayNoDuplicate, _super);
  8421. function SmartArrayNoDuplicate() {
  8422. var _this = _super !== null && _super.apply(this, arguments) || this;
  8423. _this._duplicateId = 0;
  8424. return _this;
  8425. }
  8426. SmartArrayNoDuplicate.prototype.push = function (value) {
  8427. _super.prototype.push.call(this, value);
  8428. if (!value.__smartArrayFlags) {
  8429. value.__smartArrayFlags = {};
  8430. }
  8431. value.__smartArrayFlags[this._id] = this._duplicateId;
  8432. };
  8433. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8434. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8435. return false;
  8436. }
  8437. this.push(value);
  8438. return true;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.reset = function () {
  8441. _super.prototype.reset.call(this);
  8442. this._duplicateId++;
  8443. };
  8444. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8445. if (array.length === 0) {
  8446. return;
  8447. }
  8448. if (this.length + array.length > this.data.length) {
  8449. this.data.length = (this.length + array.length) * 2;
  8450. }
  8451. for (var index = 0; index < array.length; index++) {
  8452. var item = (array.data || array)[index];
  8453. this.pushNoDuplicate(item);
  8454. }
  8455. };
  8456. return SmartArrayNoDuplicate;
  8457. }(SmartArray));
  8458. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8459. })(BABYLON || (BABYLON = {}));
  8460. //# sourceMappingURL=babylon.smartArray.js.map
  8461. var BABYLON;
  8462. (function (BABYLON) {
  8463. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8464. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8465. var LoadFileError = /** @class */ (function (_super) {
  8466. __extends(LoadFileError, _super);
  8467. function LoadFileError(message, request) {
  8468. var _this = _super.call(this, message) || this;
  8469. _this.request = request;
  8470. _this.name = "LoadFileError";
  8471. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8472. return _this;
  8473. }
  8474. // Polyfill for Object.setPrototypeOf if necessary.
  8475. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8476. return LoadFileError;
  8477. }(Error));
  8478. BABYLON.LoadFileError = LoadFileError;
  8479. var RetryStrategy = /** @class */ (function () {
  8480. function RetryStrategy() {
  8481. }
  8482. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8483. if (maxRetries === void 0) { maxRetries = 3; }
  8484. if (baseInterval === void 0) { baseInterval = 500; }
  8485. return function (url, request, retryIndex) {
  8486. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8487. return -1;
  8488. }
  8489. return Math.pow(2, retryIndex) * baseInterval;
  8490. };
  8491. };
  8492. return RetryStrategy;
  8493. }());
  8494. BABYLON.RetryStrategy = RetryStrategy;
  8495. // Screenshots
  8496. var screenshotCanvas;
  8497. var cloneValue = function (source, destinationObject) {
  8498. if (!source)
  8499. return null;
  8500. if (source instanceof BABYLON.Mesh) {
  8501. return null;
  8502. }
  8503. if (source instanceof BABYLON.SubMesh) {
  8504. return source.clone(destinationObject);
  8505. }
  8506. else if (source.clone) {
  8507. return source.clone();
  8508. }
  8509. return null;
  8510. };
  8511. var Tools = /** @class */ (function () {
  8512. function Tools() {
  8513. }
  8514. /**
  8515. * Interpolates between a and b via alpha
  8516. * @param a The lower value (returned when alpha = 0)
  8517. * @param b The upper value (returned when alpha = 1)
  8518. * @param alpha The interpolation-factor
  8519. * @return The mixed value
  8520. */
  8521. Tools.Mix = function (a, b, alpha) {
  8522. return a * (1 - alpha) + b * alpha;
  8523. };
  8524. Tools.Instantiate = function (className) {
  8525. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8526. return Tools.RegisteredExternalClasses[className];
  8527. }
  8528. var arr = className.split(".");
  8529. var fn = (window || this);
  8530. for (var i = 0, len = arr.length; i < len; i++) {
  8531. fn = fn[arr[i]];
  8532. }
  8533. if (typeof fn !== "function") {
  8534. return null;
  8535. }
  8536. return fn;
  8537. };
  8538. /**
  8539. * Provides a slice function that will work even on IE
  8540. * @param data defines the array to slice
  8541. * @param start defines the start of the data (optional)
  8542. * @param end defines the end of the data (optional)
  8543. * @returns the new sliced array
  8544. */
  8545. Tools.Slice = function (data, start, end) {
  8546. if (data.slice) {
  8547. return data.slice(start, end);
  8548. }
  8549. return Array.prototype.slice.call(data, start, end);
  8550. };
  8551. Tools.SetImmediate = function (action) {
  8552. if (window.setImmediate) {
  8553. window.setImmediate(action);
  8554. }
  8555. else {
  8556. setTimeout(action, 1);
  8557. }
  8558. };
  8559. Tools.IsExponentOfTwo = function (value) {
  8560. var count = 1;
  8561. do {
  8562. count *= 2;
  8563. } while (count < value);
  8564. return count === value;
  8565. };
  8566. /**
  8567. * Returns the nearest 32-bit single precision float representation of a Number
  8568. * @param value A Number. If the parameter is of a different type, it will get converted
  8569. * to a number or to NaN if it cannot be converted
  8570. * @returns number
  8571. */
  8572. Tools.FloatRound = function (value) {
  8573. if (Math.fround) {
  8574. return Math.fround(value);
  8575. }
  8576. return (Tools._tmpFloatArray[0] = value);
  8577. };
  8578. /**
  8579. * Find the next highest power of two.
  8580. * @param x Number to start search from.
  8581. * @return Next highest power of two.
  8582. */
  8583. Tools.CeilingPOT = function (x) {
  8584. x--;
  8585. x |= x >> 1;
  8586. x |= x >> 2;
  8587. x |= x >> 4;
  8588. x |= x >> 8;
  8589. x |= x >> 16;
  8590. x++;
  8591. return x;
  8592. };
  8593. /**
  8594. * Find the next lowest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next lowest power of two.
  8597. */
  8598. Tools.FloorPOT = function (x) {
  8599. x = x | (x >> 1);
  8600. x = x | (x >> 2);
  8601. x = x | (x >> 4);
  8602. x = x | (x >> 8);
  8603. x = x | (x >> 16);
  8604. return x - (x >> 1);
  8605. };
  8606. /**
  8607. * Find the nearest power of two.
  8608. * @param x Number to start search from.
  8609. * @return Next nearest power of two.
  8610. */
  8611. Tools.NearestPOT = function (x) {
  8612. var c = Tools.CeilingPOT(x);
  8613. var f = Tools.FloorPOT(x);
  8614. return (c - x) > (x - f) ? f : c;
  8615. };
  8616. Tools.GetExponentOfTwo = function (value, max, mode) {
  8617. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8618. var pot;
  8619. switch (mode) {
  8620. case BABYLON.Engine.SCALEMODE_FLOOR:
  8621. pot = Tools.FloorPOT(value);
  8622. break;
  8623. case BABYLON.Engine.SCALEMODE_NEAREST:
  8624. pot = Tools.NearestPOT(value);
  8625. break;
  8626. case BABYLON.Engine.SCALEMODE_CEILING:
  8627. default:
  8628. pot = Tools.CeilingPOT(value);
  8629. break;
  8630. }
  8631. return Math.min(pot, max);
  8632. };
  8633. Tools.GetFilename = function (path) {
  8634. var index = path.lastIndexOf("/");
  8635. if (index < 0)
  8636. return path;
  8637. return path.substring(index + 1);
  8638. };
  8639. /**
  8640. * Extracts the "folder" part of a path (everything before the filename).
  8641. * @param uri The URI to extract the info from
  8642. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8643. * @returns The "folder" part of the path
  8644. */
  8645. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8646. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8647. var index = uri.lastIndexOf("/");
  8648. if (index < 0) {
  8649. if (returnUnchangedIfNoSlash) {
  8650. return uri;
  8651. }
  8652. return "";
  8653. }
  8654. return uri.substring(0, index + 1);
  8655. };
  8656. Tools.GetDOMTextContent = function (element) {
  8657. var result = "";
  8658. var child = element.firstChild;
  8659. while (child) {
  8660. if (child.nodeType === 3) {
  8661. result += child.textContent;
  8662. }
  8663. child = child.nextSibling;
  8664. }
  8665. return result;
  8666. };
  8667. Tools.ToDegrees = function (angle) {
  8668. return angle * 180 / Math.PI;
  8669. };
  8670. Tools.ToRadians = function (angle) {
  8671. return angle * Math.PI / 180;
  8672. };
  8673. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8674. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8675. var output = "";
  8676. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8677. var i = 0;
  8678. var bytes = new Uint8Array(buffer);
  8679. while (i < bytes.length) {
  8680. chr1 = bytes[i++];
  8681. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8682. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8683. enc1 = chr1 >> 2;
  8684. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8685. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8686. enc4 = chr3 & 63;
  8687. if (isNaN(chr2)) {
  8688. enc3 = enc4 = 64;
  8689. }
  8690. else if (isNaN(chr3)) {
  8691. enc4 = 64;
  8692. }
  8693. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8694. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8695. }
  8696. return "data:image/png;base64," + output;
  8697. };
  8698. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8699. if (bias === void 0) { bias = null; }
  8700. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8701. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8702. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8703. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8704. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8705. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8706. }
  8707. if (bias) {
  8708. minimum.x -= minimum.x * bias.x + bias.y;
  8709. minimum.y -= minimum.y * bias.x + bias.y;
  8710. minimum.z -= minimum.z * bias.x + bias.y;
  8711. maximum.x += maximum.x * bias.x + bias.y;
  8712. maximum.y += maximum.y * bias.x + bias.y;
  8713. maximum.z += maximum.z * bias.x + bias.y;
  8714. }
  8715. return {
  8716. minimum: minimum,
  8717. maximum: maximum
  8718. };
  8719. };
  8720. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8721. if (bias === void 0) { bias = null; }
  8722. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8723. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8724. if (!stride) {
  8725. stride = 3;
  8726. }
  8727. for (var index = start; index < start + count; index++) {
  8728. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8729. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8730. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8731. }
  8732. if (bias) {
  8733. minimum.x -= minimum.x * bias.x + bias.y;
  8734. minimum.y -= minimum.y * bias.x + bias.y;
  8735. minimum.z -= minimum.z * bias.x + bias.y;
  8736. maximum.x += maximum.x * bias.x + bias.y;
  8737. maximum.y += maximum.y * bias.x + bias.y;
  8738. maximum.z += maximum.z * bias.x + bias.y;
  8739. }
  8740. return {
  8741. minimum: minimum,
  8742. maximum: maximum
  8743. };
  8744. };
  8745. Tools.Vector2ArrayFeeder = function (array) {
  8746. return function (index) {
  8747. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8748. var length = isFloatArray ? array.length / 2 : array.length;
  8749. if (index >= length) {
  8750. return null;
  8751. }
  8752. if (isFloatArray) {
  8753. var fa = array;
  8754. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8755. }
  8756. var a = array;
  8757. return a[index];
  8758. };
  8759. };
  8760. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8761. if (bias === void 0) { bias = null; }
  8762. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8763. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8764. var i = 0;
  8765. var cur = feeder(i++);
  8766. while (cur) {
  8767. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8768. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8769. cur = feeder(i++);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. }
  8777. return {
  8778. minimum: minimum,
  8779. maximum: maximum
  8780. };
  8781. };
  8782. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8783. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8784. return null;
  8785. return Array.isArray(obj) ? obj : [obj];
  8786. };
  8787. // Misc.
  8788. Tools.GetPointerPrefix = function () {
  8789. var eventPrefix = "pointer";
  8790. // Check if pointer events are supported
  8791. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8792. eventPrefix = "mouse";
  8793. }
  8794. return eventPrefix;
  8795. };
  8796. /**
  8797. * @param func - the function to be called
  8798. * @param requester - the object that will request the next frame. Falls back to window.
  8799. */
  8800. Tools.QueueNewFrame = function (func, requester) {
  8801. if (!Tools.IsWindowObjectExist()) {
  8802. return setTimeout(func, 16);
  8803. }
  8804. if (!requester) {
  8805. requester = window;
  8806. }
  8807. if (requester.requestAnimationFrame) {
  8808. return requester.requestAnimationFrame(func);
  8809. }
  8810. else if (requester.msRequestAnimationFrame) {
  8811. return requester.msRequestAnimationFrame(func);
  8812. }
  8813. else if (requester.webkitRequestAnimationFrame) {
  8814. return requester.webkitRequestAnimationFrame(func);
  8815. }
  8816. else if (requester.mozRequestAnimationFrame) {
  8817. return requester.mozRequestAnimationFrame(func);
  8818. }
  8819. else if (requester.oRequestAnimationFrame) {
  8820. return requester.oRequestAnimationFrame(func);
  8821. }
  8822. else {
  8823. return window.setTimeout(func, 16);
  8824. }
  8825. };
  8826. Tools.RequestFullscreen = function (element) {
  8827. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8828. if (!requestFunction)
  8829. return;
  8830. requestFunction.call(element);
  8831. };
  8832. Tools.ExitFullscreen = function () {
  8833. if (document.exitFullscreen) {
  8834. document.exitFullscreen();
  8835. }
  8836. else if (document.mozCancelFullScreen) {
  8837. document.mozCancelFullScreen();
  8838. }
  8839. else if (document.webkitCancelFullScreen) {
  8840. document.webkitCancelFullScreen();
  8841. }
  8842. else if (document.msCancelFullScreen) {
  8843. document.msCancelFullScreen();
  8844. }
  8845. };
  8846. Tools.SetCorsBehavior = function (url, element) {
  8847. if (url && url.indexOf("data:") === 0) {
  8848. return;
  8849. }
  8850. if (Tools.CorsBehavior) {
  8851. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8852. element.crossOrigin = Tools.CorsBehavior;
  8853. }
  8854. else {
  8855. var result = Tools.CorsBehavior(url);
  8856. if (result) {
  8857. element.crossOrigin = result;
  8858. }
  8859. }
  8860. }
  8861. };
  8862. // External files
  8863. Tools.CleanUrl = function (url) {
  8864. url = url.replace(/#/mg, "%23");
  8865. return url;
  8866. };
  8867. /**
  8868. * Loads an image as an HTMLImageElement.
  8869. * @param input url string, ArrayBuffer, or Blob to load
  8870. * @param onLoad callback called when the image successfully loads
  8871. * @param onError callback called when the image fails to load
  8872. * @param database database for caching
  8873. * @returns the HTMLImageElement of the loaded image
  8874. */
  8875. Tools.LoadImage = function (input, onLoad, onError, database) {
  8876. var url;
  8877. var usingObjectURL = false;
  8878. if (input instanceof ArrayBuffer) {
  8879. url = URL.createObjectURL(new Blob([input]));
  8880. usingObjectURL = true;
  8881. }
  8882. else if (input instanceof Blob) {
  8883. url = URL.createObjectURL(input);
  8884. usingObjectURL = true;
  8885. }
  8886. else {
  8887. url = Tools.CleanUrl(input);
  8888. url = Tools.PreprocessUrl(input);
  8889. }
  8890. var img = new Image();
  8891. Tools.SetCorsBehavior(url, img);
  8892. var loadHandler = function () {
  8893. if (usingObjectURL && img.src) {
  8894. URL.revokeObjectURL(img.src);
  8895. }
  8896. img.removeEventListener("load", loadHandler);
  8897. img.removeEventListener("error", errorHandler);
  8898. onLoad(img);
  8899. };
  8900. var errorHandler = function (err) {
  8901. if (usingObjectURL && img.src) {
  8902. URL.revokeObjectURL(img.src);
  8903. }
  8904. img.removeEventListener("load", loadHandler);
  8905. img.removeEventListener("error", errorHandler);
  8906. Tools.Error("Error while trying to load image: " + input);
  8907. if (onError) {
  8908. onError("Error while trying to load image: " + input, err);
  8909. }
  8910. };
  8911. img.addEventListener("load", loadHandler);
  8912. img.addEventListener("error", errorHandler);
  8913. var noIndexedDB = function () {
  8914. img.src = url;
  8915. };
  8916. var loadFromIndexedDB = function () {
  8917. if (database) {
  8918. database.loadImageFromDB(url, img);
  8919. }
  8920. };
  8921. //ANY database to do!
  8922. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8923. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8924. }
  8925. else {
  8926. if (url.indexOf("file:") !== -1) {
  8927. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8928. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8929. try {
  8930. var blobURL;
  8931. try {
  8932. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8933. }
  8934. catch (ex) {
  8935. // Chrome doesn't support oneTimeOnly parameter
  8936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8937. }
  8938. img.src = blobURL;
  8939. usingObjectURL = true;
  8940. }
  8941. catch (e) {
  8942. img.src = "";
  8943. }
  8944. return img;
  8945. }
  8946. }
  8947. noIndexedDB();
  8948. }
  8949. return img;
  8950. };
  8951. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8952. url = Tools.CleanUrl(url);
  8953. url = Tools.PreprocessUrl(url);
  8954. // If file and file input are set
  8955. if (url.indexOf("file:") !== -1) {
  8956. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8957. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8958. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8959. }
  8960. }
  8961. var loadUrl = Tools.BaseUrl + url;
  8962. var aborted = false;
  8963. var fileRequest = {
  8964. onCompleteObservable: new BABYLON.Observable(),
  8965. abort: function () { return aborted = true; },
  8966. };
  8967. var requestFile = function () {
  8968. var request = new XMLHttpRequest();
  8969. var retryHandle = null;
  8970. fileRequest.abort = function () {
  8971. aborted = true;
  8972. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8973. request.abort();
  8974. }
  8975. if (retryHandle !== null) {
  8976. clearTimeout(retryHandle);
  8977. retryHandle = null;
  8978. }
  8979. };
  8980. var retryLoop = function (retryIndex) {
  8981. request.open('GET', loadUrl, true);
  8982. if (useArrayBuffer) {
  8983. request.responseType = "arraybuffer";
  8984. }
  8985. if (onProgress) {
  8986. request.addEventListener("progress", onProgress);
  8987. }
  8988. var onLoadEnd = function () {
  8989. request.removeEventListener("loadend", onLoadEnd);
  8990. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8991. fileRequest.onCompleteObservable.clear();
  8992. };
  8993. request.addEventListener("loadend", onLoadEnd);
  8994. var onReadyStateChange = function () {
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. // In case of undefined state in some browsers.
  8999. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9000. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9001. request.removeEventListener("readystatechange", onReadyStateChange);
  9002. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9003. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9004. return;
  9005. }
  9006. var retryStrategy = Tools.DefaultRetryStrategy;
  9007. if (retryStrategy) {
  9008. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9009. if (waitTime !== -1) {
  9010. // Prevent the request from completing for retry.
  9011. request.removeEventListener("loadend", onLoadEnd);
  9012. request = new XMLHttpRequest();
  9013. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9014. return;
  9015. }
  9016. }
  9017. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9018. if (onError) {
  9019. onError(request, e);
  9020. }
  9021. else {
  9022. throw e;
  9023. }
  9024. }
  9025. };
  9026. request.addEventListener("readystatechange", onReadyStateChange);
  9027. request.send();
  9028. };
  9029. retryLoop(0);
  9030. };
  9031. // Caching all files
  9032. if (database && database.enableSceneOffline) {
  9033. var noIndexedDB_1 = function () {
  9034. if (!aborted) {
  9035. requestFile();
  9036. }
  9037. };
  9038. var loadFromIndexedDB = function () {
  9039. // TODO: database needs to support aborting and should return a IFileRequest
  9040. if (aborted) {
  9041. return;
  9042. }
  9043. if (database) {
  9044. database.loadFileFromDB(url, function (data) {
  9045. if (!aborted) {
  9046. onSuccess(data);
  9047. }
  9048. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9049. }, onProgress ? function (event) {
  9050. if (!aborted) {
  9051. onProgress(event);
  9052. }
  9053. } : undefined, noIndexedDB_1, useArrayBuffer);
  9054. }
  9055. };
  9056. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9057. }
  9058. else {
  9059. requestFile();
  9060. }
  9061. return fileRequest;
  9062. };
  9063. /**
  9064. * Load a script (identified by an url). When the url returns, the
  9065. * content of this file is added into a new script element, attached to the DOM (body element)
  9066. */
  9067. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9068. var head = document.getElementsByTagName('head')[0];
  9069. var script = document.createElement('script');
  9070. script.type = 'text/javascript';
  9071. script.src = scriptUrl;
  9072. script.onload = function () {
  9073. if (onSuccess) {
  9074. onSuccess();
  9075. }
  9076. };
  9077. script.onerror = function (e) {
  9078. if (onError) {
  9079. onError("Unable to load script '" + scriptUrl + "'", e);
  9080. }
  9081. };
  9082. head.appendChild(script);
  9083. };
  9084. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9085. var reader = new FileReader();
  9086. var request = {
  9087. onCompleteObservable: new BABYLON.Observable(),
  9088. abort: function () { return reader.abort(); },
  9089. };
  9090. reader.onloadend = function (e) {
  9091. request.onCompleteObservable.notifyObservers(request);
  9092. };
  9093. reader.onload = function (e) {
  9094. //target doesn't have result from ts 1.3
  9095. callback(e.target['result']);
  9096. };
  9097. reader.onprogress = progressCallback;
  9098. reader.readAsDataURL(fileToLoad);
  9099. return request;
  9100. };
  9101. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9102. var reader = new FileReader();
  9103. var request = {
  9104. onCompleteObservable: new BABYLON.Observable(),
  9105. abort: function () { return reader.abort(); },
  9106. };
  9107. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9108. reader.onerror = function (e) {
  9109. Tools.Log("Error while reading file: " + fileToLoad.name);
  9110. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9111. };
  9112. reader.onload = function (e) {
  9113. //target doesn't have result from ts 1.3
  9114. callback(e.target['result']);
  9115. };
  9116. if (progressCallBack) {
  9117. reader.onprogress = progressCallBack;
  9118. }
  9119. if (!useArrayBuffer) {
  9120. // Asynchronous read
  9121. reader.readAsText(fileToLoad);
  9122. }
  9123. else {
  9124. reader.readAsArrayBuffer(fileToLoad);
  9125. }
  9126. return request;
  9127. };
  9128. //returns a downloadable url to a file content.
  9129. Tools.FileAsURL = function (content) {
  9130. var fileBlob = new Blob([content]);
  9131. var url = window.URL || window.webkitURL;
  9132. var link = url.createObjectURL(fileBlob);
  9133. return link;
  9134. };
  9135. // Misc.
  9136. Tools.Format = function (value, decimals) {
  9137. if (decimals === void 0) { decimals = 2; }
  9138. return value.toFixed(decimals);
  9139. };
  9140. Tools.CheckExtends = function (v, min, max) {
  9141. if (v.x < min.x)
  9142. min.x = v.x;
  9143. if (v.y < min.y)
  9144. min.y = v.y;
  9145. if (v.z < min.z)
  9146. min.z = v.z;
  9147. if (v.x > max.x)
  9148. max.x = v.x;
  9149. if (v.y > max.y)
  9150. max.y = v.y;
  9151. if (v.z > max.z)
  9152. max.z = v.z;
  9153. };
  9154. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9155. for (var prop in source) {
  9156. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9157. continue;
  9158. }
  9159. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9160. continue;
  9161. }
  9162. var sourceValue = source[prop];
  9163. var typeOfSourceValue = typeof sourceValue;
  9164. if (typeOfSourceValue === "function") {
  9165. continue;
  9166. }
  9167. try {
  9168. if (typeOfSourceValue === "object") {
  9169. if (sourceValue instanceof Array) {
  9170. destination[prop] = [];
  9171. if (sourceValue.length > 0) {
  9172. if (typeof sourceValue[0] == "object") {
  9173. for (var index = 0; index < sourceValue.length; index++) {
  9174. var clonedValue = cloneValue(sourceValue[index], destination);
  9175. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9176. destination[prop].push(clonedValue);
  9177. }
  9178. }
  9179. }
  9180. else {
  9181. destination[prop] = sourceValue.slice(0);
  9182. }
  9183. }
  9184. }
  9185. else {
  9186. destination[prop] = cloneValue(sourceValue, destination);
  9187. }
  9188. }
  9189. else {
  9190. destination[prop] = sourceValue;
  9191. }
  9192. }
  9193. catch (e) {
  9194. // Just ignore error (it could be because of a read-only property)
  9195. }
  9196. }
  9197. };
  9198. Tools.IsEmpty = function (obj) {
  9199. for (var i in obj) {
  9200. if (obj.hasOwnProperty(i)) {
  9201. return false;
  9202. }
  9203. }
  9204. return true;
  9205. };
  9206. Tools.RegisterTopRootEvents = function (events) {
  9207. for (var index = 0; index < events.length; index++) {
  9208. var event = events[index];
  9209. window.addEventListener(event.name, event.handler, false);
  9210. try {
  9211. if (window.parent) {
  9212. window.parent.addEventListener(event.name, event.handler, false);
  9213. }
  9214. }
  9215. catch (e) {
  9216. // Silently fails...
  9217. }
  9218. }
  9219. };
  9220. Tools.UnregisterTopRootEvents = function (events) {
  9221. for (var index = 0; index < events.length; index++) {
  9222. var event = events[index];
  9223. window.removeEventListener(event.name, event.handler);
  9224. try {
  9225. if (window.parent) {
  9226. window.parent.removeEventListener(event.name, event.handler);
  9227. }
  9228. }
  9229. catch (e) {
  9230. // Silently fails...
  9231. }
  9232. }
  9233. };
  9234. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9235. if (mimeType === void 0) { mimeType = "image/png"; }
  9236. // Read the contents of the framebuffer
  9237. var numberOfChannelsByLine = width * 4;
  9238. var halfHeight = height / 2;
  9239. //Reading datas from WebGL
  9240. var data = engine.readPixels(0, 0, width, height);
  9241. //To flip image on Y axis.
  9242. for (var i = 0; i < halfHeight; i++) {
  9243. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9244. var currentCell = j + i * numberOfChannelsByLine;
  9245. var targetLine = height - i - 1;
  9246. var targetCell = j + targetLine * numberOfChannelsByLine;
  9247. var temp = data[currentCell];
  9248. data[currentCell] = data[targetCell];
  9249. data[targetCell] = temp;
  9250. }
  9251. }
  9252. // Create a 2D canvas to store the result
  9253. if (!screenshotCanvas) {
  9254. screenshotCanvas = document.createElement('canvas');
  9255. }
  9256. screenshotCanvas.width = width;
  9257. screenshotCanvas.height = height;
  9258. var context = screenshotCanvas.getContext('2d');
  9259. if (context) {
  9260. // Copy the pixels to a 2D canvas
  9261. var imageData = context.createImageData(width, height);
  9262. var castData = (imageData.data);
  9263. castData.set(data);
  9264. context.putImageData(imageData, 0, 0);
  9265. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9266. }
  9267. };
  9268. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9269. if (mimeType === void 0) { mimeType = "image/png"; }
  9270. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9271. if (successCallback) {
  9272. successCallback(base64Image);
  9273. }
  9274. else {
  9275. // We need HTMLCanvasElement.toBlob for HD screenshots
  9276. if (!screenshotCanvas.toBlob) {
  9277. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9278. screenshotCanvas.toBlob = function (callback, type, quality) {
  9279. var _this = this;
  9280. setTimeout(function () {
  9281. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9282. for (var i = 0; i < len; i++) {
  9283. arr[i] = binStr.charCodeAt(i);
  9284. }
  9285. callback(new Blob([arr], { type: type || 'image/png' }));
  9286. });
  9287. };
  9288. }
  9289. screenshotCanvas.toBlob(function (blob) {
  9290. var url = URL.createObjectURL(blob);
  9291. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9292. if (("download" in document.createElement("a"))) {
  9293. var a = window.document.createElement("a");
  9294. a.href = url;
  9295. if (fileName) {
  9296. a.setAttribute("download", fileName);
  9297. }
  9298. else {
  9299. var date = new Date();
  9300. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9301. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9302. }
  9303. window.document.body.appendChild(a);
  9304. a.addEventListener("click", function () {
  9305. if (a.parentElement) {
  9306. a.parentElement.removeChild(a);
  9307. }
  9308. });
  9309. a.click();
  9310. }
  9311. else {
  9312. var newWindow = window.open("");
  9313. if (!newWindow)
  9314. return;
  9315. var img = newWindow.document.createElement("img");
  9316. img.onload = function () {
  9317. // no longer need to read the blob so it's revoked
  9318. URL.revokeObjectURL(url);
  9319. };
  9320. img.src = url;
  9321. newWindow.document.body.appendChild(img);
  9322. }
  9323. });
  9324. }
  9325. };
  9326. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9327. if (mimeType === void 0) { mimeType = "image/png"; }
  9328. var width;
  9329. var height;
  9330. // If a precision value is specified
  9331. if (size.precision) {
  9332. width = Math.round(engine.getRenderWidth() * size.precision);
  9333. height = Math.round(width / engine.getAspectRatio(camera));
  9334. }
  9335. else if (size.width && size.height) {
  9336. width = size.width;
  9337. height = size.height;
  9338. }
  9339. //If passing only width, computing height to keep display canvas ratio.
  9340. else if (size.width && !size.height) {
  9341. width = size.width;
  9342. height = Math.round(width / engine.getAspectRatio(camera));
  9343. }
  9344. //If passing only height, computing width to keep display canvas ratio.
  9345. else if (size.height && !size.width) {
  9346. height = size.height;
  9347. width = Math.round(height * engine.getAspectRatio(camera));
  9348. }
  9349. //Assuming here that "size" parameter is a number
  9350. else if (!isNaN(size)) {
  9351. height = size;
  9352. width = size;
  9353. }
  9354. else {
  9355. Tools.Error("Invalid 'size' parameter !");
  9356. return;
  9357. }
  9358. if (!screenshotCanvas) {
  9359. screenshotCanvas = document.createElement('canvas');
  9360. }
  9361. screenshotCanvas.width = width;
  9362. screenshotCanvas.height = height;
  9363. var renderContext = screenshotCanvas.getContext("2d");
  9364. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9365. var newWidth = width;
  9366. var newHeight = newWidth / ratio;
  9367. if (newHeight > height) {
  9368. newHeight = height;
  9369. newWidth = newHeight * ratio;
  9370. }
  9371. var offsetX = Math.max(0, width - newWidth) / 2;
  9372. var offsetY = Math.max(0, height - newHeight) / 2;
  9373. var renderingCanvas = engine.getRenderingCanvas();
  9374. if (renderContext && renderingCanvas) {
  9375. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9376. }
  9377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9378. };
  9379. /**
  9380. * Generates an image screenshot from the specified camera.
  9381. *
  9382. * @param engine The engine to use for rendering
  9383. * @param camera The camera to use for rendering
  9384. * @param size This parameter can be set to a single number or to an object with the
  9385. * following (optional) properties: precision, width, height. If a single number is passed,
  9386. * it will be used for both width and height. If an object is passed, the screenshot size
  9387. * will be derived from the parameters. The precision property is a multiplier allowing
  9388. * rendering at a higher or lower resolution.
  9389. * @param successCallback The callback receives a single parameter which contains the
  9390. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9391. * src parameter of an <img> to display it.
  9392. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9393. * Check your browser for supported MIME types.
  9394. * @param samples Texture samples (default: 1)
  9395. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9396. * @param fileName A name for for the downloaded file.
  9397. * @constructor
  9398. */
  9399. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9400. if (mimeType === void 0) { mimeType = "image/png"; }
  9401. if (samples === void 0) { samples = 1; }
  9402. if (antialiasing === void 0) { antialiasing = false; }
  9403. var width;
  9404. var height;
  9405. //If a precision value is specified
  9406. if (size.precision) {
  9407. width = Math.round(engine.getRenderWidth() * size.precision);
  9408. height = Math.round(width / engine.getAspectRatio(camera));
  9409. size = { width: width, height: height };
  9410. }
  9411. else if (size.width && size.height) {
  9412. width = size.width;
  9413. height = size.height;
  9414. }
  9415. //If passing only width, computing height to keep display canvas ratio.
  9416. else if (size.width && !size.height) {
  9417. width = size.width;
  9418. height = Math.round(width / engine.getAspectRatio(camera));
  9419. size = { width: width, height: height };
  9420. }
  9421. //If passing only height, computing width to keep display canvas ratio.
  9422. else if (size.height && !size.width) {
  9423. height = size.height;
  9424. width = Math.round(height * engine.getAspectRatio(camera));
  9425. size = { width: width, height: height };
  9426. }
  9427. //Assuming here that "size" parameter is a number
  9428. else if (!isNaN(size)) {
  9429. height = size;
  9430. width = size;
  9431. }
  9432. else {
  9433. Tools.Error("Invalid 'size' parameter !");
  9434. return;
  9435. }
  9436. var scene = camera.getScene();
  9437. var previousCamera = null;
  9438. if (scene.activeCamera !== camera) {
  9439. previousCamera = scene.activeCamera;
  9440. scene.activeCamera = camera;
  9441. }
  9442. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9443. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9444. texture.renderList = null;
  9445. texture.samples = samples;
  9446. if (antialiasing) {
  9447. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9448. }
  9449. texture.onAfterRenderObservable.add(function () {
  9450. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9451. });
  9452. scene.incrementRenderId();
  9453. scene.resetCachedMaterial();
  9454. texture.render(true);
  9455. texture.dispose();
  9456. if (previousCamera) {
  9457. scene.activeCamera = previousCamera;
  9458. }
  9459. camera.getProjectionMatrix(true); // Force cache refresh;
  9460. };
  9461. // XHR response validator for local file scenario
  9462. Tools.ValidateXHRData = function (xhr, dataType) {
  9463. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9464. if (dataType === void 0) { dataType = 7; }
  9465. try {
  9466. if (dataType & 1) {
  9467. if (xhr.responseText && xhr.responseText.length > 0) {
  9468. return true;
  9469. }
  9470. else if (dataType === 1) {
  9471. return false;
  9472. }
  9473. }
  9474. if (dataType & 2) {
  9475. // Check header width and height since there is no "TGA" magic number
  9476. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9477. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9478. return true;
  9479. }
  9480. else if (dataType === 2) {
  9481. return false;
  9482. }
  9483. }
  9484. if (dataType & 4) {
  9485. // Check for the "DDS" magic number
  9486. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9487. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9488. return true;
  9489. }
  9490. else {
  9491. return false;
  9492. }
  9493. }
  9494. }
  9495. catch (e) {
  9496. // Global protection
  9497. }
  9498. return false;
  9499. };
  9500. /**
  9501. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9502. * Be aware Math.random() could cause collisions, but:
  9503. * "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"
  9504. */
  9505. Tools.RandomId = function () {
  9506. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9507. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9508. return v.toString(16);
  9509. });
  9510. };
  9511. /**
  9512. * Test if the given uri is a base64 string.
  9513. * @param uri The uri to test
  9514. * @return True if the uri is a base64 string or false otherwise.
  9515. */
  9516. Tools.IsBase64 = function (uri) {
  9517. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9518. };
  9519. /**
  9520. * Decode the given base64 uri.
  9521. * @param uri The uri to decode
  9522. * @return The decoded base64 data.
  9523. */
  9524. Tools.DecodeBase64 = function (uri) {
  9525. var decodedString = atob(uri.split(",")[1]);
  9526. var bufferLength = decodedString.length;
  9527. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9528. for (var i = 0; i < bufferLength; i++) {
  9529. bufferView[i] = decodedString.charCodeAt(i);
  9530. }
  9531. return bufferView.buffer;
  9532. };
  9533. Object.defineProperty(Tools, "NoneLogLevel", {
  9534. get: function () {
  9535. return Tools._NoneLogLevel;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(Tools, "MessageLogLevel", {
  9541. get: function () {
  9542. return Tools._MessageLogLevel;
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(Tools, "WarningLogLevel", {
  9548. get: function () {
  9549. return Tools._WarningLogLevel;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Tools, "ErrorLogLevel", {
  9555. get: function () {
  9556. return Tools._ErrorLogLevel;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Tools, "AllLogLevel", {
  9562. get: function () {
  9563. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Tools._AddLogEntry = function (entry) {
  9569. Tools._LogCache = entry + Tools._LogCache;
  9570. if (Tools.OnNewCacheEntry) {
  9571. Tools.OnNewCacheEntry(entry);
  9572. }
  9573. };
  9574. Tools._FormatMessage = function (message) {
  9575. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9576. var date = new Date();
  9577. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9578. };
  9579. Tools._LogDisabled = function (message) {
  9580. // nothing to do
  9581. };
  9582. Tools._LogEnabled = function (message) {
  9583. var formattedMessage = Tools._FormatMessage(message);
  9584. console.log("BJS - " + formattedMessage);
  9585. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9586. Tools._AddLogEntry(entry);
  9587. };
  9588. Tools._WarnDisabled = function (message) {
  9589. // nothing to do
  9590. };
  9591. Tools._WarnEnabled = function (message) {
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.warn("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Tools._ErrorDisabled = function (message) {
  9598. // nothing to do
  9599. };
  9600. Tools._ErrorEnabled = function (message) {
  9601. Tools.errorsCount++;
  9602. var formattedMessage = Tools._FormatMessage(message);
  9603. console.error("BJS - " + formattedMessage);
  9604. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9605. Tools._AddLogEntry(entry);
  9606. };
  9607. Object.defineProperty(Tools, "LogCache", {
  9608. get: function () {
  9609. return Tools._LogCache;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Tools.ClearLogCache = function () {
  9615. Tools._LogCache = "";
  9616. Tools.errorsCount = 0;
  9617. };
  9618. Object.defineProperty(Tools, "LogLevels", {
  9619. set: function (level) {
  9620. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9621. Tools.Log = Tools._LogEnabled;
  9622. }
  9623. else {
  9624. Tools.Log = Tools._LogDisabled;
  9625. }
  9626. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9627. Tools.Warn = Tools._WarnEnabled;
  9628. }
  9629. else {
  9630. Tools.Warn = Tools._WarnDisabled;
  9631. }
  9632. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9633. Tools.Error = Tools._ErrorEnabled;
  9634. }
  9635. else {
  9636. Tools.Error = Tools._ErrorDisabled;
  9637. }
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Tools.IsWindowObjectExist = function () {
  9643. return (typeof window) !== "undefined";
  9644. };
  9645. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9646. get: function () {
  9647. return Tools._PerformanceNoneLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9653. get: function () {
  9654. return Tools._PerformanceUserMarkLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9660. get: function () {
  9661. return Tools._PerformanceConsoleLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9667. set: function (level) {
  9668. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9669. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9670. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9671. return;
  9672. }
  9673. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9674. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9675. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9676. return;
  9677. }
  9678. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9679. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9685. };
  9686. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9687. };
  9688. Tools._StartUserMark = function (counterName, condition) {
  9689. if (condition === void 0) { condition = true; }
  9690. if (!Tools._performance) {
  9691. if (!Tools.IsWindowObjectExist()) {
  9692. return;
  9693. }
  9694. Tools._performance = window.performance;
  9695. }
  9696. if (!condition || !Tools._performance.mark) {
  9697. return;
  9698. }
  9699. Tools._performance.mark(counterName + "-Begin");
  9700. };
  9701. Tools._EndUserMark = function (counterName, condition) {
  9702. if (condition === void 0) { condition = true; }
  9703. if (!condition || !Tools._performance.mark) {
  9704. return;
  9705. }
  9706. Tools._performance.mark(counterName + "-End");
  9707. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9708. };
  9709. Tools._StartPerformanceConsole = function (counterName, condition) {
  9710. if (condition === void 0) { condition = true; }
  9711. if (!condition) {
  9712. return;
  9713. }
  9714. Tools._StartUserMark(counterName, condition);
  9715. if (console.time) {
  9716. console.time(counterName);
  9717. }
  9718. };
  9719. Tools._EndPerformanceConsole = function (counterName, condition) {
  9720. if (condition === void 0) { condition = true; }
  9721. if (!condition) {
  9722. return;
  9723. }
  9724. Tools._EndUserMark(counterName, condition);
  9725. if (console.time) {
  9726. console.timeEnd(counterName);
  9727. }
  9728. };
  9729. Object.defineProperty(Tools, "Now", {
  9730. get: function () {
  9731. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9732. return window.performance.now();
  9733. }
  9734. return Date.now();
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. /**
  9740. * This method will return the name of the class used to create the instance of the given object.
  9741. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9742. * @param object the object to get the class name from
  9743. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9744. */
  9745. Tools.GetClassName = function (object, isType) {
  9746. if (isType === void 0) { isType = false; }
  9747. var name = null;
  9748. if (!isType && object.getClassName) {
  9749. name = object.getClassName();
  9750. }
  9751. else {
  9752. if (object instanceof Object) {
  9753. var classObj = isType ? object : Object.getPrototypeOf(object);
  9754. name = classObj.constructor["__bjsclassName__"];
  9755. }
  9756. if (!name) {
  9757. name = typeof object;
  9758. }
  9759. }
  9760. return name;
  9761. };
  9762. Tools.First = function (array, predicate) {
  9763. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9764. var el = array_1[_i];
  9765. if (predicate(el)) {
  9766. return el;
  9767. }
  9768. }
  9769. return null;
  9770. };
  9771. /**
  9772. * This method will return the name of the full name of the class, including its owning module (if any).
  9773. * 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).
  9774. * @param object the object to get the class name from
  9775. * @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.
  9776. */
  9777. Tools.getFullClassName = function (object, isType) {
  9778. if (isType === void 0) { isType = false; }
  9779. var className = null;
  9780. var moduleName = null;
  9781. if (!isType && object.getClassName) {
  9782. className = object.getClassName();
  9783. }
  9784. else {
  9785. if (object instanceof Object) {
  9786. var classObj = isType ? object : Object.getPrototypeOf(object);
  9787. className = classObj.constructor["__bjsclassName__"];
  9788. moduleName = classObj.constructor["__bjsmoduleName__"];
  9789. }
  9790. if (!className) {
  9791. className = typeof object;
  9792. }
  9793. }
  9794. if (!className) {
  9795. return null;
  9796. }
  9797. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9798. };
  9799. /**
  9800. * 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.
  9801. * @param array
  9802. */
  9803. Tools.arrayOrStringFeeder = function (array) {
  9804. return function (index) {
  9805. if (index >= array.length) {
  9806. return null;
  9807. }
  9808. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9809. if (val && val.getHashCode) {
  9810. val = val.getHashCode();
  9811. }
  9812. if (typeof val === "string") {
  9813. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9814. }
  9815. return val;
  9816. };
  9817. };
  9818. /**
  9819. * Compute the hashCode of a stream of number
  9820. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9821. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9822. * @return the hash code computed
  9823. */
  9824. Tools.hashCodeFromStream = function (feeder) {
  9825. // Based from here: http://stackoverflow.com/a/7616484/802124
  9826. var hash = 0;
  9827. var index = 0;
  9828. var chr = feeder(index++);
  9829. while (chr != null) {
  9830. hash = ((hash << 5) - hash) + chr;
  9831. hash |= 0; // Convert to 32bit integer
  9832. chr = feeder(index++);
  9833. }
  9834. return hash;
  9835. };
  9836. /**
  9837. * Returns a promise that resolves after the given amount of time.
  9838. * @param delay Number of milliseconds to delay
  9839. * @returns Promise that resolves after the given amount of time
  9840. */
  9841. Tools.DelayAsync = function (delay) {
  9842. return new Promise(function (resolve) {
  9843. setTimeout(function () {
  9844. resolve();
  9845. }, delay);
  9846. });
  9847. };
  9848. Tools.BaseUrl = "";
  9849. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9850. /**
  9851. * Default behaviour for cors in the application.
  9852. * It can be a string if the expected behavior is identical in the entire app.
  9853. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9854. */
  9855. Tools.CorsBehavior = "anonymous";
  9856. Tools.UseFallbackTexture = true;
  9857. /**
  9858. * Use this object to register external classes like custom textures or material
  9859. * to allow the laoders to instantiate them
  9860. */
  9861. Tools.RegisteredExternalClasses = {};
  9862. // Used in case of a texture loading problem
  9863. 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";
  9864. Tools._tmpFloatArray = new Float32Array(1);
  9865. Tools.PreprocessUrl = function (url) {
  9866. return url;
  9867. };
  9868. // Logs
  9869. Tools._NoneLogLevel = 0;
  9870. Tools._MessageLogLevel = 1;
  9871. Tools._WarningLogLevel = 2;
  9872. Tools._ErrorLogLevel = 4;
  9873. Tools._LogCache = "";
  9874. Tools.errorsCount = 0;
  9875. Tools.Log = Tools._LogEnabled;
  9876. Tools.Warn = Tools._WarnEnabled;
  9877. Tools.Error = Tools._ErrorEnabled;
  9878. // Performances
  9879. Tools._PerformanceNoneLogLevel = 0;
  9880. Tools._PerformanceUserMarkLogLevel = 1;
  9881. Tools._PerformanceConsoleLogLevel = 2;
  9882. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9883. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9884. return Tools;
  9885. }());
  9886. BABYLON.Tools = Tools;
  9887. /**
  9888. * This class is used to track a performance counter which is number based.
  9889. * The user has access to many properties which give statistics of different nature
  9890. *
  9891. * The implementer can track two kinds of Performance Counter: time and count
  9892. * 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.
  9893. * 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.
  9894. */
  9895. var PerfCounter = /** @class */ (function () {
  9896. function PerfCounter() {
  9897. this._startMonitoringTime = 0;
  9898. this._min = 0;
  9899. this._max = 0;
  9900. this._average = 0;
  9901. this._lastSecAverage = 0;
  9902. this._current = 0;
  9903. this._totalValueCount = 0;
  9904. this._totalAccumulated = 0;
  9905. this._lastSecAccumulated = 0;
  9906. this._lastSecTime = 0;
  9907. this._lastSecValueCount = 0;
  9908. }
  9909. Object.defineProperty(PerfCounter.prototype, "min", {
  9910. /**
  9911. * Returns the smallest value ever
  9912. */
  9913. get: function () {
  9914. return this._min;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(PerfCounter.prototype, "max", {
  9920. /**
  9921. * Returns the biggest value ever
  9922. */
  9923. get: function () {
  9924. return this._max;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(PerfCounter.prototype, "average", {
  9930. /**
  9931. * Returns the average value since the performance counter is running
  9932. */
  9933. get: function () {
  9934. return this._average;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9940. /**
  9941. * Returns the average value of the last second the counter was monitored
  9942. */
  9943. get: function () {
  9944. return this._lastSecAverage;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(PerfCounter.prototype, "current", {
  9950. /**
  9951. * Returns the current value
  9952. */
  9953. get: function () {
  9954. return this._current;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(PerfCounter.prototype, "total", {
  9960. get: function () {
  9961. return this._totalAccumulated;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "count", {
  9967. get: function () {
  9968. return this._totalValueCount;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. /**
  9974. * Call this method to start monitoring a new frame.
  9975. * 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.
  9976. */
  9977. PerfCounter.prototype.fetchNewFrame = function () {
  9978. this._totalValueCount++;
  9979. this._current = 0;
  9980. this._lastSecValueCount++;
  9981. };
  9982. /**
  9983. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9984. * @param newCount the count value to add to the monitored count
  9985. * @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.
  9986. */
  9987. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9988. if (!PerfCounter.Enabled) {
  9989. return;
  9990. }
  9991. this._current += newCount;
  9992. if (fetchResult) {
  9993. this._fetchResult();
  9994. }
  9995. };
  9996. /**
  9997. * Start monitoring this performance counter
  9998. */
  9999. PerfCounter.prototype.beginMonitoring = function () {
  10000. if (!PerfCounter.Enabled) {
  10001. return;
  10002. }
  10003. this._startMonitoringTime = Tools.Now;
  10004. };
  10005. /**
  10006. * Compute the time lapsed since the previous beginMonitoring() call.
  10007. * @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
  10008. */
  10009. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10010. if (newFrame === void 0) { newFrame = true; }
  10011. if (!PerfCounter.Enabled) {
  10012. return;
  10013. }
  10014. if (newFrame) {
  10015. this.fetchNewFrame();
  10016. }
  10017. var currentTime = Tools.Now;
  10018. this._current = currentTime - this._startMonitoringTime;
  10019. if (newFrame) {
  10020. this._fetchResult();
  10021. }
  10022. };
  10023. PerfCounter.prototype._fetchResult = function () {
  10024. this._totalAccumulated += this._current;
  10025. this._lastSecAccumulated += this._current;
  10026. // Min/Max update
  10027. this._min = Math.min(this._min, this._current);
  10028. this._max = Math.max(this._max, this._current);
  10029. this._average = this._totalAccumulated / this._totalValueCount;
  10030. // Reset last sec?
  10031. var now = Tools.Now;
  10032. if ((now - this._lastSecTime) > 1000) {
  10033. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10034. this._lastSecTime = now;
  10035. this._lastSecAccumulated = 0;
  10036. this._lastSecValueCount = 0;
  10037. }
  10038. };
  10039. PerfCounter.Enabled = true;
  10040. return PerfCounter;
  10041. }());
  10042. BABYLON.PerfCounter = PerfCounter;
  10043. /**
  10044. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10045. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10046. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10047. * @param name The name of the class, case should be preserved
  10048. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10049. */
  10050. function className(name, module) {
  10051. return function (target) {
  10052. target["__bjsclassName__"] = name;
  10053. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10054. };
  10055. }
  10056. BABYLON.className = className;
  10057. /**
  10058. * An implementation of a loop for asynchronous functions.
  10059. */
  10060. var AsyncLoop = /** @class */ (function () {
  10061. /**
  10062. * Constroctor.
  10063. * @param iterations the number of iterations.
  10064. * @param _fn the function to run each iteration
  10065. * @param _successCallback the callback that will be called upon succesful execution
  10066. * @param offset starting offset.
  10067. */
  10068. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10069. if (offset === void 0) { offset = 0; }
  10070. this.iterations = iterations;
  10071. this._fn = _fn;
  10072. this._successCallback = _successCallback;
  10073. this.index = offset - 1;
  10074. this._done = false;
  10075. }
  10076. /**
  10077. * Execute the next iteration. Must be called after the last iteration was finished.
  10078. */
  10079. AsyncLoop.prototype.executeNext = function () {
  10080. if (!this._done) {
  10081. if (this.index + 1 < this.iterations) {
  10082. ++this.index;
  10083. this._fn(this);
  10084. }
  10085. else {
  10086. this.breakLoop();
  10087. }
  10088. }
  10089. };
  10090. /**
  10091. * Break the loop and run the success callback.
  10092. */
  10093. AsyncLoop.prototype.breakLoop = function () {
  10094. this._done = true;
  10095. this._successCallback();
  10096. };
  10097. /**
  10098. * Helper function
  10099. */
  10100. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10101. if (offset === void 0) { offset = 0; }
  10102. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10103. loop.executeNext();
  10104. return loop;
  10105. };
  10106. /**
  10107. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10108. * @param iterations total number of iterations
  10109. * @param syncedIterations number of synchronous iterations in each async iteration.
  10110. * @param fn the function to call each iteration.
  10111. * @param callback a success call back that will be called when iterating stops.
  10112. * @param breakFunction a break condition (optional)
  10113. * @param timeout timeout settings for the setTimeout function. default - 0.
  10114. * @constructor
  10115. */
  10116. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10117. if (timeout === void 0) { timeout = 0; }
  10118. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10119. if (breakFunction && breakFunction())
  10120. loop.breakLoop();
  10121. else {
  10122. setTimeout(function () {
  10123. for (var i = 0; i < syncedIterations; ++i) {
  10124. var iteration = (loop.index * syncedIterations) + i;
  10125. if (iteration >= iterations)
  10126. break;
  10127. fn(iteration);
  10128. if (breakFunction && breakFunction()) {
  10129. loop.breakLoop();
  10130. break;
  10131. }
  10132. }
  10133. loop.executeNext();
  10134. }, timeout);
  10135. }
  10136. }, callback);
  10137. };
  10138. return AsyncLoop;
  10139. }());
  10140. BABYLON.AsyncLoop = AsyncLoop;
  10141. })(BABYLON || (BABYLON = {}));
  10142. //# sourceMappingURL=babylon.tools.js.map
  10143. var BABYLON;
  10144. (function (BABYLON) {
  10145. var PromiseStates;
  10146. (function (PromiseStates) {
  10147. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10148. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10149. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10150. })(PromiseStates || (PromiseStates = {}));
  10151. var FulFillmentAgregator = /** @class */ (function () {
  10152. function FulFillmentAgregator() {
  10153. this.count = 0;
  10154. this.target = 0;
  10155. this.results = [];
  10156. }
  10157. return FulFillmentAgregator;
  10158. }());
  10159. var InternalPromise = /** @class */ (function () {
  10160. function InternalPromise(resolver) {
  10161. var _this = this;
  10162. this._state = PromiseStates.Pending;
  10163. this._children = new Array();
  10164. this._rejectWasConsumed = false;
  10165. if (!resolver) {
  10166. return;
  10167. }
  10168. try {
  10169. resolver(function (value) {
  10170. _this._resolve(value);
  10171. }, function (reason) {
  10172. _this._reject(reason);
  10173. });
  10174. }
  10175. catch (e) {
  10176. this._reject(e);
  10177. }
  10178. }
  10179. Object.defineProperty(InternalPromise.prototype, "_result", {
  10180. get: function () {
  10181. return this._resultValue;
  10182. },
  10183. set: function (value) {
  10184. this._resultValue = value;
  10185. if (this._parent && this._parent._result === undefined) {
  10186. this._parent._result = value;
  10187. }
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. InternalPromise.prototype.catch = function (onRejected) {
  10193. return this.then(undefined, onRejected);
  10194. };
  10195. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10196. var _this = this;
  10197. var newPromise = new InternalPromise();
  10198. newPromise._onFulfilled = onFulfilled;
  10199. newPromise._onRejected = onRejected;
  10200. // Composition
  10201. this._children.push(newPromise);
  10202. newPromise._parent = this;
  10203. if (this._state !== PromiseStates.Pending) {
  10204. BABYLON.Tools.SetImmediate(function () {
  10205. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10206. var returnedValue = newPromise._resolve(_this._result);
  10207. if (returnedValue !== undefined && returnedValue !== null) {
  10208. if (returnedValue._state !== undefined) {
  10209. var returnedPromise = returnedValue;
  10210. newPromise._children.push(returnedPromise);
  10211. returnedPromise._parent = newPromise;
  10212. newPromise = returnedPromise;
  10213. }
  10214. else {
  10215. newPromise._result = returnedValue;
  10216. }
  10217. }
  10218. }
  10219. else {
  10220. newPromise._reject(_this._reason);
  10221. }
  10222. });
  10223. }
  10224. return newPromise;
  10225. };
  10226. InternalPromise.prototype._moveChildren = function (children) {
  10227. var _this = this;
  10228. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10229. this._children.forEach(function (child) {
  10230. child._parent = _this;
  10231. });
  10232. if (this._state === PromiseStates.Fulfilled) {
  10233. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10234. var child = _b[_i];
  10235. child._resolve(this._result);
  10236. }
  10237. }
  10238. else if (this._state === PromiseStates.Rejected) {
  10239. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10240. var child = _d[_c];
  10241. child._reject(this._reason);
  10242. }
  10243. }
  10244. var _a;
  10245. };
  10246. InternalPromise.prototype._resolve = function (value) {
  10247. try {
  10248. this._state = PromiseStates.Fulfilled;
  10249. var returnedValue = null;
  10250. if (this._onFulfilled) {
  10251. returnedValue = this._onFulfilled(value);
  10252. }
  10253. if (returnedValue !== undefined && returnedValue !== null) {
  10254. if (returnedValue._state !== undefined) {
  10255. // Transmit children
  10256. var returnedPromise = returnedValue;
  10257. returnedPromise._parent = this;
  10258. returnedPromise._moveChildren(this._children);
  10259. value = returnedPromise._result;
  10260. }
  10261. else {
  10262. value = returnedValue;
  10263. }
  10264. }
  10265. this._result = value;
  10266. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10267. var child = _a[_i];
  10268. child._resolve(value);
  10269. }
  10270. this._children.length = 0;
  10271. delete this._onFulfilled;
  10272. delete this._onRejected;
  10273. }
  10274. catch (e) {
  10275. this._reject(e, true);
  10276. }
  10277. };
  10278. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10279. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10280. this._state = PromiseStates.Rejected;
  10281. this._reason = reason;
  10282. if (this._onRejected && !onLocalThrow) {
  10283. try {
  10284. this._onRejected(reason);
  10285. this._rejectWasConsumed = true;
  10286. }
  10287. catch (e) {
  10288. reason = e;
  10289. }
  10290. }
  10291. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10292. var child = _a[_i];
  10293. if (this._rejectWasConsumed) {
  10294. child._resolve(null);
  10295. }
  10296. else {
  10297. child._reject(reason);
  10298. }
  10299. }
  10300. this._children.length = 0;
  10301. delete this._onFulfilled;
  10302. delete this._onRejected;
  10303. };
  10304. InternalPromise.resolve = function (value) {
  10305. var newPromise = new InternalPromise();
  10306. newPromise._resolve(value);
  10307. return newPromise;
  10308. };
  10309. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10310. promise.then(function (value) {
  10311. agregator.results[index] = value;
  10312. agregator.count++;
  10313. if (agregator.count === agregator.target) {
  10314. agregator.rootPromise._resolve(agregator.results);
  10315. }
  10316. return null;
  10317. }, function (reason) {
  10318. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10319. agregator.rootPromise._reject(reason);
  10320. }
  10321. });
  10322. };
  10323. InternalPromise.all = function (promises) {
  10324. var newPromise = new InternalPromise();
  10325. var agregator = new FulFillmentAgregator();
  10326. agregator.target = promises.length;
  10327. agregator.rootPromise = newPromise;
  10328. if (promises.length) {
  10329. for (var index = 0; index < promises.length; index++) {
  10330. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10331. }
  10332. }
  10333. else {
  10334. newPromise._resolve([]);
  10335. }
  10336. return newPromise;
  10337. };
  10338. InternalPromise.race = function (promises) {
  10339. var newPromise = new InternalPromise();
  10340. if (promises.length) {
  10341. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10342. var promise = promises_1[_i];
  10343. promise.then(function (value) {
  10344. if (newPromise) {
  10345. newPromise._resolve(value);
  10346. newPromise = null;
  10347. }
  10348. return null;
  10349. }, function (reason) {
  10350. if (newPromise) {
  10351. newPromise._reject(reason);
  10352. newPromise = null;
  10353. }
  10354. });
  10355. }
  10356. }
  10357. return newPromise;
  10358. };
  10359. return InternalPromise;
  10360. }());
  10361. /**
  10362. * Helper class that provides a small promise polyfill
  10363. */
  10364. var PromisePolyfill = /** @class */ (function () {
  10365. function PromisePolyfill() {
  10366. }
  10367. /**
  10368. * Static function used to check if the polyfill is required
  10369. * If this is the case then the function will inject the polyfill to window.Promise
  10370. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10371. */
  10372. PromisePolyfill.Apply = function (force) {
  10373. if (force === void 0) { force = false; }
  10374. if (force || typeof Promise === 'undefined') {
  10375. var root = window;
  10376. root.Promise = InternalPromise;
  10377. }
  10378. };
  10379. return PromisePolyfill;
  10380. }());
  10381. BABYLON.PromisePolyfill = PromisePolyfill;
  10382. })(BABYLON || (BABYLON = {}));
  10383. //# sourceMappingURL=babylon.promise.js.map
  10384. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10385. var BABYLON;
  10386. (function (BABYLON) {
  10387. /**
  10388. * Helper class to push actions to a pool of workers.
  10389. */
  10390. var WorkerPool = /** @class */ (function () {
  10391. /**
  10392. * Constructor
  10393. * @param workers Array of workers to use for actions
  10394. */
  10395. function WorkerPool(workers) {
  10396. this._pendingActions = new Array();
  10397. this._workerInfos = workers.map(function (worker) { return ({
  10398. worker: worker,
  10399. active: false
  10400. }); });
  10401. }
  10402. /**
  10403. * Terminates all workers and clears any pending actions.
  10404. */
  10405. WorkerPool.prototype.dispose = function () {
  10406. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10407. var workerInfo = _a[_i];
  10408. workerInfo.worker.terminate();
  10409. }
  10410. delete this._workerInfos;
  10411. delete this._pendingActions;
  10412. };
  10413. /**
  10414. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10415. * pended until a worker has completed its action.
  10416. * @param action The action to perform. Call onComplete when the action is complete.
  10417. */
  10418. WorkerPool.prototype.push = function (action) {
  10419. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10420. var workerInfo = _a[_i];
  10421. if (!workerInfo.active) {
  10422. this._execute(workerInfo, action);
  10423. return;
  10424. }
  10425. }
  10426. this._pendingActions.push(action);
  10427. };
  10428. WorkerPool.prototype._execute = function (workerInfo, action) {
  10429. var _this = this;
  10430. workerInfo.active = true;
  10431. action(workerInfo.worker, function () {
  10432. workerInfo.active = false;
  10433. var nextAction = _this._pendingActions.shift();
  10434. if (nextAction) {
  10435. _this._execute(workerInfo, nextAction);
  10436. }
  10437. });
  10438. };
  10439. return WorkerPool;
  10440. }());
  10441. BABYLON.WorkerPool = WorkerPool;
  10442. })(BABYLON || (BABYLON = {}));
  10443. //# sourceMappingURL=babylon.workerPool.js.map
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. /**
  10447. * @hidden
  10448. **/
  10449. var _AlphaState = /** @class */ (function () {
  10450. /**
  10451. * Initializes the state.
  10452. */
  10453. function _AlphaState() {
  10454. this._isAlphaBlendDirty = false;
  10455. this._isBlendFunctionParametersDirty = false;
  10456. this._isBlendEquationParametersDirty = false;
  10457. this._isBlendConstantsDirty = false;
  10458. this._alphaBlend = false;
  10459. this._blendFunctionParameters = new Array(4);
  10460. this._blendEquationParameters = new Array(2);
  10461. this._blendConstants = new Array(4);
  10462. this.reset();
  10463. }
  10464. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10465. get: function () {
  10466. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10467. },
  10468. enumerable: true,
  10469. configurable: true
  10470. });
  10471. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10472. get: function () {
  10473. return this._alphaBlend;
  10474. },
  10475. set: function (value) {
  10476. if (this._alphaBlend === value) {
  10477. return;
  10478. }
  10479. this._alphaBlend = value;
  10480. this._isAlphaBlendDirty = true;
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10486. if (this._blendConstants[0] === r &&
  10487. this._blendConstants[1] === g &&
  10488. this._blendConstants[2] === b &&
  10489. this._blendConstants[3] === a) {
  10490. return;
  10491. }
  10492. this._blendConstants[0] = r;
  10493. this._blendConstants[1] = g;
  10494. this._blendConstants[2] = b;
  10495. this._blendConstants[3] = a;
  10496. this._isBlendConstantsDirty = true;
  10497. };
  10498. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10499. if (this._blendFunctionParameters[0] === value0 &&
  10500. this._blendFunctionParameters[1] === value1 &&
  10501. this._blendFunctionParameters[2] === value2 &&
  10502. this._blendFunctionParameters[3] === value3) {
  10503. return;
  10504. }
  10505. this._blendFunctionParameters[0] = value0;
  10506. this._blendFunctionParameters[1] = value1;
  10507. this._blendFunctionParameters[2] = value2;
  10508. this._blendFunctionParameters[3] = value3;
  10509. this._isBlendFunctionParametersDirty = true;
  10510. };
  10511. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10512. if (this._blendEquationParameters[0] === rgb &&
  10513. this._blendEquationParameters[1] === alpha) {
  10514. return;
  10515. }
  10516. this._blendEquationParameters[0] = rgb;
  10517. this._blendEquationParameters[1] = alpha;
  10518. this._isBlendEquationParametersDirty = true;
  10519. };
  10520. _AlphaState.prototype.reset = function () {
  10521. this._alphaBlend = false;
  10522. this._blendFunctionParameters[0] = null;
  10523. this._blendFunctionParameters[1] = null;
  10524. this._blendFunctionParameters[2] = null;
  10525. this._blendFunctionParameters[3] = null;
  10526. this._blendEquationParameters[0] = null;
  10527. this._blendEquationParameters[1] = null;
  10528. this._blendConstants[0] = null;
  10529. this._blendConstants[1] = null;
  10530. this._blendConstants[2] = null;
  10531. this._blendConstants[3] = null;
  10532. this._isAlphaBlendDirty = true;
  10533. this._isBlendFunctionParametersDirty = false;
  10534. this._isBlendEquationParametersDirty = false;
  10535. this._isBlendConstantsDirty = false;
  10536. };
  10537. _AlphaState.prototype.apply = function (gl) {
  10538. if (!this.isDirty) {
  10539. return;
  10540. }
  10541. // Alpha blend
  10542. if (this._isAlphaBlendDirty) {
  10543. if (this._alphaBlend) {
  10544. gl.enable(gl.BLEND);
  10545. }
  10546. else {
  10547. gl.disable(gl.BLEND);
  10548. }
  10549. this._isAlphaBlendDirty = false;
  10550. }
  10551. // Alpha function
  10552. if (this._isBlendFunctionParametersDirty) {
  10553. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10554. this._isBlendFunctionParametersDirty = false;
  10555. }
  10556. // Alpha equation
  10557. if (this._isBlendEquationParametersDirty) {
  10558. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10559. this._isBlendEquationParametersDirty = false;
  10560. }
  10561. // Constants
  10562. if (this._isBlendConstantsDirty) {
  10563. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10564. this._isBlendConstantsDirty = false;
  10565. }
  10566. };
  10567. return _AlphaState;
  10568. }());
  10569. BABYLON._AlphaState = _AlphaState;
  10570. })(BABYLON || (BABYLON = {}));
  10571. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10572. var BABYLON;
  10573. (function (BABYLON) {
  10574. /**
  10575. * @hidden
  10576. **/
  10577. var _DepthCullingState = /** @class */ (function () {
  10578. /**
  10579. * Initializes the state.
  10580. */
  10581. function _DepthCullingState() {
  10582. this._isDepthTestDirty = false;
  10583. this._isDepthMaskDirty = false;
  10584. this._isDepthFuncDirty = false;
  10585. this._isCullFaceDirty = false;
  10586. this._isCullDirty = false;
  10587. this._isZOffsetDirty = false;
  10588. this._isFrontFaceDirty = false;
  10589. this.reset();
  10590. }
  10591. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10592. get: function () {
  10593. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10599. get: function () {
  10600. return this._zOffset;
  10601. },
  10602. set: function (value) {
  10603. if (this._zOffset === value) {
  10604. return;
  10605. }
  10606. this._zOffset = value;
  10607. this._isZOffsetDirty = true;
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10613. get: function () {
  10614. return this._cullFace;
  10615. },
  10616. set: function (value) {
  10617. if (this._cullFace === value) {
  10618. return;
  10619. }
  10620. this._cullFace = value;
  10621. this._isCullFaceDirty = true;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10627. get: function () {
  10628. return this._cull;
  10629. },
  10630. set: function (value) {
  10631. if (this._cull === value) {
  10632. return;
  10633. }
  10634. this._cull = value;
  10635. this._isCullDirty = true;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10641. get: function () {
  10642. return this._depthFunc;
  10643. },
  10644. set: function (value) {
  10645. if (this._depthFunc === value) {
  10646. return;
  10647. }
  10648. this._depthFunc = value;
  10649. this._isDepthFuncDirty = true;
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10655. get: function () {
  10656. return this._depthMask;
  10657. },
  10658. set: function (value) {
  10659. if (this._depthMask === value) {
  10660. return;
  10661. }
  10662. this._depthMask = value;
  10663. this._isDepthMaskDirty = true;
  10664. },
  10665. enumerable: true,
  10666. configurable: true
  10667. });
  10668. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10669. get: function () {
  10670. return this._depthTest;
  10671. },
  10672. set: function (value) {
  10673. if (this._depthTest === value) {
  10674. return;
  10675. }
  10676. this._depthTest = value;
  10677. this._isDepthTestDirty = true;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10683. get: function () {
  10684. return this._frontFace;
  10685. },
  10686. set: function (value) {
  10687. if (this._frontFace === value) {
  10688. return;
  10689. }
  10690. this._frontFace = value;
  10691. this._isFrontFaceDirty = true;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. _DepthCullingState.prototype.reset = function () {
  10697. this._depthMask = true;
  10698. this._depthTest = true;
  10699. this._depthFunc = null;
  10700. this._cullFace = null;
  10701. this._cull = null;
  10702. this._zOffset = 0;
  10703. this._frontFace = null;
  10704. this._isDepthTestDirty = true;
  10705. this._isDepthMaskDirty = true;
  10706. this._isDepthFuncDirty = false;
  10707. this._isCullFaceDirty = false;
  10708. this._isCullDirty = false;
  10709. this._isZOffsetDirty = false;
  10710. this._isFrontFaceDirty = false;
  10711. };
  10712. _DepthCullingState.prototype.apply = function (gl) {
  10713. if (!this.isDirty) {
  10714. return;
  10715. }
  10716. // Cull
  10717. if (this._isCullDirty) {
  10718. if (this.cull) {
  10719. gl.enable(gl.CULL_FACE);
  10720. }
  10721. else {
  10722. gl.disable(gl.CULL_FACE);
  10723. }
  10724. this._isCullDirty = false;
  10725. }
  10726. // Cull face
  10727. if (this._isCullFaceDirty) {
  10728. gl.cullFace(this.cullFace);
  10729. this._isCullFaceDirty = false;
  10730. }
  10731. // Depth mask
  10732. if (this._isDepthMaskDirty) {
  10733. gl.depthMask(this.depthMask);
  10734. this._isDepthMaskDirty = false;
  10735. }
  10736. // Depth test
  10737. if (this._isDepthTestDirty) {
  10738. if (this.depthTest) {
  10739. gl.enable(gl.DEPTH_TEST);
  10740. }
  10741. else {
  10742. gl.disable(gl.DEPTH_TEST);
  10743. }
  10744. this._isDepthTestDirty = false;
  10745. }
  10746. // Depth func
  10747. if (this._isDepthFuncDirty) {
  10748. gl.depthFunc(this.depthFunc);
  10749. this._isDepthFuncDirty = false;
  10750. }
  10751. // zOffset
  10752. if (this._isZOffsetDirty) {
  10753. if (this.zOffset) {
  10754. gl.enable(gl.POLYGON_OFFSET_FILL);
  10755. gl.polygonOffset(this.zOffset, 0);
  10756. }
  10757. else {
  10758. gl.disable(gl.POLYGON_OFFSET_FILL);
  10759. }
  10760. this._isZOffsetDirty = false;
  10761. }
  10762. // Front face
  10763. if (this._isFrontFaceDirty) {
  10764. gl.frontFace(this.frontFace);
  10765. this._isFrontFaceDirty = false;
  10766. }
  10767. };
  10768. return _DepthCullingState;
  10769. }());
  10770. BABYLON._DepthCullingState = _DepthCullingState;
  10771. })(BABYLON || (BABYLON = {}));
  10772. //# sourceMappingURL=babylon.depthCullingState.js.map
  10773. var BABYLON;
  10774. (function (BABYLON) {
  10775. /**
  10776. * @hidden
  10777. **/
  10778. var _StencilState = /** @class */ (function () {
  10779. function _StencilState() {
  10780. this._isStencilTestDirty = false;
  10781. this._isStencilMaskDirty = false;
  10782. this._isStencilFuncDirty = false;
  10783. this._isStencilOpDirty = false;
  10784. this.reset();
  10785. }
  10786. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10787. get: function () {
  10788. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10794. get: function () {
  10795. return this._stencilFunc;
  10796. },
  10797. set: function (value) {
  10798. if (this._stencilFunc === value) {
  10799. return;
  10800. }
  10801. this._stencilFunc = value;
  10802. this._isStencilFuncDirty = true;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10808. get: function () {
  10809. return this._stencilFuncRef;
  10810. },
  10811. set: function (value) {
  10812. if (this._stencilFuncRef === value) {
  10813. return;
  10814. }
  10815. this._stencilFuncRef = value;
  10816. this._isStencilFuncDirty = true;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10822. get: function () {
  10823. return this._stencilFuncMask;
  10824. },
  10825. set: function (value) {
  10826. if (this._stencilFuncMask === value) {
  10827. return;
  10828. }
  10829. this._stencilFuncMask = value;
  10830. this._isStencilFuncDirty = true;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10836. get: function () {
  10837. return this._stencilOpStencilFail;
  10838. },
  10839. set: function (value) {
  10840. if (this._stencilOpStencilFail === value) {
  10841. return;
  10842. }
  10843. this._stencilOpStencilFail = value;
  10844. this._isStencilOpDirty = true;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10850. get: function () {
  10851. return this._stencilOpDepthFail;
  10852. },
  10853. set: function (value) {
  10854. if (this._stencilOpDepthFail === value) {
  10855. return;
  10856. }
  10857. this._stencilOpDepthFail = value;
  10858. this._isStencilOpDirty = true;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10864. get: function () {
  10865. return this._stencilOpStencilDepthPass;
  10866. },
  10867. set: function (value) {
  10868. if (this._stencilOpStencilDepthPass === value) {
  10869. return;
  10870. }
  10871. this._stencilOpStencilDepthPass = value;
  10872. this._isStencilOpDirty = true;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10878. get: function () {
  10879. return this._stencilMask;
  10880. },
  10881. set: function (value) {
  10882. if (this._stencilMask === value) {
  10883. return;
  10884. }
  10885. this._stencilMask = value;
  10886. this._isStencilMaskDirty = true;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10892. get: function () {
  10893. return this._stencilTest;
  10894. },
  10895. set: function (value) {
  10896. if (this._stencilTest === value) {
  10897. return;
  10898. }
  10899. this._stencilTest = value;
  10900. this._isStencilTestDirty = true;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. _StencilState.prototype.reset = function () {
  10906. this._stencilTest = false;
  10907. this._stencilMask = 0xFF;
  10908. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10909. this._stencilFuncRef = 1;
  10910. this._stencilFuncMask = 0xFF;
  10911. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10912. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10913. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10914. this._isStencilTestDirty = true;
  10915. this._isStencilMaskDirty = true;
  10916. this._isStencilFuncDirty = true;
  10917. this._isStencilOpDirty = true;
  10918. };
  10919. _StencilState.prototype.apply = function (gl) {
  10920. if (!this.isDirty) {
  10921. return;
  10922. }
  10923. // Stencil test
  10924. if (this._isStencilTestDirty) {
  10925. if (this.stencilTest) {
  10926. gl.enable(gl.STENCIL_TEST);
  10927. }
  10928. else {
  10929. gl.disable(gl.STENCIL_TEST);
  10930. }
  10931. this._isStencilTestDirty = false;
  10932. }
  10933. // Stencil mask
  10934. if (this._isStencilMaskDirty) {
  10935. gl.stencilMask(this.stencilMask);
  10936. this._isStencilMaskDirty = false;
  10937. }
  10938. // Stencil func
  10939. if (this._isStencilFuncDirty) {
  10940. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10941. this._isStencilFuncDirty = false;
  10942. }
  10943. // Stencil op
  10944. if (this._isStencilOpDirty) {
  10945. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10946. this._isStencilOpDirty = false;
  10947. }
  10948. };
  10949. return _StencilState;
  10950. }());
  10951. BABYLON._StencilState = _StencilState;
  10952. })(BABYLON || (BABYLON = {}));
  10953. //# sourceMappingURL=babylon.stencilState.js.map
  10954. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10955. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10956. s = arguments[i];
  10957. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10958. t[p] = s[p];
  10959. }
  10960. return t;
  10961. };
  10962. var BABYLON;
  10963. (function (BABYLON) {
  10964. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10965. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10966. };
  10967. var compileRawShader = function (gl, source, type) {
  10968. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10969. gl.shaderSource(shader, source);
  10970. gl.compileShader(shader);
  10971. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10972. var log = gl.getShaderInfoLog(shader);
  10973. if (log) {
  10974. throw new Error(log);
  10975. }
  10976. }
  10977. if (!shader) {
  10978. throw new Error("Something went wrong while compile the shader.");
  10979. }
  10980. return shader;
  10981. };
  10982. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10983. var magFilter = gl.NEAREST;
  10984. var minFilter = gl.NEAREST;
  10985. switch (samplingMode) {
  10986. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10987. magFilter = gl.LINEAR;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10996. magFilter = gl.LINEAR;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11005. magFilter = gl.NEAREST;
  11006. if (generateMipMaps) {
  11007. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11008. }
  11009. else {
  11010. minFilter = gl.NEAREST;
  11011. }
  11012. break;
  11013. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11014. magFilter = gl.NEAREST;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11017. }
  11018. else {
  11019. minFilter = gl.NEAREST;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11023. magFilter = gl.NEAREST;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_LINEAR:
  11041. magFilter = gl.NEAREST;
  11042. minFilter = gl.LINEAR;
  11043. break;
  11044. case BABYLON.Texture.NEAREST_NEAREST:
  11045. magFilter = gl.NEAREST;
  11046. minFilter = gl.NEAREST;
  11047. break;
  11048. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11049. magFilter = gl.LINEAR;
  11050. if (generateMipMaps) {
  11051. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11052. }
  11053. else {
  11054. minFilter = gl.NEAREST;
  11055. }
  11056. break;
  11057. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11058. magFilter = gl.LINEAR;
  11059. if (generateMipMaps) {
  11060. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11061. }
  11062. else {
  11063. minFilter = gl.NEAREST;
  11064. }
  11065. break;
  11066. case BABYLON.Texture.LINEAR_LINEAR:
  11067. magFilter = gl.LINEAR;
  11068. minFilter = gl.LINEAR;
  11069. break;
  11070. case BABYLON.Texture.LINEAR_NEAREST:
  11071. magFilter = gl.LINEAR;
  11072. minFilter = gl.NEAREST;
  11073. break;
  11074. }
  11075. return {
  11076. min: minFilter,
  11077. mag: magFilter
  11078. };
  11079. };
  11080. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11081. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11082. var img;
  11083. var onload = function () {
  11084. loadedImages[index] = img;
  11085. loadedImages._internalCount++;
  11086. if (scene) {
  11087. scene._removePendingData(img);
  11088. }
  11089. if (loadedImages._internalCount === 6) {
  11090. onfinish(loadedImages);
  11091. }
  11092. };
  11093. var onerror = function (message, exception) {
  11094. if (scene) {
  11095. scene._removePendingData(img);
  11096. }
  11097. if (onErrorCallBack) {
  11098. onErrorCallBack(message, exception);
  11099. }
  11100. };
  11101. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11102. if (scene) {
  11103. scene._addPendingData(img);
  11104. }
  11105. };
  11106. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11107. if (onError === void 0) { onError = null; }
  11108. var loadedImages = [];
  11109. loadedImages._internalCount = 0;
  11110. for (var index = 0; index < 6; index++) {
  11111. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11112. }
  11113. };
  11114. var BufferPointer = /** @class */ (function () {
  11115. function BufferPointer() {
  11116. }
  11117. return BufferPointer;
  11118. }());
  11119. /**
  11120. * Interface for attribute information associated with buffer instanciation
  11121. */
  11122. var InstancingAttributeInfo = /** @class */ (function () {
  11123. function InstancingAttributeInfo() {
  11124. }
  11125. return InstancingAttributeInfo;
  11126. }());
  11127. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11128. /**
  11129. * Define options used to create a render target texture
  11130. */
  11131. var RenderTargetCreationOptions = /** @class */ (function () {
  11132. function RenderTargetCreationOptions() {
  11133. }
  11134. return RenderTargetCreationOptions;
  11135. }());
  11136. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11137. /**
  11138. * Define options used to create a depth texture
  11139. */
  11140. var DepthTextureCreationOptions = /** @class */ (function () {
  11141. function DepthTextureCreationOptions() {
  11142. }
  11143. return DepthTextureCreationOptions;
  11144. }());
  11145. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11146. /**
  11147. * Class used to describe the capabilities of the engine relatively to the current browser
  11148. */
  11149. var EngineCapabilities = /** @class */ (function () {
  11150. function EngineCapabilities() {
  11151. }
  11152. return EngineCapabilities;
  11153. }());
  11154. BABYLON.EngineCapabilities = EngineCapabilities;
  11155. /**
  11156. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11157. */
  11158. var Engine = /** @class */ (function () {
  11159. /**
  11160. * Creates a new engine
  11161. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11162. * @param antialias defines enable antialiasing (default: false)
  11163. * @param options defines further options to be sent to the getContext() function
  11164. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11165. */
  11166. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11167. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11168. var _this = this;
  11169. // Public members
  11170. /**
  11171. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11172. */
  11173. this.forcePOTTextures = false;
  11174. /**
  11175. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11176. */
  11177. this.isFullscreen = false;
  11178. /**
  11179. * Gets a boolean indicating if the pointer is currently locked
  11180. */
  11181. this.isPointerLock = false;
  11182. /**
  11183. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11184. */
  11185. this.cullBackFaces = true;
  11186. /**
  11187. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11188. */
  11189. this.renderEvenInBackground = true;
  11190. /**
  11191. * Gets or sets a boolean indicating that cache can be kept between frames
  11192. */
  11193. this.preventCacheWipeBetweenFrames = false;
  11194. /**
  11195. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11196. **/
  11197. this.enableOfflineSupport = false;
  11198. /**
  11199. * 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)
  11200. **/
  11201. this.disableManifestCheck = false;
  11202. /**
  11203. * Gets the list of created scenes
  11204. */
  11205. this.scenes = new Array();
  11206. /**
  11207. * Gets the list of created postprocesses
  11208. */
  11209. this.postProcesses = new Array();
  11210. // Observables
  11211. /**
  11212. * Observable event triggered each time the rendering canvas is resized
  11213. */
  11214. this.onResizeObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable event triggered each time the canvas loses focus
  11217. */
  11218. this.onCanvasBlurObservable = new BABYLON.Observable();
  11219. /**
  11220. * Observable event triggered each time the canvas gains focus
  11221. */
  11222. this.onCanvasFocusObservable = new BABYLON.Observable();
  11223. /**
  11224. * Observable event triggered each time the canvas receives pointerout event
  11225. */
  11226. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11227. /**
  11228. * Observable event triggered before each texture is initialized
  11229. */
  11230. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11231. //WebVR
  11232. this._vrDisplay = undefined;
  11233. this._vrSupported = false;
  11234. this._vrExclusivePointerMode = false;
  11235. // Uniform buffers list
  11236. /**
  11237. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11238. */
  11239. this.disableUniformBuffers = false;
  11240. /** @hidden */
  11241. this._uniformBuffers = new Array();
  11242. // Observables
  11243. /**
  11244. * Observable raised when the engine begins a new frame
  11245. */
  11246. this.onBeginFrameObservable = new BABYLON.Observable();
  11247. /**
  11248. * Observable raised when the engine ends the current frame
  11249. */
  11250. this.onEndFrameObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable raised when the engine is about to compile a shader
  11253. */
  11254. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable raised when the engine has jsut compiled a shader
  11257. */
  11258. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11259. this._windowIsBackground = false;
  11260. this._webGLVersion = 1.0;
  11261. /** @hidden */
  11262. this._badOS = false;
  11263. /** @hidden */
  11264. this._badDesktopOS = false;
  11265. /**
  11266. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11267. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11268. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11269. */
  11270. this.disableTextureBindingOptimization = false;
  11271. /**
  11272. * Observable signaled when VR display mode changes
  11273. */
  11274. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable signaled when VR request present is complete
  11277. */
  11278. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11279. /**
  11280. * Observable signaled when VR request present starts
  11281. */
  11282. this.onVRRequestPresentStart = new BABYLON.Observable();
  11283. this._colorWrite = true;
  11284. /** @hidden */
  11285. this._drawCalls = new BABYLON.PerfCounter();
  11286. /** @hidden */
  11287. this._textureCollisions = new BABYLON.PerfCounter();
  11288. this._renderingQueueLaunched = false;
  11289. this._activeRenderLoops = new Array();
  11290. // Deterministic lockstepMaxSteps
  11291. this._deterministicLockstep = false;
  11292. this._lockstepMaxSteps = 4;
  11293. // Lost context
  11294. /**
  11295. * Observable signaled when a context lost event is raised
  11296. */
  11297. this.onContextLostObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable signaled when a context restored event is raised
  11300. */
  11301. this.onContextRestoredObservable = new BABYLON.Observable();
  11302. this._contextWasLost = false;
  11303. this._doNotHandleContextLost = false;
  11304. // FPS
  11305. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11306. this._fps = 60;
  11307. this._deltaTime = 0;
  11308. /**
  11309. * Turn this value on if you want to pause FPS computation when in background
  11310. */
  11311. this.disablePerformanceMonitorInBackground = false;
  11312. // States
  11313. /** @hidden */
  11314. this._depthCullingState = new BABYLON._DepthCullingState();
  11315. /** @hidden */
  11316. this._stencilState = new BABYLON._StencilState();
  11317. /** @hidden */
  11318. this._alphaState = new BABYLON._AlphaState();
  11319. /** @hidden */
  11320. this._alphaMode = Engine.ALPHA_DISABLE;
  11321. // Cache
  11322. this._internalTexturesCache = new Array();
  11323. /** @hidden */
  11324. this._activeChannel = 0;
  11325. this._currentTextureChannel = -1;
  11326. /** @hidden */
  11327. this._boundTexturesCache = {};
  11328. this._compiledEffects = {};
  11329. this._vertexAttribArraysEnabled = [];
  11330. this._uintIndicesCurrentlySet = false;
  11331. this._currentBoundBuffer = new Array();
  11332. this._currentBufferPointers = new Array();
  11333. this._currentInstanceLocations = new Array();
  11334. this._currentInstanceBuffers = new Array();
  11335. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11336. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11337. this._vaoRecordInProgress = false;
  11338. this._mustWipeVertexAttributes = false;
  11339. this._nextFreeTextureSlots = new Array();
  11340. this._maxSimultaneousTextures = 0;
  11341. this._activeRequests = new Array();
  11342. // Hardware supported Compressed Textures
  11343. this._texturesSupported = new Array();
  11344. this._onVRFullScreenTriggered = function () {
  11345. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11346. //get the old size before we change
  11347. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11348. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11349. //get the width and height, change the render size
  11350. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11351. _this.setHardwareScalingLevel(1);
  11352. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11353. }
  11354. else {
  11355. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11356. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11357. }
  11358. };
  11359. this._boundUniforms = {};
  11360. // Register promises
  11361. BABYLON.PromisePolyfill.Apply();
  11362. var canvas = null;
  11363. Engine.Instances.push(this);
  11364. if (!canvasOrContext) {
  11365. return;
  11366. }
  11367. options = options || {};
  11368. if (canvasOrContext.getContext) {
  11369. canvas = canvasOrContext;
  11370. this._renderingCanvas = canvas;
  11371. if (antialias != null) {
  11372. options.antialias = antialias;
  11373. }
  11374. if (options.deterministicLockstep === undefined) {
  11375. options.deterministicLockstep = false;
  11376. }
  11377. if (options.lockstepMaxSteps === undefined) {
  11378. options.lockstepMaxSteps = 4;
  11379. }
  11380. if (options.preserveDrawingBuffer === undefined) {
  11381. options.preserveDrawingBuffer = false;
  11382. }
  11383. if (options.audioEngine === undefined) {
  11384. options.audioEngine = true;
  11385. }
  11386. if (options.stencil === undefined) {
  11387. options.stencil = true;
  11388. }
  11389. this._deterministicLockstep = options.deterministicLockstep;
  11390. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11391. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11392. // Exceptions
  11393. if (navigator && navigator.userAgent) {
  11394. var ua = navigator.userAgent;
  11395. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11396. var exception = _a[_i];
  11397. var key = exception.key;
  11398. var targets = exception.targets;
  11399. if (ua.indexOf(key) > -1) {
  11400. if (exception.capture && exception.captureConstraint) {
  11401. var capture = exception.capture;
  11402. var constraint = exception.captureConstraint;
  11403. var regex = new RegExp(capture);
  11404. var matches = regex.exec(ua);
  11405. if (matches && matches.length > 0) {
  11406. var capturedValue = parseInt(matches[matches.length - 1]);
  11407. if (capturedValue >= constraint) {
  11408. continue;
  11409. }
  11410. }
  11411. }
  11412. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11413. var target = targets_1[_b];
  11414. switch (target) {
  11415. case "uniformBuffer":
  11416. this.disableUniformBuffers = true;
  11417. break;
  11418. case "textureBindingOptimization":
  11419. this.disableTextureBindingOptimization = true;
  11420. break;
  11421. }
  11422. }
  11423. }
  11424. }
  11425. }
  11426. // GL
  11427. if (!options.disableWebGL2Support) {
  11428. try {
  11429. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11430. if (this._gl) {
  11431. this._webGLVersion = 2.0;
  11432. }
  11433. }
  11434. catch (e) {
  11435. // Do nothing
  11436. }
  11437. }
  11438. if (!this._gl) {
  11439. if (!canvas) {
  11440. throw new Error("The provided canvas is null or undefined.");
  11441. }
  11442. try {
  11443. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11444. }
  11445. catch (e) {
  11446. throw new Error("WebGL not supported");
  11447. }
  11448. }
  11449. if (!this._gl) {
  11450. throw new Error("WebGL not supported");
  11451. }
  11452. this._onCanvasFocus = function () {
  11453. _this.onCanvasFocusObservable.notifyObservers(_this);
  11454. };
  11455. this._onCanvasBlur = function () {
  11456. _this.onCanvasBlurObservable.notifyObservers(_this);
  11457. };
  11458. canvas.addEventListener("focus", this._onCanvasFocus);
  11459. canvas.addEventListener("blur", this._onCanvasBlur);
  11460. this._onBlur = function () {
  11461. if (_this.disablePerformanceMonitorInBackground) {
  11462. _this._performanceMonitor.disable();
  11463. }
  11464. _this._windowIsBackground = true;
  11465. };
  11466. this._onFocus = function () {
  11467. if (_this.disablePerformanceMonitorInBackground) {
  11468. _this._performanceMonitor.enable();
  11469. }
  11470. _this._windowIsBackground = false;
  11471. };
  11472. this._onCanvasPointerOut = function (ev) {
  11473. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11474. };
  11475. window.addEventListener("blur", this._onBlur);
  11476. window.addEventListener("focus", this._onFocus);
  11477. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11478. // Context lost
  11479. if (!this._doNotHandleContextLost) {
  11480. this._onContextLost = function (evt) {
  11481. evt.preventDefault();
  11482. _this._contextWasLost = true;
  11483. BABYLON.Tools.Warn("WebGL context lost.");
  11484. _this.onContextLostObservable.notifyObservers(_this);
  11485. };
  11486. this._onContextRestored = function (evt) {
  11487. // Adding a timeout to avoid race condition at browser level
  11488. setTimeout(function () {
  11489. // Rebuild gl context
  11490. _this._initGLContext();
  11491. // Rebuild effects
  11492. _this._rebuildEffects();
  11493. // Rebuild textures
  11494. _this._rebuildInternalTextures();
  11495. // Rebuild buffers
  11496. _this._rebuildBuffers();
  11497. // Cache
  11498. _this.wipeCaches(true);
  11499. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11500. _this.onContextRestoredObservable.notifyObservers(_this);
  11501. _this._contextWasLost = false;
  11502. }, 0);
  11503. };
  11504. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11505. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11506. }
  11507. }
  11508. else {
  11509. this._gl = canvasOrContext;
  11510. this._renderingCanvas = this._gl.canvas;
  11511. if (this._gl.renderbufferStorageMultisample) {
  11512. this._webGLVersion = 2.0;
  11513. }
  11514. options.stencil = this._gl.getContextAttributes().stencil;
  11515. }
  11516. // Viewport
  11517. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11518. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11519. this.resize();
  11520. this._isStencilEnable = options.stencil ? true : false;
  11521. this._initGLContext();
  11522. if (canvas) {
  11523. // Fullscreen
  11524. this._onFullscreenChange = function () {
  11525. if (document.fullscreen !== undefined) {
  11526. _this.isFullscreen = document.fullscreen;
  11527. }
  11528. else if (document.mozFullScreen !== undefined) {
  11529. _this.isFullscreen = document.mozFullScreen;
  11530. }
  11531. else if (document.webkitIsFullScreen !== undefined) {
  11532. _this.isFullscreen = document.webkitIsFullScreen;
  11533. }
  11534. else if (document.msIsFullScreen !== undefined) {
  11535. _this.isFullscreen = document.msIsFullScreen;
  11536. }
  11537. // Pointer lock
  11538. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11539. canvas.requestPointerLock = canvas.requestPointerLock ||
  11540. canvas.msRequestPointerLock ||
  11541. canvas.mozRequestPointerLock ||
  11542. canvas.webkitRequestPointerLock;
  11543. if (canvas.requestPointerLock) {
  11544. canvas.requestPointerLock();
  11545. }
  11546. }
  11547. };
  11548. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11549. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11550. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11551. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11552. // Pointer lock
  11553. this._onPointerLockChange = function () {
  11554. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11555. document.webkitPointerLockElement === canvas ||
  11556. document.msPointerLockElement === canvas ||
  11557. document.pointerLockElement === canvas);
  11558. };
  11559. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11560. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11561. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11562. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11563. this._onVRDisplayPointerRestricted = function () {
  11564. if (canvas) {
  11565. canvas.requestPointerLock();
  11566. }
  11567. };
  11568. this._onVRDisplayPointerUnrestricted = function () {
  11569. document.exitPointerLock();
  11570. };
  11571. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11572. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11573. }
  11574. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11575. Engine.audioEngine = new BABYLON.AudioEngine();
  11576. }
  11577. // Prepare buffer pointers
  11578. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11579. this._currentBufferPointers[i] = new BufferPointer();
  11580. }
  11581. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11582. // Load WebVR Devices
  11583. if (options.autoEnableWebVR) {
  11584. this.initWebVR();
  11585. }
  11586. // Detect if we are running on a faulty buggy OS.
  11587. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11588. // Detect if we are running on a faulty buggy desktop OS.
  11589. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11590. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11591. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11592. }
  11593. Object.defineProperty(Engine, "LastCreatedEngine", {
  11594. /**
  11595. * Gets the latest created engine
  11596. */
  11597. get: function () {
  11598. if (Engine.Instances.length === 0) {
  11599. return null;
  11600. }
  11601. return Engine.Instances[Engine.Instances.length - 1];
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Object.defineProperty(Engine, "LastCreatedScene", {
  11607. /**
  11608. * Gets the latest created scene
  11609. */
  11610. get: function () {
  11611. var lastCreatedEngine = Engine.LastCreatedEngine;
  11612. if (!lastCreatedEngine) {
  11613. return null;
  11614. }
  11615. if (lastCreatedEngine.scenes.length === 0) {
  11616. return null;
  11617. }
  11618. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. /**
  11624. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11625. * @param flag defines which part of the materials must be marked as dirty
  11626. * @param predicate defines a predicate used to filter which materials should be affected
  11627. */
  11628. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11629. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11630. var engine = Engine.Instances[engineIndex];
  11631. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11632. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11633. }
  11634. }
  11635. };
  11636. Object.defineProperty(Engine, "NEVER", {
  11637. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11638. get: function () {
  11639. return Engine._NEVER;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine, "ALWAYS", {
  11645. /** 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 */
  11646. get: function () {
  11647. return Engine._ALWAYS;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "LESS", {
  11653. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11654. get: function () {
  11655. return Engine._LESS;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "EQUAL", {
  11661. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11662. get: function () {
  11663. return Engine._EQUAL;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "LEQUAL", {
  11669. /** 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 */
  11670. get: function () {
  11671. return Engine._LEQUAL;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "GREATER", {
  11677. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11678. get: function () {
  11679. return Engine._GREATER;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "GEQUAL", {
  11685. /** 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 */
  11686. get: function () {
  11687. return Engine._GEQUAL;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "NOTEQUAL", {
  11693. /** 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 */
  11694. get: function () {
  11695. return Engine._NOTEQUAL;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "KEEP", {
  11701. /** Passed to stencilOperation to specify that stencil value must be kept */
  11702. get: function () {
  11703. return Engine._KEEP;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "REPLACE", {
  11709. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11710. get: function () {
  11711. return Engine._REPLACE;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "INCR", {
  11717. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11718. get: function () {
  11719. return Engine._INCR;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "DECR", {
  11725. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11726. get: function () {
  11727. return Engine._DECR;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "INVERT", {
  11733. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11734. get: function () {
  11735. return Engine._INVERT;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "INCR_WRAP", {
  11741. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11742. get: function () {
  11743. return Engine._INCR_WRAP;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "DECR_WRAP", {
  11749. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11750. get: function () {
  11751. return Engine._DECR_WRAP;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11757. // Alpha
  11758. /** Defines that alpha blending is disabled */
  11759. get: function () {
  11760. return Engine._ALPHA_DISABLE;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11766. /** Defines that alpha blending to SRC + DEST */
  11767. get: function () {
  11768. return Engine._ALPHA_ONEONE;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "ALPHA_ADD", {
  11774. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11775. get: function () {
  11776. return Engine._ALPHA_ADD;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11782. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11783. get: function () {
  11784. return Engine._ALPHA_COMBINE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11790. /** Defines that alpha blending to DEST - SRC * DEST */
  11791. get: function () {
  11792. return Engine._ALPHA_SUBTRACT;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11798. /** Defines that alpha blending to SRC * DEST */
  11799. get: function () {
  11800. return Engine._ALPHA_MULTIPLY;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11806. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11807. get: function () {
  11808. return Engine._ALPHA_MAXIMIZED;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11814. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_PREMULTIPLIED;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11822. /**
  11823. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11824. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11825. */
  11826. get: function () {
  11827. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11833. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_INTERPOLATE;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11841. /**
  11842. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11843. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11844. */
  11845. get: function () {
  11846. return Engine._ALPHA_SCREENMODE;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11852. // Delays
  11853. /** Defines that the ressource is not delayed*/
  11854. get: function () {
  11855. return Engine._DELAYLOADSTATE_NONE;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11861. /** Defines that the ressource was successfully delay loaded */
  11862. get: function () {
  11863. return Engine._DELAYLOADSTATE_LOADED;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11869. /** Defines that the ressource is currently delay loading */
  11870. get: function () {
  11871. return Engine._DELAYLOADSTATE_LOADING;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11877. /** Defines that the ressource is delayed and has not started loading */
  11878. get: function () {
  11879. return Engine._DELAYLOADSTATE_NOTLOADED;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11885. /** ALPHA */
  11886. get: function () {
  11887. return Engine._TEXTUREFORMAT_ALPHA;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11893. /** LUMINANCE */
  11894. get: function () {
  11895. return Engine._TEXTUREFORMAT_LUMINANCE;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11901. /**
  11902. * R
  11903. */
  11904. get: function () {
  11905. return Engine._TEXTUREFORMAT_R;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11911. /**
  11912. * RG
  11913. */
  11914. get: function () {
  11915. return Engine._TEXTUREFORMAT_RG;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11921. /** LUMINANCE_ALPHA */
  11922. get: function () {
  11923. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11929. /** RGB */
  11930. get: function () {
  11931. return Engine._TEXTUREFORMAT_RGB;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11937. /** RGBA */
  11938. get: function () {
  11939. return Engine._TEXTUREFORMAT_RGBA;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11945. /** UNSIGNED_INT */
  11946. get: function () {
  11947. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11953. /** FLOAT */
  11954. get: function () {
  11955. return Engine._TEXTURETYPE_FLOAT;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11961. /** HALF_FLOAT */
  11962. get: function () {
  11963. return Engine._TEXTURETYPE_HALF_FLOAT;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11969. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11970. get: function () {
  11971. return Engine._SCALEMODE_FLOOR;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11977. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11978. get: function () {
  11979. return Engine._SCALEMODE_NEAREST;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11985. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11986. get: function () {
  11987. return Engine._SCALEMODE_CEILING;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "Version", {
  11993. /**
  11994. * Returns the current version of the framework
  11995. */
  11996. get: function () {
  11997. return "3.3.0-alpha.3";
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12003. /**
  12004. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12005. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12006. */
  12007. get: function () {
  12008. return this._vrExclusivePointerMode;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12014. /**
  12015. * Gets a boolean indicating that the engine supports uniform buffers
  12016. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12017. */
  12018. get: function () {
  12019. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12025. /**
  12026. * Gets a boolean indicating that only power of 2 textures are supported
  12027. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12028. */
  12029. get: function () {
  12030. return this._webGLVersion < 2 || this.forcePOTTextures;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12036. /**
  12037. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12038. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12039. */
  12040. get: function () {
  12041. return this._doNotHandleContextLost;
  12042. },
  12043. set: function (value) {
  12044. this._doNotHandleContextLost = value;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12050. /**
  12051. * Gets the performance monitor attached to this engine
  12052. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12053. */
  12054. get: function () {
  12055. return this._performanceMonitor;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12061. /**
  12062. * Gets the list of texture formats supported
  12063. */
  12064. get: function () {
  12065. return this._texturesSupported;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12071. /**
  12072. * Gets the list of texture formats in use
  12073. */
  12074. get: function () {
  12075. return this._textureFormatInUse;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine.prototype, "currentViewport", {
  12081. /**
  12082. * Gets the current viewport
  12083. */
  12084. get: function () {
  12085. return this._cachedViewport;
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12091. /**
  12092. * Gets the default empty texture
  12093. */
  12094. get: function () {
  12095. if (!this._emptyTexture) {
  12096. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12097. }
  12098. return this._emptyTexture;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12104. /**
  12105. * Gets the default empty 3D texture
  12106. */
  12107. get: function () {
  12108. if (!this._emptyTexture3D) {
  12109. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12110. }
  12111. return this._emptyTexture3D;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12117. /**
  12118. * Gets the default empty cube texture
  12119. */
  12120. get: function () {
  12121. if (!this._emptyCubeTexture) {
  12122. var faceData = new Uint8Array(4);
  12123. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12124. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12125. }
  12126. return this._emptyCubeTexture;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Engine.prototype._rebuildInternalTextures = function () {
  12132. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12133. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12134. var internalTexture = currentState_1[_i];
  12135. internalTexture._rebuild();
  12136. }
  12137. };
  12138. Engine.prototype._rebuildEffects = function () {
  12139. for (var key in this._compiledEffects) {
  12140. var effect = this._compiledEffects[key];
  12141. effect._prepareEffect();
  12142. }
  12143. BABYLON.Effect.ResetCache();
  12144. };
  12145. Engine.prototype._rebuildBuffers = function () {
  12146. // Index / Vertex
  12147. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12148. var scene = _a[_i];
  12149. scene.resetCachedMaterial();
  12150. scene._rebuildGeometries();
  12151. scene._rebuildTextures();
  12152. }
  12153. // Uniforms
  12154. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12155. var uniformBuffer = _c[_b];
  12156. uniformBuffer._rebuild();
  12157. }
  12158. };
  12159. Engine.prototype._initGLContext = function () {
  12160. // Caps
  12161. this._caps = new EngineCapabilities();
  12162. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12163. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12164. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12165. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12166. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12167. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12168. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12169. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12170. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12171. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12172. // Infos
  12173. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12174. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12175. if (rendererInfo != null) {
  12176. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12177. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12178. }
  12179. if (!this._glVendor) {
  12180. this._glVendor = "Unknown vendor";
  12181. }
  12182. if (!this._glRenderer) {
  12183. this._glRenderer = "Unknown renderer";
  12184. }
  12185. // Constants
  12186. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12187. if (this._gl.RGBA16F !== 0x881A) {
  12188. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12189. }
  12190. if (this._gl.RGBA32F !== 0x8814) {
  12191. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12192. }
  12193. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12194. this._gl.DEPTH24_STENCIL8 = 35056;
  12195. }
  12196. // Extensions
  12197. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12198. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12199. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12200. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12201. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12202. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12203. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12204. 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');
  12205. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12206. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12207. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12208. this._caps.highPrecisionShaderSupported = true;
  12209. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12210. if (this._caps.timerQuery) {
  12211. if (this._webGLVersion === 1) {
  12212. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12213. }
  12214. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12215. }
  12216. // Checks if some of the format renders first to allow the use of webgl inspector.
  12217. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12218. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12219. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12220. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12221. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12222. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12223. if (this._webGLVersion > 1) {
  12224. this._gl.HALF_FLOAT_OES = 0x140B;
  12225. }
  12226. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12227. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12228. // Draw buffers
  12229. if (this._webGLVersion > 1) {
  12230. this._caps.drawBuffersExtension = true;
  12231. }
  12232. else {
  12233. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12234. if (drawBuffersExtension !== null) {
  12235. this._caps.drawBuffersExtension = true;
  12236. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12237. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12238. for (var i = 0; i < 16; i++) {
  12239. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12240. }
  12241. }
  12242. else {
  12243. this._caps.drawBuffersExtension = false;
  12244. }
  12245. }
  12246. // Depth Texture
  12247. if (this._webGLVersion > 1) {
  12248. this._caps.depthTextureExtension = true;
  12249. }
  12250. else {
  12251. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12252. if (depthTextureExtension != null) {
  12253. this._caps.depthTextureExtension = true;
  12254. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12255. }
  12256. }
  12257. // Vertex array object
  12258. if (this._webGLVersion > 1) {
  12259. this._caps.vertexArrayObject = true;
  12260. }
  12261. else {
  12262. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12263. if (vertexArrayObjectExtension != null) {
  12264. this._caps.vertexArrayObject = true;
  12265. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12266. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12267. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12268. }
  12269. else {
  12270. this._caps.vertexArrayObject = false;
  12271. }
  12272. }
  12273. // Instances count
  12274. if (this._webGLVersion > 1) {
  12275. this._caps.instancedArrays = true;
  12276. }
  12277. else {
  12278. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12279. if (instanceExtension != null) {
  12280. this._caps.instancedArrays = true;
  12281. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12282. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12283. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12284. }
  12285. else {
  12286. this._caps.instancedArrays = false;
  12287. }
  12288. }
  12289. // Intelligently add supported compressed formats in order to check for.
  12290. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12291. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12292. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12293. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12294. if (this._caps.astc)
  12295. this.texturesSupported.push('-astc.ktx');
  12296. if (this._caps.s3tc)
  12297. this.texturesSupported.push('-dxt.ktx');
  12298. if (this._caps.pvrtc)
  12299. this.texturesSupported.push('-pvrtc.ktx');
  12300. if (this._caps.etc2)
  12301. this.texturesSupported.push('-etc2.ktx');
  12302. if (this._caps.etc1)
  12303. this.texturesSupported.push('-etc1.ktx');
  12304. if (this._gl.getShaderPrecisionFormat) {
  12305. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12306. if (highp) {
  12307. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12308. }
  12309. }
  12310. // Depth buffer
  12311. this.setDepthBuffer(true);
  12312. this.setDepthFunctionToLessOrEqual();
  12313. this.setDepthWrite(true);
  12314. // Texture maps
  12315. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12316. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12317. this._nextFreeTextureSlots.push(slot);
  12318. }
  12319. };
  12320. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12321. /**
  12322. * Gets version of the current webGL context
  12323. */
  12324. get: function () {
  12325. return this._webGLVersion;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12331. /**
  12332. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12333. */
  12334. get: function () {
  12335. return this._isStencilEnable;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. Engine.prototype._prepareWorkingCanvas = function () {
  12341. if (this._workingCanvas) {
  12342. return;
  12343. }
  12344. this._workingCanvas = document.createElement("canvas");
  12345. var context = this._workingCanvas.getContext("2d");
  12346. if (context) {
  12347. this._workingContext = context;
  12348. }
  12349. };
  12350. /**
  12351. * Reset the texture cache to empty state
  12352. */
  12353. Engine.prototype.resetTextureCache = function () {
  12354. for (var key in this._boundTexturesCache) {
  12355. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12356. continue;
  12357. }
  12358. var boundTexture = this._boundTexturesCache[key];
  12359. if (boundTexture) {
  12360. this._removeDesignatedSlot(boundTexture);
  12361. }
  12362. this._boundTexturesCache[key] = null;
  12363. }
  12364. if (!this.disableTextureBindingOptimization) {
  12365. this._nextFreeTextureSlots = [];
  12366. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12367. this._nextFreeTextureSlots.push(slot);
  12368. }
  12369. }
  12370. this._currentTextureChannel = -1;
  12371. };
  12372. /**
  12373. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12374. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12375. * @returns true if engine is in deterministic lock step mode
  12376. */
  12377. Engine.prototype.isDeterministicLockStep = function () {
  12378. return this._deterministicLockstep;
  12379. };
  12380. /**
  12381. * Gets the max steps when engine is running in deterministic lock step
  12382. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12383. * @returns the max steps
  12384. */
  12385. Engine.prototype.getLockstepMaxSteps = function () {
  12386. return this._lockstepMaxSteps;
  12387. };
  12388. /**
  12389. * Gets an object containing information about the current webGL context
  12390. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12391. */
  12392. Engine.prototype.getGlInfo = function () {
  12393. return {
  12394. vendor: this._glVendor,
  12395. renderer: this._glRenderer,
  12396. version: this._glVersion
  12397. };
  12398. };
  12399. /**
  12400. * Gets current aspect ratio
  12401. * @param camera defines the camera to use to get the aspect ratio
  12402. * @param useScreen defines if screen size must be used (or the current render target if any)
  12403. * @returns a number defining the aspect ratio
  12404. */
  12405. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12406. if (useScreen === void 0) { useScreen = false; }
  12407. var viewport = camera.viewport;
  12408. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12409. };
  12410. /**
  12411. * Gets current screen aspect ratio
  12412. * @returns a number defining the aspect ratio
  12413. */
  12414. Engine.prototype.getScreenAspectRatio = function () {
  12415. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12416. };
  12417. /**
  12418. * Gets the current render width
  12419. * @param useScreen defines if screen size must be used (or the current render target if any)
  12420. * @returns a number defining the current render width
  12421. */
  12422. Engine.prototype.getRenderWidth = function (useScreen) {
  12423. if (useScreen === void 0) { useScreen = false; }
  12424. if (!useScreen && this._currentRenderTarget) {
  12425. return this._currentRenderTarget.width;
  12426. }
  12427. return this._gl.drawingBufferWidth;
  12428. };
  12429. /**
  12430. * Gets the current render height
  12431. * @param useScreen defines if screen size must be used (or the current render target if any)
  12432. * @returns a number defining the current render height
  12433. */
  12434. Engine.prototype.getRenderHeight = function (useScreen) {
  12435. if (useScreen === void 0) { useScreen = false; }
  12436. if (!useScreen && this._currentRenderTarget) {
  12437. return this._currentRenderTarget.height;
  12438. }
  12439. return this._gl.drawingBufferHeight;
  12440. };
  12441. /**
  12442. * Gets the HTML canvas attached with the current webGL context
  12443. * @returns a HTML canvas
  12444. */
  12445. Engine.prototype.getRenderingCanvas = function () {
  12446. return this._renderingCanvas;
  12447. };
  12448. /**
  12449. * Gets the client rect of the HTML canvas attached with the current webGL context
  12450. * @returns a client rectanglee
  12451. */
  12452. Engine.prototype.getRenderingCanvasClientRect = function () {
  12453. if (!this._renderingCanvas) {
  12454. return null;
  12455. }
  12456. return this._renderingCanvas.getBoundingClientRect();
  12457. };
  12458. /**
  12459. * Defines the hardware scaling level.
  12460. * By default the hardware scaling level is computed from the window device ratio.
  12461. * 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.
  12462. * @param level defines the level to use
  12463. */
  12464. Engine.prototype.setHardwareScalingLevel = function (level) {
  12465. this._hardwareScalingLevel = level;
  12466. this.resize();
  12467. };
  12468. /**
  12469. * Gets the current hardware scaling level.
  12470. * By default the hardware scaling level is computed from the window device ratio.
  12471. * 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.
  12472. * @returns a number indicating the current hardware scaling level
  12473. */
  12474. Engine.prototype.getHardwareScalingLevel = function () {
  12475. return this._hardwareScalingLevel;
  12476. };
  12477. /**
  12478. * Gets the list of loaded textures
  12479. * @returns an array containing all loaded textures
  12480. */
  12481. Engine.prototype.getLoadedTexturesCache = function () {
  12482. return this._internalTexturesCache;
  12483. };
  12484. /**
  12485. * Gets the object containing all engine capabilities
  12486. * @returns the EngineCapabilities object
  12487. */
  12488. Engine.prototype.getCaps = function () {
  12489. return this._caps;
  12490. };
  12491. Object.defineProperty(Engine.prototype, "drawCalls", {
  12492. /** @hidden */
  12493. get: function () {
  12494. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12495. return 0;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12501. /** @hidden */
  12502. get: function () {
  12503. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12504. return null;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. /**
  12510. * Gets the current depth function
  12511. * @returns a number defining the depth function
  12512. */
  12513. Engine.prototype.getDepthFunction = function () {
  12514. return this._depthCullingState.depthFunc;
  12515. };
  12516. /**
  12517. * Sets the current depth function
  12518. * @param depthFunc defines the function to use
  12519. */
  12520. Engine.prototype.setDepthFunction = function (depthFunc) {
  12521. this._depthCullingState.depthFunc = depthFunc;
  12522. };
  12523. /**
  12524. * Sets the current depth function to GREATER
  12525. */
  12526. Engine.prototype.setDepthFunctionToGreater = function () {
  12527. this._depthCullingState.depthFunc = this._gl.GREATER;
  12528. };
  12529. /**
  12530. * Sets the current depth function to GEQUAL
  12531. */
  12532. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12533. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12534. };
  12535. /**
  12536. * Sets the current depth function to LESS
  12537. */
  12538. Engine.prototype.setDepthFunctionToLess = function () {
  12539. this._depthCullingState.depthFunc = this._gl.LESS;
  12540. };
  12541. /**
  12542. * Sets the current depth function to LEQUAL
  12543. */
  12544. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12545. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12546. };
  12547. /**
  12548. * Gets a boolean indicating if stencil buffer is enabled
  12549. * @returns the current stencil buffer state
  12550. */
  12551. Engine.prototype.getStencilBuffer = function () {
  12552. return this._stencilState.stencilTest;
  12553. };
  12554. /**
  12555. * Enable or disable the stencil buffer
  12556. * @param enable defines if the stencil buffer must be enabled or disabled
  12557. */
  12558. Engine.prototype.setStencilBuffer = function (enable) {
  12559. this._stencilState.stencilTest = enable;
  12560. };
  12561. /**
  12562. * Gets the current stencil mask
  12563. * @returns a number defining the new stencil mask to use
  12564. */
  12565. Engine.prototype.getStencilMask = function () {
  12566. return this._stencilState.stencilMask;
  12567. };
  12568. /**
  12569. * Sets the current stencil mask
  12570. * @param mask defines the new stencil mask to use
  12571. */
  12572. Engine.prototype.setStencilMask = function (mask) {
  12573. this._stencilState.stencilMask = mask;
  12574. };
  12575. /**
  12576. * Gets the current stencil function
  12577. * @returns a number defining the stencil function to use
  12578. */
  12579. Engine.prototype.getStencilFunction = function () {
  12580. return this._stencilState.stencilFunc;
  12581. };
  12582. /**
  12583. * Gets the current stencil reference value
  12584. * @returns a number defining the stencil reference value to use
  12585. */
  12586. Engine.prototype.getStencilFunctionReference = function () {
  12587. return this._stencilState.stencilFuncRef;
  12588. };
  12589. /**
  12590. * Gets the current stencil mask
  12591. * @returns a number defining the stencil mask to use
  12592. */
  12593. Engine.prototype.getStencilFunctionMask = function () {
  12594. return this._stencilState.stencilFuncMask;
  12595. };
  12596. /**
  12597. * Sets the current stencil function
  12598. * @param stencilFunc defines the new stencil function to use
  12599. */
  12600. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12601. this._stencilState.stencilFunc = stencilFunc;
  12602. };
  12603. /**
  12604. * Sets the current stencil reference
  12605. * @param reference defines the new stencil reference to use
  12606. */
  12607. Engine.prototype.setStencilFunctionReference = function (reference) {
  12608. this._stencilState.stencilFuncRef = reference;
  12609. };
  12610. /**
  12611. * Sets the current stencil mask
  12612. * @param mask defines the new stencil mask to use
  12613. */
  12614. Engine.prototype.setStencilFunctionMask = function (mask) {
  12615. this._stencilState.stencilFuncMask = mask;
  12616. };
  12617. /**
  12618. * Gets the current stencil operation when stencil fails
  12619. * @returns a number defining stencil operation to use when stencil fails
  12620. */
  12621. Engine.prototype.getStencilOperationFail = function () {
  12622. return this._stencilState.stencilOpStencilFail;
  12623. };
  12624. /**
  12625. * Gets the current stencil operation when depth fails
  12626. * @returns a number defining stencil operation to use when depth fails
  12627. */
  12628. Engine.prototype.getStencilOperationDepthFail = function () {
  12629. return this._stencilState.stencilOpDepthFail;
  12630. };
  12631. /**
  12632. * Gets the current stencil operation when stencil passes
  12633. * @returns a number defining stencil operation to use when stencil passes
  12634. */
  12635. Engine.prototype.getStencilOperationPass = function () {
  12636. return this._stencilState.stencilOpStencilDepthPass;
  12637. };
  12638. /**
  12639. * Sets the stencil operation to use when stencil fails
  12640. * @param operation defines the stencil operation to use when stencil fails
  12641. */
  12642. Engine.prototype.setStencilOperationFail = function (operation) {
  12643. this._stencilState.stencilOpStencilFail = operation;
  12644. };
  12645. /**
  12646. * Sets the stencil operation to use when depth fails
  12647. * @param operation defines the stencil operation to use when depth fails
  12648. */
  12649. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12650. this._stencilState.stencilOpDepthFail = operation;
  12651. };
  12652. /**
  12653. * Sets the stencil operation to use when stencil passes
  12654. * @param operation defines the stencil operation to use when stencil passes
  12655. */
  12656. Engine.prototype.setStencilOperationPass = function (operation) {
  12657. this._stencilState.stencilOpStencilDepthPass = operation;
  12658. };
  12659. /**
  12660. * Sets a boolean indicating if the dithering state is enabled or disabled
  12661. * @param value defines the dithering state
  12662. */
  12663. Engine.prototype.setDitheringState = function (value) {
  12664. if (value) {
  12665. this._gl.enable(this._gl.DITHER);
  12666. }
  12667. else {
  12668. this._gl.disable(this._gl.DITHER);
  12669. }
  12670. };
  12671. /**
  12672. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12673. * @param value defines the rasterizer state
  12674. */
  12675. Engine.prototype.setRasterizerState = function (value) {
  12676. if (value) {
  12677. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12678. }
  12679. else {
  12680. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12681. }
  12682. };
  12683. /**
  12684. * stop executing a render loop function and remove it from the execution array
  12685. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12686. */
  12687. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12688. if (!renderFunction) {
  12689. this._activeRenderLoops = [];
  12690. return;
  12691. }
  12692. var index = this._activeRenderLoops.indexOf(renderFunction);
  12693. if (index >= 0) {
  12694. this._activeRenderLoops.splice(index, 1);
  12695. }
  12696. };
  12697. /** @hidden */
  12698. Engine.prototype._renderLoop = function () {
  12699. if (!this._contextWasLost) {
  12700. var shouldRender = true;
  12701. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12702. shouldRender = false;
  12703. }
  12704. if (shouldRender) {
  12705. // Start new frame
  12706. this.beginFrame();
  12707. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12708. var renderFunction = this._activeRenderLoops[index];
  12709. renderFunction();
  12710. }
  12711. // Present
  12712. this.endFrame();
  12713. }
  12714. }
  12715. if (this._activeRenderLoops.length > 0) {
  12716. // Register new frame
  12717. var requester = null;
  12718. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12719. requester = this._vrDisplay;
  12720. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12721. }
  12722. else {
  12723. this._renderingQueueLaunched = false;
  12724. }
  12725. };
  12726. /**
  12727. * Register and execute a render loop. The engine can have more than one render function
  12728. * @param renderFunction defines the function to continuously execute
  12729. */
  12730. Engine.prototype.runRenderLoop = function (renderFunction) {
  12731. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12732. return;
  12733. }
  12734. this._activeRenderLoops.push(renderFunction);
  12735. if (!this._renderingQueueLaunched) {
  12736. this._renderingQueueLaunched = true;
  12737. this._bindedRenderFunction = this._renderLoop.bind(this);
  12738. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12739. }
  12740. };
  12741. /**
  12742. * Toggle full screen mode
  12743. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12744. * @param options defines an option object to be sent to the requestFullscreen function
  12745. */
  12746. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12747. if (this.isFullscreen) {
  12748. BABYLON.Tools.ExitFullscreen();
  12749. }
  12750. else {
  12751. this._pointerLockRequested = requestPointerLock;
  12752. if (this._renderingCanvas) {
  12753. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12754. }
  12755. }
  12756. };
  12757. /**
  12758. * Clear the current render buffer or the current render target (if any is set up)
  12759. * @param color defines the color to use
  12760. * @param backBuffer defines if the back buffer must be cleared
  12761. * @param depth defines if the depth buffer must be cleared
  12762. * @param stencil defines if the stencil buffer must be cleared
  12763. */
  12764. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12765. if (stencil === void 0) { stencil = false; }
  12766. this.applyStates();
  12767. var mode = 0;
  12768. if (backBuffer && color) {
  12769. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12770. mode |= this._gl.COLOR_BUFFER_BIT;
  12771. }
  12772. if (depth) {
  12773. this._gl.clearDepth(1.0);
  12774. mode |= this._gl.DEPTH_BUFFER_BIT;
  12775. }
  12776. if (stencil) {
  12777. this._gl.clearStencil(0);
  12778. mode |= this._gl.STENCIL_BUFFER_BIT;
  12779. }
  12780. this._gl.clear(mode);
  12781. };
  12782. /**
  12783. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12784. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12785. * @param y defines the y-coordinate of the corner of the clear rectangle
  12786. * @param width defines the width of the clear rectangle
  12787. * @param height defines the height of the clear rectangle
  12788. * @param clearColor defines the clear color
  12789. */
  12790. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12791. var gl = this._gl;
  12792. // Save state
  12793. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12794. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12795. // Change state
  12796. gl.enable(gl.SCISSOR_TEST);
  12797. gl.scissor(x, y, width, height);
  12798. // Clear
  12799. this.clear(clearColor, true, true, true);
  12800. // Restore state
  12801. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12802. if (curScissor === true) {
  12803. gl.enable(gl.SCISSOR_TEST);
  12804. }
  12805. else {
  12806. gl.disable(gl.SCISSOR_TEST);
  12807. }
  12808. };
  12809. /**
  12810. * Set the WebGL's viewport
  12811. * @param viewport defines the viewport element to be used
  12812. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12813. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12814. */
  12815. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12816. var width = requiredWidth || this.getRenderWidth();
  12817. var height = requiredHeight || this.getRenderHeight();
  12818. var x = viewport.x || 0;
  12819. var y = viewport.y || 0;
  12820. this._cachedViewport = viewport;
  12821. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12822. };
  12823. /**
  12824. * Directly set the WebGL Viewport
  12825. * @param x defines the x coordinate of the viewport (in screen space)
  12826. * @param y defines the y coordinate of the viewport (in screen space)
  12827. * @param width defines the width of the viewport (in screen space)
  12828. * @param height defines the height of the viewport (in screen space)
  12829. * @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
  12830. */
  12831. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12832. var currentViewport = this._cachedViewport;
  12833. this._cachedViewport = null;
  12834. this._gl.viewport(x, y, width, height);
  12835. return currentViewport;
  12836. };
  12837. /**
  12838. * Begin a new frame
  12839. */
  12840. Engine.prototype.beginFrame = function () {
  12841. this.onBeginFrameObservable.notifyObservers(this);
  12842. this._measureFps();
  12843. };
  12844. /**
  12845. * Enf the current frame
  12846. */
  12847. Engine.prototype.endFrame = function () {
  12848. // Force a flush in case we are using a bad OS.
  12849. if (this._badOS) {
  12850. this.flushFramebuffer();
  12851. }
  12852. // Submit frame to the vr device, if enabled
  12853. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12854. // TODO: We should only submit the frame if we read frameData successfully.
  12855. this._vrDisplay.submitFrame();
  12856. }
  12857. this.onEndFrameObservable.notifyObservers(this);
  12858. };
  12859. /**
  12860. * Resize the view according to the canvas' size
  12861. */
  12862. Engine.prototype.resize = function () {
  12863. // We're not resizing the size of the canvas while in VR mode & presenting
  12864. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12865. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12866. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12867. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12868. }
  12869. };
  12870. /**
  12871. * Force a specific size of the canvas
  12872. * @param width defines the new canvas' width
  12873. * @param height defines the new canvas' height
  12874. */
  12875. Engine.prototype.setSize = function (width, height) {
  12876. if (!this._renderingCanvas) {
  12877. return;
  12878. }
  12879. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12880. return;
  12881. }
  12882. this._renderingCanvas.width = width;
  12883. this._renderingCanvas.height = height;
  12884. for (var index = 0; index < this.scenes.length; index++) {
  12885. var scene = this.scenes[index];
  12886. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12887. var cam = scene.cameras[camIndex];
  12888. cam._currentRenderId = 0;
  12889. }
  12890. }
  12891. if (this.onResizeObservable.hasObservers) {
  12892. this.onResizeObservable.notifyObservers(this);
  12893. }
  12894. };
  12895. // WebVR functions
  12896. /**
  12897. * Gets a boolean indicating if a webVR device was detected
  12898. * @returns true if a webVR device was detected
  12899. */
  12900. Engine.prototype.isVRDevicePresent = function () {
  12901. return !!this._vrDisplay;
  12902. };
  12903. /**
  12904. * Gets the current webVR device
  12905. * @returns the current webVR device (or null)
  12906. */
  12907. Engine.prototype.getVRDevice = function () {
  12908. return this._vrDisplay;
  12909. };
  12910. /**
  12911. * Initializes a webVR display and starts listening to display change events
  12912. * The onVRDisplayChangedObservable will be notified upon these changes
  12913. * @returns The onVRDisplayChangedObservable
  12914. */
  12915. Engine.prototype.initWebVR = function () {
  12916. this.initWebVRAsync();
  12917. return this.onVRDisplayChangedObservable;
  12918. };
  12919. /**
  12920. * Initializes a webVR display and starts listening to display change events
  12921. * The onVRDisplayChangedObservable will be notified upon these changes
  12922. * @returns A promise containing a VRDisplay and if vr is supported
  12923. */
  12924. Engine.prototype.initWebVRAsync = function () {
  12925. var _this = this;
  12926. var notifyObservers = function () {
  12927. var eventArgs = {
  12928. vrDisplay: _this._vrDisplay,
  12929. vrSupported: _this._vrSupported
  12930. };
  12931. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12932. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12933. };
  12934. if (!this._onVrDisplayConnect) {
  12935. this._onVrDisplayConnect = function (event) {
  12936. _this._vrDisplay = event.display;
  12937. notifyObservers();
  12938. };
  12939. this._onVrDisplayDisconnect = function () {
  12940. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12941. _this._vrDisplay = undefined;
  12942. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12943. notifyObservers();
  12944. };
  12945. this._onVrDisplayPresentChange = function () {
  12946. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12947. };
  12948. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12949. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12950. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12951. }
  12952. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12953. this._webVRInitPromise.then(notifyObservers);
  12954. return this._webVRInitPromise;
  12955. };
  12956. /**
  12957. * Call this function to switch to webVR mode
  12958. * Will do nothing if webVR is not supported or if there is no webVR device
  12959. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12960. */
  12961. Engine.prototype.enableVR = function () {
  12962. var _this = this;
  12963. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12964. var onResolved = function () {
  12965. _this.onVRRequestPresentComplete.notifyObservers(true);
  12966. _this._onVRFullScreenTriggered();
  12967. };
  12968. var onRejected = function () {
  12969. _this.onVRRequestPresentComplete.notifyObservers(false);
  12970. };
  12971. this.onVRRequestPresentStart.notifyObservers(this);
  12972. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12973. }
  12974. };
  12975. /**
  12976. * Call this function to leave webVR mode
  12977. * Will do nothing if webVR is not supported or if there is no webVR device
  12978. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12979. */
  12980. Engine.prototype.disableVR = function () {
  12981. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12982. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12983. }
  12984. };
  12985. Engine.prototype._getVRDisplaysAsync = function () {
  12986. var _this = this;
  12987. return new Promise(function (res, rej) {
  12988. if (navigator.getVRDisplays) {
  12989. navigator.getVRDisplays().then(function (devices) {
  12990. _this._vrSupported = true;
  12991. // note that devices may actually be an empty array. This is fine;
  12992. // we expect this._vrDisplay to be undefined in this case.
  12993. _this._vrDisplay = devices[0];
  12994. res({
  12995. vrDisplay: _this._vrDisplay,
  12996. vrSupported: _this._vrSupported
  12997. });
  12998. });
  12999. }
  13000. else {
  13001. _this._vrDisplay = undefined;
  13002. _this._vrSupported = false;
  13003. res({
  13004. vrDisplay: _this._vrDisplay,
  13005. vrSupported: _this._vrSupported
  13006. });
  13007. }
  13008. });
  13009. };
  13010. /**
  13011. * Binds the frame buffer to the specified texture.
  13012. * @param texture The texture to render to or null for the default canvas
  13013. * @param faceIndex The face of the texture to render to in case of cube texture
  13014. * @param requiredWidth The width of the target to render to
  13015. * @param requiredHeight The height of the target to render to
  13016. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13017. * @param depthStencilTexture The depth stencil texture to use to render
  13018. */
  13019. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13020. if (this._currentRenderTarget) {
  13021. this.unBindFramebuffer(this._currentRenderTarget);
  13022. }
  13023. this._currentRenderTarget = texture;
  13024. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13025. var gl = this._gl;
  13026. if (texture.isCube) {
  13027. if (faceIndex === undefined) {
  13028. faceIndex = 0;
  13029. }
  13030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13031. if (depthStencilTexture) {
  13032. if (depthStencilTexture._generateStencilBuffer) {
  13033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13034. }
  13035. else {
  13036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13037. }
  13038. }
  13039. }
  13040. if (this._cachedViewport && !forceFullscreenViewport) {
  13041. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13042. }
  13043. else {
  13044. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13045. }
  13046. this.wipeCaches();
  13047. };
  13048. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13049. if (this._currentFramebuffer !== framebuffer) {
  13050. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13051. this._currentFramebuffer = framebuffer;
  13052. }
  13053. };
  13054. /**
  13055. * Unbind the current render target texture from the webGL context
  13056. * @param texture defines the render target texture to unbind
  13057. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13058. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13059. */
  13060. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13061. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13062. this._currentRenderTarget = null;
  13063. // If MSAA, we need to bitblt back to main texture
  13064. var gl = this._gl;
  13065. if (texture._MSAAFramebuffer) {
  13066. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13067. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13068. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13069. }
  13070. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13071. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13072. gl.generateMipmap(gl.TEXTURE_2D);
  13073. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13074. }
  13075. if (onBeforeUnbind) {
  13076. if (texture._MSAAFramebuffer) {
  13077. // Bind the correct framebuffer
  13078. this.bindUnboundFramebuffer(texture._framebuffer);
  13079. }
  13080. onBeforeUnbind();
  13081. }
  13082. this.bindUnboundFramebuffer(null);
  13083. };
  13084. /**
  13085. * Unbind a list of render target textures from the webGL context
  13086. * This is used only when drawBuffer extension or webGL2 are active
  13087. * @param textures defines the render target textures to unbind
  13088. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13089. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13090. */
  13091. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13092. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13093. this._currentRenderTarget = null;
  13094. // If MSAA, we need to bitblt back to main texture
  13095. var gl = this._gl;
  13096. if (textures[0]._MSAAFramebuffer) {
  13097. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13098. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13099. var attachments = textures[0]._attachments;
  13100. if (!attachments) {
  13101. attachments = new Array(textures.length);
  13102. textures[0]._attachments = attachments;
  13103. }
  13104. for (var i = 0; i < textures.length; i++) {
  13105. var texture = textures[i];
  13106. for (var j = 0; j < attachments.length; j++) {
  13107. attachments[j] = gl.NONE;
  13108. }
  13109. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13110. gl.readBuffer(attachments[i]);
  13111. gl.drawBuffers(attachments);
  13112. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13113. }
  13114. for (var i = 0; i < attachments.length; i++) {
  13115. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13116. }
  13117. gl.drawBuffers(attachments);
  13118. }
  13119. for (var i = 0; i < textures.length; i++) {
  13120. var texture = textures[i];
  13121. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13122. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13123. gl.generateMipmap(gl.TEXTURE_2D);
  13124. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13125. }
  13126. }
  13127. if (onBeforeUnbind) {
  13128. if (textures[0]._MSAAFramebuffer) {
  13129. // Bind the correct framebuffer
  13130. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13131. }
  13132. onBeforeUnbind();
  13133. }
  13134. this.bindUnboundFramebuffer(null);
  13135. };
  13136. /**
  13137. * Force the mipmap generation for the given render target texture
  13138. * @param texture defines the render target texture to use
  13139. */
  13140. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13141. if (texture.generateMipMaps) {
  13142. var gl = this._gl;
  13143. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13144. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13145. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13146. }
  13147. };
  13148. /**
  13149. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13150. */
  13151. Engine.prototype.flushFramebuffer = function () {
  13152. this._gl.flush();
  13153. };
  13154. /**
  13155. * Unbind the current render target and bind the default framebuffer
  13156. */
  13157. Engine.prototype.restoreDefaultFramebuffer = function () {
  13158. if (this._currentRenderTarget) {
  13159. this.unBindFramebuffer(this._currentRenderTarget);
  13160. }
  13161. else {
  13162. this.bindUnboundFramebuffer(null);
  13163. }
  13164. if (this._cachedViewport) {
  13165. this.setViewport(this._cachedViewport);
  13166. }
  13167. this.wipeCaches();
  13168. };
  13169. // UBOs
  13170. /**
  13171. * Create an uniform buffer
  13172. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13173. * @param elements defines the content of the uniform buffer
  13174. * @returns the webGL uniform buffer
  13175. */
  13176. Engine.prototype.createUniformBuffer = function (elements) {
  13177. var ubo = this._gl.createBuffer();
  13178. if (!ubo) {
  13179. throw new Error("Unable to create uniform buffer");
  13180. }
  13181. this.bindUniformBuffer(ubo);
  13182. if (elements instanceof Float32Array) {
  13183. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13184. }
  13185. else {
  13186. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13187. }
  13188. this.bindUniformBuffer(null);
  13189. ubo.references = 1;
  13190. return ubo;
  13191. };
  13192. /**
  13193. * Create a dynamic uniform buffer
  13194. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13195. * @param elements defines the content of the uniform buffer
  13196. * @returns the webGL uniform buffer
  13197. */
  13198. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13199. var ubo = this._gl.createBuffer();
  13200. if (!ubo) {
  13201. throw new Error("Unable to create dynamic uniform buffer");
  13202. }
  13203. this.bindUniformBuffer(ubo);
  13204. if (elements instanceof Float32Array) {
  13205. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13206. }
  13207. else {
  13208. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13209. }
  13210. this.bindUniformBuffer(null);
  13211. ubo.references = 1;
  13212. return ubo;
  13213. };
  13214. /**
  13215. * Update an existing uniform buffer
  13216. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13217. * @param uniformBuffer defines the target uniform buffer
  13218. * @param elements defines the content to update
  13219. * @param offset defines the offset in the uniform buffer where update should start
  13220. * @param count defines the size of the data to update
  13221. */
  13222. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13223. this.bindUniformBuffer(uniformBuffer);
  13224. if (offset === undefined) {
  13225. offset = 0;
  13226. }
  13227. if (count === undefined) {
  13228. if (elements instanceof Float32Array) {
  13229. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13230. }
  13231. else {
  13232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13233. }
  13234. }
  13235. else {
  13236. if (elements instanceof Float32Array) {
  13237. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13238. }
  13239. else {
  13240. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13241. }
  13242. }
  13243. this.bindUniformBuffer(null);
  13244. };
  13245. // VBOs
  13246. Engine.prototype._resetVertexBufferBinding = function () {
  13247. this.bindArrayBuffer(null);
  13248. this._cachedVertexBuffers = null;
  13249. };
  13250. /**
  13251. * Creates a vertex buffer
  13252. * @param data the data for the vertex buffer
  13253. * @returns the new WebGL static buffer
  13254. */
  13255. Engine.prototype.createVertexBuffer = function (data) {
  13256. var vbo = this._gl.createBuffer();
  13257. if (!vbo) {
  13258. throw new Error("Unable to create vertex buffer");
  13259. }
  13260. this.bindArrayBuffer(vbo);
  13261. if (data instanceof Array) {
  13262. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13263. }
  13264. else {
  13265. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13266. }
  13267. this._resetVertexBufferBinding();
  13268. vbo.references = 1;
  13269. return vbo;
  13270. };
  13271. /**
  13272. * Creates a dynamic vertex buffer
  13273. * @param data the data for the dynamic vertex buffer
  13274. * @returns the new WebGL dynamic buffer
  13275. */
  13276. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13277. var vbo = this._gl.createBuffer();
  13278. if (!vbo) {
  13279. throw new Error("Unable to create dynamic vertex buffer");
  13280. }
  13281. this.bindArrayBuffer(vbo);
  13282. if (data instanceof Array) {
  13283. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13287. }
  13288. this._resetVertexBufferBinding();
  13289. vbo.references = 1;
  13290. return vbo;
  13291. };
  13292. /**
  13293. * Update a dynamic index buffer
  13294. * @param indexBuffer defines the target index buffer
  13295. * @param indices defines the data to update
  13296. * @param offset defines the offset in the target index buffer where update should start
  13297. */
  13298. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13299. if (offset === void 0) { offset = 0; }
  13300. // Force cache update
  13301. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13302. this.bindIndexBuffer(indexBuffer);
  13303. var arrayBuffer;
  13304. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13305. arrayBuffer = indices;
  13306. }
  13307. else {
  13308. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13309. }
  13310. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13311. this._resetIndexBufferBinding();
  13312. };
  13313. /**
  13314. * Updates a dynamic vertex buffer.
  13315. * @param vertexBuffer the vertex buffer to update
  13316. * @param data the data used to update the vertex buffer
  13317. * @param byteOffset the byte offset of the data
  13318. * @param byteLength the byte length of the data
  13319. */
  13320. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13321. this.bindArrayBuffer(vertexBuffer);
  13322. if (byteOffset === undefined) {
  13323. byteOffset = 0;
  13324. }
  13325. if (byteLength === undefined) {
  13326. if (data instanceof Array) {
  13327. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13328. }
  13329. else {
  13330. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13331. }
  13332. }
  13333. else {
  13334. if (data instanceof Array) {
  13335. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13336. }
  13337. else {
  13338. if (data instanceof ArrayBuffer) {
  13339. data = new Uint8Array(data, byteOffset, byteLength);
  13340. }
  13341. else {
  13342. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13343. }
  13344. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13345. }
  13346. }
  13347. this._resetVertexBufferBinding();
  13348. };
  13349. Engine.prototype._resetIndexBufferBinding = function () {
  13350. this.bindIndexBuffer(null);
  13351. this._cachedIndexBuffer = null;
  13352. };
  13353. /**
  13354. * Creates a new index buffer
  13355. * @param indices defines the content of the index buffer
  13356. * @param updatable defines if the index buffer must be updatable
  13357. * @returns a new webGL buffer
  13358. */
  13359. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13360. var vbo = this._gl.createBuffer();
  13361. if (!vbo) {
  13362. throw new Error("Unable to create index buffer");
  13363. }
  13364. this.bindIndexBuffer(vbo);
  13365. // Check for 32 bits indices
  13366. var arrayBuffer;
  13367. var need32Bits = false;
  13368. if (indices instanceof Uint16Array) {
  13369. arrayBuffer = indices;
  13370. }
  13371. else {
  13372. //check 32 bit support
  13373. if (this._caps.uintIndices) {
  13374. if (indices instanceof Uint32Array) {
  13375. arrayBuffer = indices;
  13376. need32Bits = true;
  13377. }
  13378. else {
  13379. //number[] or Int32Array, check if 32 bit is necessary
  13380. for (var index = 0; index < indices.length; index++) {
  13381. if (indices[index] > 65535) {
  13382. need32Bits = true;
  13383. break;
  13384. }
  13385. }
  13386. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13387. }
  13388. }
  13389. else {
  13390. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13391. arrayBuffer = new Uint16Array(indices);
  13392. }
  13393. }
  13394. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13395. this._resetIndexBufferBinding();
  13396. vbo.references = 1;
  13397. vbo.is32Bits = need32Bits;
  13398. return vbo;
  13399. };
  13400. /**
  13401. * Bind a webGL buffer to the webGL context
  13402. * @param buffer defines the buffer to bind
  13403. */
  13404. Engine.prototype.bindArrayBuffer = function (buffer) {
  13405. if (!this._vaoRecordInProgress) {
  13406. this._unbindVertexArrayObject();
  13407. }
  13408. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13409. };
  13410. /**
  13411. * Bind an uniform buffer to the current webGL context
  13412. * @param buffer defines the buffer to bind
  13413. */
  13414. Engine.prototype.bindUniformBuffer = function (buffer) {
  13415. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13416. };
  13417. /**
  13418. * Bind a buffer to the current webGL context at a given location
  13419. * @param buffer defines the buffer to bind
  13420. * @param location defines the index where to bind the buffer
  13421. */
  13422. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13423. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13424. };
  13425. /**
  13426. * Bind a specific block at a given index in a specific shader program
  13427. * @param shaderProgram defines the shader program
  13428. * @param blockName defines the block name
  13429. * @param index defines the index where to bind the block
  13430. */
  13431. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13432. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13433. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13434. };
  13435. ;
  13436. Engine.prototype.bindIndexBuffer = function (buffer) {
  13437. if (!this._vaoRecordInProgress) {
  13438. this._unbindVertexArrayObject();
  13439. }
  13440. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13441. };
  13442. Engine.prototype.bindBuffer = function (buffer, target) {
  13443. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13444. this._gl.bindBuffer(target, buffer);
  13445. this._currentBoundBuffer[target] = buffer;
  13446. }
  13447. };
  13448. /**
  13449. * update the bound buffer with the given data
  13450. * @param data defines the data to update
  13451. */
  13452. Engine.prototype.updateArrayBuffer = function (data) {
  13453. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13454. };
  13455. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13456. var pointer = this._currentBufferPointers[indx];
  13457. var changed = false;
  13458. if (!pointer.active) {
  13459. changed = true;
  13460. pointer.active = true;
  13461. pointer.index = indx;
  13462. pointer.size = size;
  13463. pointer.type = type;
  13464. pointer.normalized = normalized;
  13465. pointer.stride = stride;
  13466. pointer.offset = offset;
  13467. pointer.buffer = buffer;
  13468. }
  13469. else {
  13470. if (pointer.buffer !== buffer) {
  13471. pointer.buffer = buffer;
  13472. changed = true;
  13473. }
  13474. if (pointer.size !== size) {
  13475. pointer.size = size;
  13476. changed = true;
  13477. }
  13478. if (pointer.type !== type) {
  13479. pointer.type = type;
  13480. changed = true;
  13481. }
  13482. if (pointer.normalized !== normalized) {
  13483. pointer.normalized = normalized;
  13484. changed = true;
  13485. }
  13486. if (pointer.stride !== stride) {
  13487. pointer.stride = stride;
  13488. changed = true;
  13489. }
  13490. if (pointer.offset !== offset) {
  13491. pointer.offset = offset;
  13492. changed = true;
  13493. }
  13494. }
  13495. if (changed || this._vaoRecordInProgress) {
  13496. this.bindArrayBuffer(buffer);
  13497. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13498. }
  13499. };
  13500. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13501. if (indexBuffer == null) {
  13502. return;
  13503. }
  13504. if (this._cachedIndexBuffer !== indexBuffer) {
  13505. this._cachedIndexBuffer = indexBuffer;
  13506. this.bindIndexBuffer(indexBuffer);
  13507. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13508. }
  13509. };
  13510. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13511. var attributes = effect.getAttributesNames();
  13512. if (!this._vaoRecordInProgress) {
  13513. this._unbindVertexArrayObject();
  13514. }
  13515. this.unbindAllAttributes();
  13516. for (var index = 0; index < attributes.length; index++) {
  13517. var order = effect.getAttributeLocation(index);
  13518. if (order >= 0) {
  13519. var vertexBuffer = vertexBuffers[attributes[index]];
  13520. if (!vertexBuffer) {
  13521. continue;
  13522. }
  13523. this._gl.enableVertexAttribArray(order);
  13524. if (!this._vaoRecordInProgress) {
  13525. this._vertexAttribArraysEnabled[order] = true;
  13526. }
  13527. var buffer = vertexBuffer.getBuffer();
  13528. if (buffer) {
  13529. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13530. if (vertexBuffer.getIsInstanced()) {
  13531. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13532. if (!this._vaoRecordInProgress) {
  13533. this._currentInstanceLocations.push(order);
  13534. this._currentInstanceBuffers.push(buffer);
  13535. }
  13536. }
  13537. }
  13538. }
  13539. }
  13540. };
  13541. /**
  13542. * Records a vertex array object
  13543. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13544. * @param vertexBuffers defines the list of vertex buffers to store
  13545. * @param indexBuffer defines the index buffer to store
  13546. * @param effect defines the effect to store
  13547. * @returns the new vertex array object
  13548. */
  13549. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13550. var vao = this._gl.createVertexArray();
  13551. this._vaoRecordInProgress = true;
  13552. this._gl.bindVertexArray(vao);
  13553. this._mustWipeVertexAttributes = true;
  13554. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13555. this.bindIndexBuffer(indexBuffer);
  13556. this._vaoRecordInProgress = false;
  13557. this._gl.bindVertexArray(null);
  13558. return vao;
  13559. };
  13560. /**
  13561. * Bind a specific vertex array object
  13562. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13563. * @param vertexArrayObject defines the vertex array object to bind
  13564. * @param indexBuffer defines the index buffer to bind
  13565. */
  13566. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13567. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13568. this._cachedVertexArrayObject = vertexArrayObject;
  13569. this._gl.bindVertexArray(vertexArrayObject);
  13570. this._cachedVertexBuffers = null;
  13571. this._cachedIndexBuffer = null;
  13572. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13573. this._mustWipeVertexAttributes = true;
  13574. }
  13575. };
  13576. /**
  13577. * Bind webGl buffers directly to the webGL context
  13578. * @param vertexBuffer defines the vertex buffer to bind
  13579. * @param indexBuffer defines the index buffer to bind
  13580. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13581. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13582. * @param effect defines the effect associated with the vertex buffer
  13583. */
  13584. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13585. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13586. this._cachedVertexBuffers = vertexBuffer;
  13587. this._cachedEffectForVertexBuffers = effect;
  13588. var attributesCount = effect.getAttributesCount();
  13589. this._unbindVertexArrayObject();
  13590. this.unbindAllAttributes();
  13591. var offset = 0;
  13592. for (var index = 0; index < attributesCount; index++) {
  13593. if (index < vertexDeclaration.length) {
  13594. var order = effect.getAttributeLocation(index);
  13595. if (order >= 0) {
  13596. this._gl.enableVertexAttribArray(order);
  13597. this._vertexAttribArraysEnabled[order] = true;
  13598. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13599. }
  13600. offset += vertexDeclaration[index] * 4;
  13601. }
  13602. }
  13603. }
  13604. this._bindIndexBufferWithCache(indexBuffer);
  13605. };
  13606. Engine.prototype._unbindVertexArrayObject = function () {
  13607. if (!this._cachedVertexArrayObject) {
  13608. return;
  13609. }
  13610. this._cachedVertexArrayObject = null;
  13611. this._gl.bindVertexArray(null);
  13612. };
  13613. /**
  13614. * Bind a list of vertex buffers to the webGL context
  13615. * @param vertexBuffers defines the list of vertex buffers to bind
  13616. * @param indexBuffer defines the index buffer to bind
  13617. * @param effect defines the effect associated with the vertex buffers
  13618. */
  13619. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13620. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13621. this._cachedVertexBuffers = vertexBuffers;
  13622. this._cachedEffectForVertexBuffers = effect;
  13623. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13624. }
  13625. this._bindIndexBufferWithCache(indexBuffer);
  13626. };
  13627. /**
  13628. * Unbind all instance attributes
  13629. */
  13630. Engine.prototype.unbindInstanceAttributes = function () {
  13631. var boundBuffer;
  13632. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13633. var instancesBuffer = this._currentInstanceBuffers[i];
  13634. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13635. boundBuffer = instancesBuffer;
  13636. this.bindArrayBuffer(instancesBuffer);
  13637. }
  13638. var offsetLocation = this._currentInstanceLocations[i];
  13639. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13640. }
  13641. this._currentInstanceBuffers.length = 0;
  13642. this._currentInstanceLocations.length = 0;
  13643. };
  13644. /**
  13645. * Release and free the memory of a vertex array object
  13646. * @param vao defines the vertex array object to delete
  13647. */
  13648. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13649. this._gl.deleteVertexArray(vao);
  13650. };
  13651. /** @hidden */
  13652. Engine.prototype._releaseBuffer = function (buffer) {
  13653. buffer.references--;
  13654. if (buffer.references === 0) {
  13655. this._gl.deleteBuffer(buffer);
  13656. return true;
  13657. }
  13658. return false;
  13659. };
  13660. /**
  13661. * Creates a webGL buffer to use with instanciation
  13662. * @param capacity defines the size of the buffer
  13663. * @returns the webGL buffer
  13664. */
  13665. Engine.prototype.createInstancesBuffer = function (capacity) {
  13666. var buffer = this._gl.createBuffer();
  13667. if (!buffer) {
  13668. throw new Error("Unable to create instance buffer");
  13669. }
  13670. buffer.capacity = capacity;
  13671. this.bindArrayBuffer(buffer);
  13672. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13673. return buffer;
  13674. };
  13675. /**
  13676. * Delete a webGL buffer used with instanciation
  13677. * @param buffer defines the webGL buffer to delete
  13678. */
  13679. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13680. this._gl.deleteBuffer(buffer);
  13681. };
  13682. /**
  13683. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13684. * @param instancesBuffer defines the webGL buffer to update and bind
  13685. * @param data defines the data to store in the buffer
  13686. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13687. */
  13688. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13689. this.bindArrayBuffer(instancesBuffer);
  13690. if (data) {
  13691. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13692. }
  13693. if (offsetLocations[0].index !== undefined) {
  13694. var stride = 0;
  13695. for (var i = 0; i < offsetLocations.length; i++) {
  13696. var ai = offsetLocations[i];
  13697. stride += ai.attributeSize * 4;
  13698. }
  13699. for (var i = 0; i < offsetLocations.length; i++) {
  13700. var ai = offsetLocations[i];
  13701. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13702. this._gl.enableVertexAttribArray(ai.index);
  13703. this._vertexAttribArraysEnabled[ai.index] = true;
  13704. }
  13705. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13706. this._gl.vertexAttribDivisor(ai.index, 1);
  13707. this._currentInstanceLocations.push(ai.index);
  13708. this._currentInstanceBuffers.push(instancesBuffer);
  13709. }
  13710. }
  13711. else {
  13712. for (var index = 0; index < 4; index++) {
  13713. var offsetLocation = offsetLocations[index];
  13714. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13715. this._gl.enableVertexAttribArray(offsetLocation);
  13716. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13717. }
  13718. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13719. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13720. this._currentInstanceLocations.push(offsetLocation);
  13721. this._currentInstanceBuffers.push(instancesBuffer);
  13722. }
  13723. }
  13724. };
  13725. /**
  13726. * Apply all cached states (depth, culling, stencil and alpha)
  13727. */
  13728. Engine.prototype.applyStates = function () {
  13729. this._depthCullingState.apply(this._gl);
  13730. this._stencilState.apply(this._gl);
  13731. this._alphaState.apply(this._gl);
  13732. };
  13733. /**
  13734. * Send a draw order
  13735. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13736. * @param indexStart defines the starting index
  13737. * @param indexCount defines the number of index to draw
  13738. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13739. */
  13740. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13741. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13742. };
  13743. /**
  13744. * Draw a list of points
  13745. * @param verticesStart defines the index of first vertex to draw
  13746. * @param verticesCount defines the count of vertices to draw
  13747. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13748. */
  13749. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13750. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13751. };
  13752. /**
  13753. * Draw a list of unindexed primitives
  13754. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13755. * @param verticesStart defines the index of first vertex to draw
  13756. * @param verticesCount defines the count of vertices to draw
  13757. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13758. */
  13759. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13760. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13761. };
  13762. /**
  13763. * Draw a list of indexed primitives
  13764. * @param fillMode defines the primitive to use
  13765. * @param indexStart defines the starting index
  13766. * @param indexCount defines the number of index to draw
  13767. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13768. */
  13769. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13770. // Apply states
  13771. this.applyStates();
  13772. this._drawCalls.addCount(1, false);
  13773. // Render
  13774. var drawMode = this._drawMode(fillMode);
  13775. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13776. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13777. if (instancesCount) {
  13778. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13779. }
  13780. else {
  13781. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13782. }
  13783. };
  13784. /**
  13785. * Draw a list of unindexed primitives
  13786. * @param fillMode defines the primitive to use
  13787. * @param verticesStart defines the index of first vertex to draw
  13788. * @param verticesCount defines the count of vertices to draw
  13789. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13790. */
  13791. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13792. // Apply states
  13793. this.applyStates();
  13794. this._drawCalls.addCount(1, false);
  13795. var drawMode = this._drawMode(fillMode);
  13796. if (instancesCount) {
  13797. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13798. }
  13799. else {
  13800. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13801. }
  13802. };
  13803. Engine.prototype._drawMode = function (fillMode) {
  13804. switch (fillMode) {
  13805. // Triangle views
  13806. case BABYLON.Material.TriangleFillMode:
  13807. return this._gl.TRIANGLES;
  13808. case BABYLON.Material.PointFillMode:
  13809. return this._gl.POINTS;
  13810. case BABYLON.Material.WireFrameFillMode:
  13811. return this._gl.LINES;
  13812. // Draw modes
  13813. case BABYLON.Material.PointListDrawMode:
  13814. return this._gl.POINTS;
  13815. case BABYLON.Material.LineListDrawMode:
  13816. return this._gl.LINES;
  13817. case BABYLON.Material.LineLoopDrawMode:
  13818. return this._gl.LINE_LOOP;
  13819. case BABYLON.Material.LineStripDrawMode:
  13820. return this._gl.LINE_STRIP;
  13821. case BABYLON.Material.TriangleStripDrawMode:
  13822. return this._gl.TRIANGLE_STRIP;
  13823. case BABYLON.Material.TriangleFanDrawMode:
  13824. return this._gl.TRIANGLE_FAN;
  13825. default:
  13826. return this._gl.TRIANGLES;
  13827. }
  13828. };
  13829. // Shaders
  13830. /** @hidden */
  13831. Engine.prototype._releaseEffect = function (effect) {
  13832. if (this._compiledEffects[effect._key]) {
  13833. delete this._compiledEffects[effect._key];
  13834. this._deleteProgram(effect.getProgram());
  13835. }
  13836. };
  13837. /** @hidden */
  13838. Engine.prototype._deleteProgram = function (program) {
  13839. if (program) {
  13840. program.__SPECTOR_rebuildProgram = null;
  13841. if (program.transformFeedback) {
  13842. this.deleteTransformFeedback(program.transformFeedback);
  13843. program.transformFeedback = null;
  13844. }
  13845. this._gl.deleteProgram(program);
  13846. }
  13847. };
  13848. /**
  13849. * Create a new effect (used to store vertex/fragment shaders)
  13850. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13851. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13852. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13853. * @param samplers defines an array of string used to represent textures
  13854. * @param defines defines the string containing the defines to use to compile the shaders
  13855. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13856. * @param onCompiled defines a function to call when the effect creation is successful
  13857. * @param onError defines a function to call when the effect creation has failed
  13858. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13859. * @returns the new Effect
  13860. */
  13861. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13862. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13863. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13864. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13865. if (this._compiledEffects[name]) {
  13866. var compiledEffect = this._compiledEffects[name];
  13867. if (onCompiled && compiledEffect.isReady()) {
  13868. onCompiled(compiledEffect);
  13869. }
  13870. return compiledEffect;
  13871. }
  13872. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13873. effect._key = name;
  13874. this._compiledEffects[name] = effect;
  13875. return effect;
  13876. };
  13877. /**
  13878. * Create an effect to use with particle systems
  13879. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13880. * @param uniformsNames defines a list of attribute names
  13881. * @param samplers defines an array of string used to represent textures
  13882. * @param defines defines the string containing the defines to use to compile the shaders
  13883. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13884. * @param onCompiled defines a function to call when the effect creation is successful
  13885. * @param onError defines a function to call when the effect creation has failed
  13886. * @returns the new Effect
  13887. */
  13888. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13889. if (uniformsNames === void 0) { uniformsNames = []; }
  13890. if (samplers === void 0) { samplers = []; }
  13891. if (defines === void 0) { defines = ""; }
  13892. return this.createEffect({
  13893. vertex: "particles",
  13894. fragmentElement: fragmentName
  13895. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13896. };
  13897. /**
  13898. * Directly creates a webGL program
  13899. * @param vertexCode defines the vertex shader code to use
  13900. * @param fragmentCode defines the fragment shader code to use
  13901. * @param context defines the webGL context to use (if not set, the current one will be used)
  13902. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13903. * @returns the new webGL program
  13904. */
  13905. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13906. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13907. context = context || this._gl;
  13908. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13909. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13910. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13911. };
  13912. /**
  13913. * Creates a webGL program
  13914. * @param vertexCode defines the vertex shader code to use
  13915. * @param fragmentCode defines the fragment shader code to use
  13916. * @param defines defines the string containing the defines to use to compile the shaders
  13917. * @param context defines the webGL context to use (if not set, the current one will be used)
  13918. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13919. * @returns the new webGL program
  13920. */
  13921. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13922. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13923. context = context || this._gl;
  13924. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13925. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13926. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13927. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13928. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13929. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13930. return program;
  13931. };
  13932. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13933. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13934. var shaderProgram = context.createProgram();
  13935. if (!shaderProgram) {
  13936. throw new Error("Unable to create program");
  13937. }
  13938. context.attachShader(shaderProgram, vertexShader);
  13939. context.attachShader(shaderProgram, fragmentShader);
  13940. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13941. var transformFeedback = this.createTransformFeedback();
  13942. this.bindTransformFeedback(transformFeedback);
  13943. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13944. shaderProgram.transformFeedback = transformFeedback;
  13945. }
  13946. context.linkProgram(shaderProgram);
  13947. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13948. this.bindTransformFeedback(null);
  13949. }
  13950. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13951. if (!linked) {
  13952. context.validateProgram(shaderProgram);
  13953. var error = context.getProgramInfoLog(shaderProgram);
  13954. if (error) {
  13955. throw new Error(error);
  13956. }
  13957. }
  13958. context.deleteShader(vertexShader);
  13959. context.deleteShader(fragmentShader);
  13960. return shaderProgram;
  13961. };
  13962. /**
  13963. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13964. * @param shaderProgram defines the webGL program to use
  13965. * @param uniformsNames defines the list of uniform names
  13966. * @returns an array of webGL uniform locations
  13967. */
  13968. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13969. var results = new Array();
  13970. for (var index = 0; index < uniformsNames.length; index++) {
  13971. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13972. }
  13973. return results;
  13974. };
  13975. /**
  13976. * Gets the lsit of active attributes for a given webGL program
  13977. * @param shaderProgram defines the webGL program to use
  13978. * @param attributesNames defines the list of attribute names to get
  13979. * @returns an array of indices indicating the offset of each attribute
  13980. */
  13981. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13982. var results = [];
  13983. for (var index = 0; index < attributesNames.length; index++) {
  13984. try {
  13985. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13986. }
  13987. catch (e) {
  13988. results.push(-1);
  13989. }
  13990. }
  13991. return results;
  13992. };
  13993. /**
  13994. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13995. * @param effect defines the effect to activate
  13996. */
  13997. Engine.prototype.enableEffect = function (effect) {
  13998. if (!effect) {
  13999. return;
  14000. }
  14001. // Use program
  14002. this.bindSamplers(effect);
  14003. this._currentEffect = effect;
  14004. if (effect.onBind) {
  14005. effect.onBind(effect);
  14006. }
  14007. effect.onBindObservable.notifyObservers(effect);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to an array of int32
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param array defines the array of int32 to store
  14013. */
  14014. Engine.prototype.setIntArray = function (uniform, array) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniform1iv(uniform, array);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to an array of int32 (stored as vec2)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param array defines the array of int32 to store
  14023. */
  14024. Engine.prototype.setIntArray2 = function (uniform, array) {
  14025. if (!uniform || array.length % 2 !== 0)
  14026. return;
  14027. this._gl.uniform2iv(uniform, array);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of int32 (stored as vec3)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of int32 to store
  14033. */
  14034. Engine.prototype.setIntArray3 = function (uniform, array) {
  14035. if (!uniform || array.length % 3 !== 0)
  14036. return;
  14037. this._gl.uniform3iv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of int32 (stored as vec4)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of int32 to store
  14043. */
  14044. Engine.prototype.setIntArray4 = function (uniform, array) {
  14045. if (!uniform || array.length % 4 !== 0)
  14046. return;
  14047. this._gl.uniform4iv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of float32
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of float32 to store
  14053. */
  14054. Engine.prototype.setFloatArray = function (uniform, array) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniform1fv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of float32 (stored as vec2)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of float32 to store
  14063. */
  14064. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14065. if (!uniform || array.length % 2 !== 0)
  14066. return;
  14067. this._gl.uniform2fv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of float32 (stored as vec3)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of float32 to store
  14073. */
  14074. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14075. if (!uniform || array.length % 3 !== 0)
  14076. return;
  14077. this._gl.uniform3fv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of float32 (stored as vec4)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of float32 to store
  14083. */
  14084. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14085. if (!uniform || array.length % 4 !== 0)
  14086. return;
  14087. this._gl.uniform4fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of number
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of number to store
  14093. */
  14094. Engine.prototype.setArray = function (uniform, array) {
  14095. if (!uniform)
  14096. return;
  14097. this._gl.uniform1fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of number (stored as vec2)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of number to store
  14103. */
  14104. Engine.prototype.setArray2 = function (uniform, array) {
  14105. if (!uniform || array.length % 2 !== 0)
  14106. return;
  14107. this._gl.uniform2fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of number (stored as vec3)
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of number to store
  14113. */
  14114. Engine.prototype.setArray3 = function (uniform, array) {
  14115. if (!uniform || array.length % 3 !== 0)
  14116. return;
  14117. this._gl.uniform3fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of number (stored as vec4)
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param array defines the array of number to store
  14123. */
  14124. Engine.prototype.setArray4 = function (uniform, array) {
  14125. if (!uniform || array.length % 4 !== 0)
  14126. return;
  14127. this._gl.uniform4fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of float32 (stored as matrices)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param matrices defines the array of float32 to store
  14133. */
  14134. Engine.prototype.setMatrices = function (uniform, matrices) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a matrix
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param matrix defines the matrix to store
  14143. */
  14144. Engine.prototype.setMatrix = function (uniform, matrix) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a matrix (3x3)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14153. */
  14154. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a matrix (2x2)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14163. */
  14164. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a number (int)
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param value defines the int number to store
  14173. */
  14174. Engine.prototype.setInt = function (uniform, value) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniform1i(uniform, value);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a number (float)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param value defines the float number to store
  14183. */
  14184. Engine.prototype.setFloat = function (uniform, value) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform1f(uniform, value);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a vec2
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param x defines the 1st component of the value
  14193. * @param y defines the 2nd component of the value
  14194. */
  14195. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform2f(uniform, x, y);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to a vec3
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param x defines the 1st component of the value
  14204. * @param y defines the 2nd component of the value
  14205. * @param z defines the 3rd component of the value
  14206. */
  14207. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14208. if (!uniform)
  14209. return;
  14210. this._gl.uniform3f(uniform, x, y, z);
  14211. };
  14212. /**
  14213. * Set the value of an uniform to a boolean
  14214. * @param uniform defines the webGL uniform location where to store the value
  14215. * @param bool defines the boolean to store
  14216. */
  14217. Engine.prototype.setBool = function (uniform, bool) {
  14218. if (!uniform)
  14219. return;
  14220. this._gl.uniform1i(uniform, bool);
  14221. };
  14222. /**
  14223. * Set the value of an uniform to a vec4
  14224. * @param uniform defines the webGL uniform location where to store the value
  14225. * @param x defines the 1st component of the value
  14226. * @param y defines the 2nd component of the value
  14227. * @param z defines the 3rd component of the value
  14228. * @param w defines the 4th component of the value
  14229. */
  14230. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14231. if (!uniform)
  14232. return;
  14233. this._gl.uniform4f(uniform, x, y, z, w);
  14234. };
  14235. /**
  14236. * Set the value of an uniform to a Color3
  14237. * @param uniform defines the webGL uniform location where to store the value
  14238. * @param color3 defines the color to store
  14239. */
  14240. Engine.prototype.setColor3 = function (uniform, color3) {
  14241. if (!uniform)
  14242. return;
  14243. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14244. };
  14245. /**
  14246. * Set the value of an uniform to a Color3 and an alpha value
  14247. * @param uniform defines the webGL uniform location where to store the value
  14248. * @param color3 defines the color to store
  14249. * @param alpha defines the alpha component to store
  14250. */
  14251. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14252. if (!uniform)
  14253. return;
  14254. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14255. };
  14256. /**
  14257. * Sets a Color4 on a uniform variable
  14258. * @param uniform defines the uniform location
  14259. * @param color4 defines the value to be set
  14260. */
  14261. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14262. if (!uniform)
  14263. return;
  14264. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14265. };
  14266. // States
  14267. /**
  14268. * Set various states to the webGL context
  14269. * @param culling defines backface culling state
  14270. * @param zOffset defines the value to apply to zOffset (0 by default)
  14271. * @param force defines if states must be applied even if cache is up to date
  14272. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14273. */
  14274. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14275. if (zOffset === void 0) { zOffset = 0; }
  14276. if (reverseSide === void 0) { reverseSide = false; }
  14277. // Culling
  14278. if (this._depthCullingState.cull !== culling || force) {
  14279. this._depthCullingState.cull = culling;
  14280. }
  14281. // Cull face
  14282. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14283. if (this._depthCullingState.cullFace !== cullFace || force) {
  14284. this._depthCullingState.cullFace = cullFace;
  14285. }
  14286. // Z offset
  14287. this.setZOffset(zOffset);
  14288. // Front face
  14289. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14290. if (this._depthCullingState.frontFace !== frontFace || force) {
  14291. this._depthCullingState.frontFace = frontFace;
  14292. }
  14293. };
  14294. /**
  14295. * Set the z offset to apply to current rendering
  14296. * @param value defines the offset to apply
  14297. */
  14298. Engine.prototype.setZOffset = function (value) {
  14299. this._depthCullingState.zOffset = value;
  14300. };
  14301. /**
  14302. * Gets the current value of the zOffset
  14303. * @returns the current zOffset state
  14304. */
  14305. Engine.prototype.getZOffset = function () {
  14306. return this._depthCullingState.zOffset;
  14307. };
  14308. /**
  14309. * Enable or disable depth buffering
  14310. * @param enable defines the state to set
  14311. */
  14312. Engine.prototype.setDepthBuffer = function (enable) {
  14313. this._depthCullingState.depthTest = enable;
  14314. };
  14315. /**
  14316. * Gets a boolean indicating if depth writing is enabled
  14317. * @returns the current depth writing state
  14318. */
  14319. Engine.prototype.getDepthWrite = function () {
  14320. return this._depthCullingState.depthMask;
  14321. };
  14322. /**
  14323. * Enable or disable depth writing
  14324. * @param enable defines the state to set
  14325. */
  14326. Engine.prototype.setDepthWrite = function (enable) {
  14327. this._depthCullingState.depthMask = enable;
  14328. };
  14329. /**
  14330. * Enable or disable color writing
  14331. * @param enable defines the state to set
  14332. */
  14333. Engine.prototype.setColorWrite = function (enable) {
  14334. this._gl.colorMask(enable, enable, enable, enable);
  14335. this._colorWrite = enable;
  14336. };
  14337. /**
  14338. * Gets a boolean indicating if color writing is enabled
  14339. * @returns the current color writing state
  14340. */
  14341. Engine.prototype.getColorWrite = function () {
  14342. return this._colorWrite;
  14343. };
  14344. /**
  14345. * Sets alpha constants used by some alpha blending modes
  14346. * @param r defines the red component
  14347. * @param g defines the green component
  14348. * @param b defines the blue component
  14349. * @param a defines the alpha component
  14350. */
  14351. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14352. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14353. };
  14354. /**
  14355. * Sets the current alpha mode
  14356. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14357. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14358. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14359. */
  14360. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14361. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14362. if (this._alphaMode === mode) {
  14363. return;
  14364. }
  14365. switch (mode) {
  14366. case Engine.ALPHA_DISABLE:
  14367. this._alphaState.alphaBlend = false;
  14368. break;
  14369. case Engine.ALPHA_PREMULTIPLIED:
  14370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14371. this._alphaState.alphaBlend = true;
  14372. break;
  14373. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14375. this._alphaState.alphaBlend = true;
  14376. break;
  14377. case Engine.ALPHA_COMBINE:
  14378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14379. this._alphaState.alphaBlend = true;
  14380. break;
  14381. case Engine.ALPHA_ONEONE:
  14382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14383. this._alphaState.alphaBlend = true;
  14384. break;
  14385. case Engine.ALPHA_ADD:
  14386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14387. this._alphaState.alphaBlend = true;
  14388. break;
  14389. case Engine.ALPHA_SUBTRACT:
  14390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14391. this._alphaState.alphaBlend = true;
  14392. break;
  14393. case Engine.ALPHA_MULTIPLY:
  14394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14395. this._alphaState.alphaBlend = true;
  14396. break;
  14397. case Engine.ALPHA_MAXIMIZED:
  14398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14399. this._alphaState.alphaBlend = true;
  14400. break;
  14401. case Engine.ALPHA_INTERPOLATE:
  14402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14403. this._alphaState.alphaBlend = true;
  14404. break;
  14405. case Engine.ALPHA_SCREENMODE:
  14406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14407. this._alphaState.alphaBlend = true;
  14408. break;
  14409. }
  14410. if (!noDepthWriteChange) {
  14411. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14412. }
  14413. this._alphaMode = mode;
  14414. };
  14415. /**
  14416. * Gets the current alpha mode
  14417. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14418. * @returns the current alpha mode
  14419. */
  14420. Engine.prototype.getAlphaMode = function () {
  14421. return this._alphaMode;
  14422. };
  14423. // Textures
  14424. /**
  14425. * Force the entire cache to be cleared
  14426. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14427. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14428. */
  14429. Engine.prototype.wipeCaches = function (bruteForce) {
  14430. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14431. return;
  14432. }
  14433. this._currentEffect = null;
  14434. if (bruteForce) {
  14435. this.resetTextureCache();
  14436. this._currentProgram = null;
  14437. this._stencilState.reset();
  14438. this._depthCullingState.reset();
  14439. this.setDepthFunctionToLessOrEqual();
  14440. this._alphaState.reset();
  14441. }
  14442. this._resetVertexBufferBinding();
  14443. this._cachedIndexBuffer = null;
  14444. this._cachedEffectForVertexBuffers = null;
  14445. this._unbindVertexArrayObject();
  14446. this.bindIndexBuffer(null);
  14447. };
  14448. /**
  14449. * Set the compressed texture format to use, based on the formats you have, and the formats
  14450. * supported by the hardware / browser.
  14451. *
  14452. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14453. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14454. * to API arguments needed to compressed textures. This puts the burden on the container
  14455. * generator to house the arcane code for determining these for current & future formats.
  14456. *
  14457. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14458. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14459. *
  14460. * Note: The result of this call is not taken into account when a texture is base64.
  14461. *
  14462. * @param formatsAvailable defines the list of those format families you have created
  14463. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14464. *
  14465. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14466. * @returns The extension selected.
  14467. */
  14468. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14469. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14470. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14471. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14472. return this._textureFormatInUse = this._texturesSupported[i];
  14473. }
  14474. }
  14475. }
  14476. // actively set format to nothing, to allow this to be called more than once
  14477. // and possibly fail the 2nd time
  14478. this._textureFormatInUse = null;
  14479. return null;
  14480. };
  14481. /** @hidden */
  14482. Engine.prototype._createTexture = function () {
  14483. var texture = this._gl.createTexture();
  14484. if (!texture) {
  14485. throw new Error("Unable to create texture");
  14486. }
  14487. return texture;
  14488. };
  14489. /**
  14490. * Usually called from BABYLON.Texture.ts.
  14491. * Passed information to create a WebGLTexture
  14492. * @param urlArg defines a value which contains one of the following:
  14493. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14494. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14495. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14496. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14497. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14498. * @param scene needed for loading to the correct scene
  14499. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14500. * @param onLoad optional callback to be called upon successful completion
  14501. * @param onError optional callback to be called upon failure
  14502. * @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
  14503. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14504. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14505. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14506. */
  14507. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14508. var _this = this;
  14509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14510. if (onLoad === void 0) { onLoad = null; }
  14511. if (onError === void 0) { onError = null; }
  14512. if (buffer === void 0) { buffer = null; }
  14513. if (fallback === void 0) { fallback = null; }
  14514. if (format === void 0) { format = null; }
  14515. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14516. var fromData = url.substr(0, 5) === "data:";
  14517. var fromBlob = url.substr(0, 5) === "blob:";
  14518. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14519. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14520. // establish the file extension, if possible
  14521. var lastDot = url.lastIndexOf('.');
  14522. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14523. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14524. var isTGA = (extension.indexOf(".tga") === 0);
  14525. // determine if a ktx file should be substituted
  14526. var isKTX = false;
  14527. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14528. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14529. isKTX = true;
  14530. }
  14531. if (scene) {
  14532. scene._addPendingData(texture);
  14533. }
  14534. texture.url = url;
  14535. texture.generateMipMaps = !noMipmap;
  14536. texture.samplingMode = samplingMode;
  14537. texture.invertY = invertY;
  14538. if (!this._doNotHandleContextLost) {
  14539. // Keep a link to the buffer only if we plan to handle context lost
  14540. texture._buffer = buffer;
  14541. }
  14542. var onLoadObserver = null;
  14543. if (onLoad && !fallback) {
  14544. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14545. }
  14546. if (!fallback)
  14547. this._internalTexturesCache.push(texture);
  14548. var onerror = function (message, exception) {
  14549. if (scene) {
  14550. scene._removePendingData(texture);
  14551. }
  14552. if (onLoadObserver) {
  14553. texture.onLoadedObservable.remove(onLoadObserver);
  14554. }
  14555. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14556. if (isKTX) {
  14557. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14558. }
  14559. else if (BABYLON.Tools.UseFallbackTexture) {
  14560. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14561. }
  14562. if (onError) {
  14563. onError(message || "Unknown error", exception);
  14564. }
  14565. };
  14566. var callback = null;
  14567. // processing for non-image formats
  14568. if (isKTX || isTGA || isDDS) {
  14569. if (isKTX) {
  14570. callback = function (data) {
  14571. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14572. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14573. ktx.uploadLevels(_this._gl, !noMipmap);
  14574. return false;
  14575. }, samplingMode);
  14576. };
  14577. }
  14578. else if (isTGA) {
  14579. callback = function (arrayBuffer) {
  14580. var data = new Uint8Array(arrayBuffer);
  14581. var header = BABYLON.TGATools.GetTGAHeader(data);
  14582. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14583. BABYLON.TGATools.UploadContent(_this._gl, data);
  14584. return false;
  14585. }, samplingMode);
  14586. };
  14587. }
  14588. else if (isDDS) {
  14589. callback = function (data) {
  14590. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14591. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14592. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14593. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14594. return false;
  14595. }, samplingMode);
  14596. };
  14597. }
  14598. if (!buffer) {
  14599. this._loadFile(url, function (data) {
  14600. if (callback) {
  14601. callback(data);
  14602. }
  14603. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14604. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14605. });
  14606. }
  14607. else {
  14608. if (callback) {
  14609. callback(buffer);
  14610. }
  14611. }
  14612. // image format processing
  14613. }
  14614. else {
  14615. var onload = function (img) {
  14616. if (fromBlob && !_this._doNotHandleContextLost) {
  14617. // We need to store the image if we need to rebuild the texture
  14618. // in case of a webgl context lost
  14619. texture._buffer = img;
  14620. }
  14621. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14622. var gl = _this._gl;
  14623. var isPot = (img.width === potWidth && img.height === potHeight);
  14624. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14625. if (isPot) {
  14626. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14627. return false;
  14628. }
  14629. // Using shaders to rescale because canvas.drawImage is lossy
  14630. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14631. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14632. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14637. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14638. _this._releaseTexture(source);
  14639. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14640. continuationCallback();
  14641. });
  14642. return true;
  14643. }, samplingMode);
  14644. };
  14645. if (!fromData || isBase64) {
  14646. if (buffer instanceof HTMLImageElement) {
  14647. onload(buffer);
  14648. }
  14649. else {
  14650. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14651. }
  14652. }
  14653. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14654. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14655. }
  14656. else {
  14657. onload(buffer);
  14658. }
  14659. }
  14660. return texture;
  14661. };
  14662. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14663. var _this = this;
  14664. var rtt = this.createRenderTargetTexture({
  14665. width: destination.width,
  14666. height: destination.height,
  14667. }, {
  14668. generateMipMaps: false,
  14669. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14670. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14671. generateDepthBuffer: false,
  14672. generateStencilBuffer: false
  14673. });
  14674. if (!this._rescalePostProcess) {
  14675. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14676. }
  14677. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14678. _this._rescalePostProcess.onApply = function (effect) {
  14679. effect._bindTexture("textureSampler", source);
  14680. };
  14681. var hostingScene = scene;
  14682. if (!hostingScene) {
  14683. hostingScene = _this.scenes[_this.scenes.length - 1];
  14684. }
  14685. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14686. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14687. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14688. _this.unBindFramebuffer(rtt);
  14689. _this._releaseTexture(rtt);
  14690. if (onComplete) {
  14691. onComplete();
  14692. }
  14693. });
  14694. };
  14695. /**
  14696. * Update a raw texture
  14697. * @param texture defines the texture to update
  14698. * @param data defines the data to store in the texture
  14699. * @param format defines the format of the data
  14700. * @param invertY defines if data must be stored with Y axis inverted
  14701. * @param compression defines the compression used (null by default)
  14702. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14703. */
  14704. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14705. if (compression === void 0) { compression = null; }
  14706. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14707. if (!texture) {
  14708. return;
  14709. }
  14710. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14711. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14712. // babylon's internalFormat but gl's texImage2D format
  14713. var internalFormat = this._getInternalFormat(format);
  14714. var textureType = this._getWebGLTextureType(type);
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14716. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14717. if (!this._doNotHandleContextLost) {
  14718. texture._bufferView = data;
  14719. texture.format = format;
  14720. texture.type = type;
  14721. texture.invertY = invertY;
  14722. texture._compression = compression;
  14723. }
  14724. if (texture.width % 4 !== 0) {
  14725. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14726. }
  14727. if (compression && data) {
  14728. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14729. }
  14730. else {
  14731. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14732. }
  14733. if (texture.generateMipMaps) {
  14734. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14735. }
  14736. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14737. // this.resetTextureCache();
  14738. texture.isReady = true;
  14739. };
  14740. /**
  14741. * Creates a raw texture
  14742. * @param data defines the data to store in the texture
  14743. * @param width defines the width of the texture
  14744. * @param height defines the height of the texture
  14745. * @param format defines the format of the data
  14746. * @param generateMipMaps defines if the engine should generate the mip levels
  14747. * @param invertY defines if data must be stored with Y axis inverted
  14748. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14749. * @param compression defines the compression used (null by default)
  14750. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14751. * @returns the raw texture inside an InternalTexture
  14752. */
  14753. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14754. if (compression === void 0) { compression = null; }
  14755. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14756. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14757. texture.baseWidth = width;
  14758. texture.baseHeight = height;
  14759. texture.width = width;
  14760. texture.height = height;
  14761. texture.format = format;
  14762. texture.generateMipMaps = generateMipMaps;
  14763. texture.samplingMode = samplingMode;
  14764. texture.invertY = invertY;
  14765. texture._compression = compression;
  14766. texture.type = type;
  14767. if (!this._doNotHandleContextLost) {
  14768. texture._bufferView = data;
  14769. }
  14770. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14771. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14772. // Filters
  14773. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14775. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14776. if (generateMipMaps) {
  14777. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14778. }
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14780. this._internalTexturesCache.push(texture);
  14781. return texture;
  14782. };
  14783. /**
  14784. * Creates a dynamic texture
  14785. * @param width defines the width of the texture
  14786. * @param height defines the height of the texture
  14787. * @param generateMipMaps defines if the engine should generate the mip levels
  14788. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14789. * @returns the dynamic texture inside an InternalTexture
  14790. */
  14791. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14792. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14793. texture.baseWidth = width;
  14794. texture.baseHeight = height;
  14795. if (generateMipMaps) {
  14796. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14797. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14798. }
  14799. // this.resetTextureCache();
  14800. texture.width = width;
  14801. texture.height = height;
  14802. texture.isReady = false;
  14803. texture.generateMipMaps = generateMipMaps;
  14804. texture.samplingMode = samplingMode;
  14805. this.updateTextureSamplingMode(samplingMode, texture);
  14806. this._internalTexturesCache.push(texture);
  14807. return texture;
  14808. };
  14809. /**
  14810. * Update the sampling mode of a given texture
  14811. * @param samplingMode defines the required sampling mode
  14812. * @param texture defines the texture to update
  14813. */
  14814. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14815. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14816. if (texture.isCube) {
  14817. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14818. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14819. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14820. }
  14821. else if (texture.is3D) {
  14822. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14823. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14824. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14825. }
  14826. else {
  14827. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14828. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14830. }
  14831. texture.samplingMode = samplingMode;
  14832. };
  14833. /**
  14834. * Update the content of a dynamic texture
  14835. * @param texture defines the texture to update
  14836. * @param canvas defines the canvas containing the source
  14837. * @param invertY defines if data must be stored with Y axis inverted
  14838. * @param premulAlpha defines if alpha is stored as premultiplied
  14839. * @param format defines the format of the data
  14840. */
  14841. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14842. if (premulAlpha === void 0) { premulAlpha = false; }
  14843. if (!texture) {
  14844. return;
  14845. }
  14846. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14847. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14848. if (premulAlpha) {
  14849. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14850. }
  14851. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14852. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14853. if (texture.generateMipMaps) {
  14854. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14855. }
  14856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14857. if (premulAlpha) {
  14858. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14859. }
  14860. texture.isReady = true;
  14861. };
  14862. /**
  14863. * Update a video texture
  14864. * @param texture defines the texture to update
  14865. * @param video defines the video element to use
  14866. * @param invertY defines if data must be stored with Y axis inverted
  14867. */
  14868. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14869. if (!texture || texture._isDisabled) {
  14870. return;
  14871. }
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14873. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14874. try {
  14875. // Testing video texture support
  14876. if (this._videoTextureSupported === undefined) {
  14877. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14878. if (this._gl.getError() !== 0) {
  14879. this._videoTextureSupported = false;
  14880. }
  14881. else {
  14882. this._videoTextureSupported = true;
  14883. }
  14884. }
  14885. // Copy video through the current working canvas if video texture is not supported
  14886. if (!this._videoTextureSupported) {
  14887. if (!texture._workingCanvas) {
  14888. texture._workingCanvas = document.createElement("canvas");
  14889. var context = texture._workingCanvas.getContext("2d");
  14890. if (!context) {
  14891. throw new Error("Unable to get 2d context");
  14892. }
  14893. texture._workingContext = context;
  14894. texture._workingCanvas.width = texture.width;
  14895. texture._workingCanvas.height = texture.height;
  14896. }
  14897. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14898. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14899. }
  14900. else {
  14901. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14902. }
  14903. if (texture.generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14907. // this.resetTextureCache();
  14908. texture.isReady = true;
  14909. }
  14910. catch (ex) {
  14911. // Something unexpected
  14912. // Let's disable the texture
  14913. texture._isDisabled = true;
  14914. }
  14915. };
  14916. /**
  14917. * Updates a depth texture Comparison Mode and Function.
  14918. * If the comparison Function is equal to 0, the mode will be set to none.
  14919. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14920. * @param texture The texture to set the comparison function for
  14921. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14922. */
  14923. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14924. if (this.webGLVersion === 1) {
  14925. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14926. return;
  14927. }
  14928. var gl = this._gl;
  14929. if (texture.isCube) {
  14930. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14931. if (comparisonFunction === 0) {
  14932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14934. }
  14935. else {
  14936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14938. }
  14939. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14940. }
  14941. else {
  14942. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14943. if (comparisonFunction === 0) {
  14944. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14945. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14946. }
  14947. else {
  14948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14950. }
  14951. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14952. }
  14953. texture._comparisonFunction = comparisonFunction;
  14954. };
  14955. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14956. var width = size.width || size;
  14957. var height = size.height || size;
  14958. internalTexture.baseWidth = width;
  14959. internalTexture.baseHeight = height;
  14960. internalTexture.width = width;
  14961. internalTexture.height = height;
  14962. internalTexture.isReady = true;
  14963. internalTexture.samples = 1;
  14964. internalTexture.generateMipMaps = false;
  14965. internalTexture._generateDepthBuffer = true;
  14966. internalTexture._generateStencilBuffer = generateStencil;
  14967. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14968. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14969. internalTexture._comparisonFunction = comparisonFunction;
  14970. var gl = this._gl;
  14971. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14972. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14973. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14974. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14975. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14976. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14977. if (comparisonFunction === 0) {
  14978. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14979. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14980. }
  14981. else {
  14982. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14983. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14984. }
  14985. };
  14986. /**
  14987. * Creates a depth stencil texture.
  14988. * This is only available in WebGL 2 or with the depth texture extension available.
  14989. * @param size The size of face edge in the texture.
  14990. * @param options The options defining the texture.
  14991. * @returns The texture
  14992. */
  14993. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14994. if (options.isCube) {
  14995. var width = size.width || size;
  14996. return this._createDepthStencilCubeTexture(width, options);
  14997. }
  14998. else {
  14999. return this._createDepthStencilTexture(size, options);
  15000. }
  15001. };
  15002. /**
  15003. * Creates a depth stencil texture.
  15004. * This is only available in WebGL 2 or with the depth texture extension available.
  15005. * @param size The size of face edge in the texture.
  15006. * @param options The options defining the texture.
  15007. * @returns The texture
  15008. */
  15009. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15010. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15011. if (!this._caps.depthTextureExtension) {
  15012. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15013. return internalTexture;
  15014. }
  15015. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15016. var gl = this._gl;
  15017. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15018. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15019. if (this.webGLVersion > 1) {
  15020. if (internalOptions.generateStencil) {
  15021. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15022. }
  15023. else {
  15024. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15025. }
  15026. }
  15027. else {
  15028. if (internalOptions.generateStencil) {
  15029. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15030. }
  15031. else {
  15032. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15033. }
  15034. }
  15035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15036. return internalTexture;
  15037. };
  15038. /**
  15039. * Creates a depth stencil cube texture.
  15040. * This is only available in WebGL 2.
  15041. * @param size The size of face edge in the cube texture.
  15042. * @param options The options defining the cube texture.
  15043. * @returns The cube texture
  15044. */
  15045. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15046. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15047. internalTexture.isCube = true;
  15048. if (this.webGLVersion === 1) {
  15049. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15050. return internalTexture;
  15051. }
  15052. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15053. var gl = this._gl;
  15054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15055. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15056. // Create the depth/stencil buffer
  15057. for (var face = 0; face < 6; face++) {
  15058. if (internalOptions.generateStencil) {
  15059. 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);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15070. * @param renderTarget The render target to set the frame buffer for
  15071. */
  15072. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15073. // Create the framebuffer
  15074. var internalTexture = renderTarget.getInternalTexture();
  15075. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15076. return;
  15077. }
  15078. var gl = this._gl;
  15079. var depthStencilTexture = renderTarget.depthStencilTexture;
  15080. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15081. if (depthStencilTexture.isCube) {
  15082. if (depthStencilTexture._generateStencilBuffer) {
  15083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15084. }
  15085. else {
  15086. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15087. }
  15088. }
  15089. else {
  15090. if (depthStencilTexture._generateStencilBuffer) {
  15091. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15092. }
  15093. else {
  15094. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15095. }
  15096. }
  15097. this.bindUnboundFramebuffer(null);
  15098. };
  15099. /**
  15100. * Creates a new render target texture
  15101. * @param size defines the size of the texture
  15102. * @param options defines the options used to create the texture
  15103. * @returns a new render target texture stored in an InternalTexture
  15104. */
  15105. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15106. var fullOptions = new RenderTargetCreationOptions();
  15107. if (options !== undefined && typeof options === "object") {
  15108. fullOptions.generateMipMaps = options.generateMipMaps;
  15109. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15110. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15111. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15112. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15113. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15114. }
  15115. else {
  15116. fullOptions.generateMipMaps = options;
  15117. fullOptions.generateDepthBuffer = true;
  15118. fullOptions.generateStencilBuffer = false;
  15119. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15120. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15121. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15122. }
  15123. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15124. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15125. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15126. }
  15127. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15128. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15129. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15130. }
  15131. var gl = this._gl;
  15132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15133. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15134. var width = size.width || size;
  15135. var height = size.height || size;
  15136. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15137. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15139. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15140. }
  15141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15145. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15146. // Create the framebuffer
  15147. var currentFrameBuffer = this._currentFramebuffer;
  15148. var framebuffer = gl.createFramebuffer();
  15149. this.bindUnboundFramebuffer(framebuffer);
  15150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15151. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15152. if (fullOptions.generateMipMaps) {
  15153. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15154. }
  15155. // Unbind
  15156. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15157. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15158. this.bindUnboundFramebuffer(currentFrameBuffer);
  15159. texture._framebuffer = framebuffer;
  15160. texture.baseWidth = width;
  15161. texture.baseHeight = height;
  15162. texture.width = width;
  15163. texture.height = height;
  15164. texture.isReady = true;
  15165. texture.samples = 1;
  15166. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15167. texture.samplingMode = fullOptions.samplingMode;
  15168. texture.type = fullOptions.type;
  15169. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15170. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15171. // this.resetTextureCache();
  15172. this._internalTexturesCache.push(texture);
  15173. return texture;
  15174. };
  15175. /**
  15176. * Create a multi render target texture
  15177. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15178. * @param size defines the size of the texture
  15179. * @param options defines the creation options
  15180. * @returns the cube texture as an InternalTexture
  15181. */
  15182. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15183. var generateMipMaps = false;
  15184. var generateDepthBuffer = true;
  15185. var generateStencilBuffer = false;
  15186. var generateDepthTexture = false;
  15187. var textureCount = 1;
  15188. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15189. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15190. var types = new Array();
  15191. var samplingModes = new Array();
  15192. if (options !== undefined) {
  15193. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15194. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15195. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15196. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15197. textureCount = options.textureCount || 1;
  15198. if (options.types) {
  15199. types = options.types;
  15200. }
  15201. if (options.samplingModes) {
  15202. samplingModes = options.samplingModes;
  15203. }
  15204. }
  15205. var gl = this._gl;
  15206. // Create the framebuffer
  15207. var framebuffer = gl.createFramebuffer();
  15208. this.bindUnboundFramebuffer(framebuffer);
  15209. var width = size.width || size;
  15210. var height = size.height || size;
  15211. var textures = [];
  15212. var attachments = [];
  15213. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15214. for (var i = 0; i < textureCount; i++) {
  15215. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15216. var type = types[i] || defaultType;
  15217. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15218. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15219. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15220. }
  15221. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15222. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15223. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15224. }
  15225. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15226. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15227. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15228. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15229. }
  15230. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15231. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15232. textures.push(texture);
  15233. attachments.push(attachment);
  15234. gl.activeTexture(gl["TEXTURE" + i]);
  15235. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15240. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15241. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15242. if (generateMipMaps) {
  15243. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15244. }
  15245. // Unbind
  15246. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15247. texture._framebuffer = framebuffer;
  15248. texture._depthStencilBuffer = depthStencilBuffer;
  15249. texture.baseWidth = width;
  15250. texture.baseHeight = height;
  15251. texture.width = width;
  15252. texture.height = height;
  15253. texture.isReady = true;
  15254. texture.samples = 1;
  15255. texture.generateMipMaps = generateMipMaps;
  15256. texture.samplingMode = samplingMode;
  15257. texture.type = type;
  15258. texture._generateDepthBuffer = generateDepthBuffer;
  15259. texture._generateStencilBuffer = generateStencilBuffer;
  15260. texture._attachments = attachments;
  15261. this._internalTexturesCache.push(texture);
  15262. }
  15263. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15264. // Depth texture
  15265. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15266. gl.activeTexture(gl.TEXTURE0);
  15267. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15272. 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);
  15273. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15274. depthTexture._framebuffer = framebuffer;
  15275. depthTexture.baseWidth = width;
  15276. depthTexture.baseHeight = height;
  15277. depthTexture.width = width;
  15278. depthTexture.height = height;
  15279. depthTexture.isReady = true;
  15280. depthTexture.samples = 1;
  15281. depthTexture.generateMipMaps = generateMipMaps;
  15282. depthTexture.samplingMode = gl.NEAREST;
  15283. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15284. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15285. textures.push(depthTexture);
  15286. this._internalTexturesCache.push(depthTexture);
  15287. }
  15288. gl.drawBuffers(attachments);
  15289. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15290. this.bindUnboundFramebuffer(null);
  15291. this.resetTextureCache();
  15292. return textures;
  15293. };
  15294. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15295. if (samples === void 0) { samples = 1; }
  15296. var depthStencilBuffer = null;
  15297. var gl = this._gl;
  15298. // Create the depth/stencil buffer
  15299. if (generateStencilBuffer) {
  15300. depthStencilBuffer = gl.createRenderbuffer();
  15301. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15302. if (samples > 1) {
  15303. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15304. }
  15305. else {
  15306. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15307. }
  15308. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15309. }
  15310. else if (generateDepthBuffer) {
  15311. depthStencilBuffer = gl.createRenderbuffer();
  15312. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15313. if (samples > 1) {
  15314. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15315. }
  15316. else {
  15317. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15318. }
  15319. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15320. }
  15321. return depthStencilBuffer;
  15322. };
  15323. /**
  15324. * Updates the sample count of a render target texture
  15325. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15326. * @param texture defines the texture to update
  15327. * @param samples defines the sample count to set
  15328. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15329. */
  15330. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15331. if (this.webGLVersion < 2 || !texture) {
  15332. return 1;
  15333. }
  15334. if (texture.samples === samples) {
  15335. return samples;
  15336. }
  15337. var gl = this._gl;
  15338. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15339. // Dispose previous render buffers
  15340. if (texture._depthStencilBuffer) {
  15341. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15342. texture._depthStencilBuffer = null;
  15343. }
  15344. if (texture._MSAAFramebuffer) {
  15345. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15346. texture._MSAAFramebuffer = null;
  15347. }
  15348. if (texture._MSAARenderBuffer) {
  15349. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15350. texture._MSAARenderBuffer = null;
  15351. }
  15352. if (samples > 1) {
  15353. var framebuffer = gl.createFramebuffer();
  15354. if (!framebuffer) {
  15355. throw new Error("Unable to create multi sampled framebuffer");
  15356. }
  15357. texture._MSAAFramebuffer = framebuffer;
  15358. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15359. var colorRenderbuffer = gl.createRenderbuffer();
  15360. if (!colorRenderbuffer) {
  15361. throw new Error("Unable to create multi sampled framebuffer");
  15362. }
  15363. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15364. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15365. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15366. texture._MSAARenderBuffer = colorRenderbuffer;
  15367. }
  15368. else {
  15369. this.bindUnboundFramebuffer(texture._framebuffer);
  15370. }
  15371. texture.samples = samples;
  15372. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15373. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15374. this.bindUnboundFramebuffer(null);
  15375. return samples;
  15376. };
  15377. /**
  15378. * Update the sample count for a given multiple render target texture
  15379. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15380. * @param textures defines the textures to update
  15381. * @param samples defines the sample count to set
  15382. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15383. */
  15384. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15385. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15386. return 1;
  15387. }
  15388. if (textures[0].samples === samples) {
  15389. return samples;
  15390. }
  15391. var gl = this._gl;
  15392. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15393. // Dispose previous render buffers
  15394. if (textures[0]._depthStencilBuffer) {
  15395. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15396. textures[0]._depthStencilBuffer = null;
  15397. }
  15398. if (textures[0]._MSAAFramebuffer) {
  15399. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15400. textures[0]._MSAAFramebuffer = null;
  15401. }
  15402. for (var i = 0; i < textures.length; i++) {
  15403. if (textures[i]._MSAARenderBuffer) {
  15404. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15405. textures[i]._MSAARenderBuffer = null;
  15406. }
  15407. }
  15408. if (samples > 1) {
  15409. var framebuffer = gl.createFramebuffer();
  15410. if (!framebuffer) {
  15411. throw new Error("Unable to create multi sampled framebuffer");
  15412. }
  15413. this.bindUnboundFramebuffer(framebuffer);
  15414. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15415. var attachments = [];
  15416. for (var i = 0; i < textures.length; i++) {
  15417. var texture = textures[i];
  15418. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15419. var colorRenderbuffer = gl.createRenderbuffer();
  15420. if (!colorRenderbuffer) {
  15421. throw new Error("Unable to create multi sampled framebuffer");
  15422. }
  15423. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15426. texture._MSAAFramebuffer = framebuffer;
  15427. texture._MSAARenderBuffer = colorRenderbuffer;
  15428. texture.samples = samples;
  15429. texture._depthStencilBuffer = depthStencilBuffer;
  15430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15431. attachments.push(attachment);
  15432. }
  15433. gl.drawBuffers(attachments);
  15434. }
  15435. else {
  15436. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15437. }
  15438. this.bindUnboundFramebuffer(null);
  15439. return samples;
  15440. };
  15441. /** @hidden */
  15442. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15443. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15444. };
  15445. /** @hidden */
  15446. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15447. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15448. };
  15449. /**
  15450. * Creates a new render target cube texture
  15451. * @param size defines the size of the texture
  15452. * @param options defines the options used to create the texture
  15453. * @returns a new render target cube texture stored in an InternalTexture
  15454. */
  15455. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15456. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15457. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15458. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15459. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15460. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15461. }
  15462. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15463. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15464. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15465. }
  15466. var gl = this._gl;
  15467. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15468. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15469. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15470. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15471. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15472. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15473. }
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15478. for (var face = 0; face < 6; face++) {
  15479. 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);
  15480. }
  15481. // Create the framebuffer
  15482. var framebuffer = gl.createFramebuffer();
  15483. this.bindUnboundFramebuffer(framebuffer);
  15484. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15485. // MipMaps
  15486. if (fullOptions.generateMipMaps) {
  15487. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15488. }
  15489. // Unbind
  15490. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15491. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15492. this.bindUnboundFramebuffer(null);
  15493. texture._framebuffer = framebuffer;
  15494. texture.width = size;
  15495. texture.height = size;
  15496. texture.isReady = true;
  15497. texture.isCube = true;
  15498. texture.samples = 1;
  15499. texture.generateMipMaps = fullOptions.generateMipMaps;
  15500. texture.samplingMode = fullOptions.samplingMode;
  15501. texture.type = fullOptions.type;
  15502. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15503. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15504. this._internalTexturesCache.push(texture);
  15505. return texture;
  15506. };
  15507. /**
  15508. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15509. * @param rootUrl defines the url where the file to load is located
  15510. * @param scene defines the current scene
  15511. * @param scale defines scale to apply to the mip map selection
  15512. * @param offset defines offset to apply to the mip map selection
  15513. * @param onLoad defines an optional callback raised when the texture is loaded
  15514. * @param onError defines an optional callback raised if there is an issue to load the texture
  15515. * @param format defines the format of the data
  15516. * @param forcedExtension defines the extension to use to pick the right loader
  15517. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15518. * @returns the cube texture as an InternalTexture
  15519. */
  15520. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15521. var _this = this;
  15522. if (onLoad === void 0) { onLoad = null; }
  15523. if (onError === void 0) { onError = null; }
  15524. if (forcedExtension === void 0) { forcedExtension = null; }
  15525. if (createPolynomials === void 0) { createPolynomials = true; }
  15526. var callback = function (loadData) {
  15527. if (!loadData) {
  15528. if (onLoad) {
  15529. onLoad(null);
  15530. }
  15531. return;
  15532. }
  15533. var texture = loadData.texture;
  15534. if (!createPolynomials) {
  15535. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15536. }
  15537. else if (loadData.info.sphericalPolynomial) {
  15538. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15539. }
  15540. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15541. texture._lodGenerationScale = scale;
  15542. texture._lodGenerationOffset = offset;
  15543. if (_this._caps.textureLOD) {
  15544. // Do not add extra process if texture lod is supported.
  15545. if (onLoad) {
  15546. onLoad(texture);
  15547. }
  15548. return;
  15549. }
  15550. var mipSlices = 3;
  15551. var gl = _this._gl;
  15552. var width = loadData.width;
  15553. if (!width) {
  15554. return;
  15555. }
  15556. var textures = [];
  15557. for (var i = 0; i < mipSlices; i++) {
  15558. //compute LOD from even spacing in smoothness (matching shader calculation)
  15559. var smoothness = i / (mipSlices - 1);
  15560. var roughness = 1 - smoothness;
  15561. var minLODIndex = offset; // roughness = 0
  15562. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15563. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15564. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15565. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15566. glTextureFromLod.isCube = true;
  15567. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15572. if (loadData.isDDS) {
  15573. var info = loadData.info;
  15574. var data = loadData.data;
  15575. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15576. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15577. }
  15578. else {
  15579. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15580. }
  15581. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15582. // Wrap in a base texture for easy binding.
  15583. var lodTexture = new BABYLON.BaseTexture(scene);
  15584. lodTexture.isCube = true;
  15585. lodTexture._texture = glTextureFromLod;
  15586. glTextureFromLod.isReady = true;
  15587. textures.push(lodTexture);
  15588. }
  15589. texture._lodTextureHigh = textures[2];
  15590. texture._lodTextureMid = textures[1];
  15591. texture._lodTextureLow = textures[0];
  15592. if (onLoad) {
  15593. onLoad(texture);
  15594. }
  15595. };
  15596. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15597. };
  15598. /**
  15599. * Creates a cube texture
  15600. * @param rootUrl defines the url where the files to load is located
  15601. * @param scene defines the current scene
  15602. * @param files defines the list of files to load (1 per face)
  15603. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15604. * @param onLoad defines an optional callback raised when the texture is loaded
  15605. * @param onError defines an optional callback raised if there is an issue to load the texture
  15606. * @param format defines the format of the data
  15607. * @param forcedExtension defines the extension to use to pick the right loader
  15608. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15609. * @returns the cube texture as an InternalTexture
  15610. */
  15611. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15612. var _this = this;
  15613. if (onLoad === void 0) { onLoad = null; }
  15614. if (onError === void 0) { onError = null; }
  15615. if (forcedExtension === void 0) { forcedExtension = null; }
  15616. if (createPolynomials === void 0) { createPolynomials = false; }
  15617. var gl = this._gl;
  15618. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15619. texture.isCube = true;
  15620. texture.url = rootUrl;
  15621. texture.generateMipMaps = !noMipmap;
  15622. if (!this._doNotHandleContextLost) {
  15623. texture._extension = forcedExtension;
  15624. texture._files = files;
  15625. }
  15626. var isKTX = false;
  15627. var isDDS = false;
  15628. var lastDot = rootUrl.lastIndexOf('.');
  15629. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15630. if (this._textureFormatInUse) {
  15631. extension = this._textureFormatInUse;
  15632. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15633. isKTX = true;
  15634. }
  15635. else {
  15636. isDDS = (extension === ".dds");
  15637. }
  15638. var onerror = function (request, exception) {
  15639. if (onError && request) {
  15640. onError(request.status + " " + request.statusText, exception);
  15641. }
  15642. };
  15643. if (isKTX) {
  15644. this._loadFile(rootUrl, function (data) {
  15645. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15646. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15647. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15648. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15649. ktx.uploadLevels(_this._gl, !noMipmap);
  15650. _this.setCubeMapTextureParams(gl, loadMipmap);
  15651. texture.width = ktx.pixelWidth;
  15652. texture.height = ktx.pixelHeight;
  15653. texture.isReady = true;
  15654. }, undefined, undefined, true, onerror);
  15655. }
  15656. else if (isDDS) {
  15657. if (files && files.length === 6) {
  15658. this._cascadeLoadFiles(scene, function (imgs) {
  15659. var info;
  15660. var loadMipmap = false;
  15661. var width = 0;
  15662. for (var index = 0; index < imgs.length; index++) {
  15663. var data = imgs[index];
  15664. info = BABYLON.DDSTools.GetDDSInfo(data);
  15665. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15667. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15668. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15669. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15670. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15671. }
  15672. texture.width = info.width;
  15673. texture.height = info.height;
  15674. texture.type = info.textureType;
  15675. width = info.width;
  15676. }
  15677. _this.setCubeMapTextureParams(gl, loadMipmap);
  15678. texture.isReady = true;
  15679. if (onLoad) {
  15680. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15681. }
  15682. }, files, onError);
  15683. }
  15684. else {
  15685. this._loadFile(rootUrl, function (data) {
  15686. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15687. if (createPolynomials) {
  15688. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15689. }
  15690. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15693. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15694. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15695. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15696. }
  15697. _this.setCubeMapTextureParams(gl, loadMipmap);
  15698. texture.width = info.width;
  15699. texture.height = info.height;
  15700. texture.isReady = true;
  15701. texture.type = info.textureType;
  15702. if (onLoad) {
  15703. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15704. }
  15705. }, undefined, undefined, true, onerror);
  15706. }
  15707. }
  15708. else {
  15709. if (!files) {
  15710. throw new Error("Cannot load cubemap because files were not defined");
  15711. }
  15712. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15713. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15714. var height = width;
  15715. _this._prepareWorkingCanvas();
  15716. if (!_this._workingCanvas || !_this._workingContext) {
  15717. return;
  15718. }
  15719. _this._workingCanvas.width = width;
  15720. _this._workingCanvas.height = height;
  15721. var faces = [
  15722. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15723. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15724. ];
  15725. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15727. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15728. for (var index = 0; index < faces.length; index++) {
  15729. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15730. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15731. }
  15732. if (!noMipmap) {
  15733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15734. }
  15735. _this.setCubeMapTextureParams(gl, !noMipmap);
  15736. texture.width = width;
  15737. texture.height = height;
  15738. texture.isReady = true;
  15739. if (format) {
  15740. texture.format = format;
  15741. }
  15742. texture.onLoadedObservable.notifyObservers(texture);
  15743. texture.onLoadedObservable.clear();
  15744. if (onLoad) {
  15745. onLoad();
  15746. }
  15747. }, files, onError);
  15748. }
  15749. this._internalTexturesCache.push(texture);
  15750. return texture;
  15751. };
  15752. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15753. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15757. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15758. // this.resetTextureCache();
  15759. };
  15760. /**
  15761. * Update a raw cube texture
  15762. * @param texture defines the texture to udpdate
  15763. * @param data defines the data to store
  15764. * @param format defines the data format
  15765. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15766. * @param invertY defines if data must be stored with Y axis inverted
  15767. * @param compression defines the compression used (null by default)
  15768. * @param level defines which level of the texture to update
  15769. */
  15770. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15771. if (compression === void 0) { compression = null; }
  15772. if (level === void 0) { level = 0; }
  15773. texture._bufferViewArray = data;
  15774. texture.format = format;
  15775. texture.type = type;
  15776. texture.invertY = invertY;
  15777. texture._compression = compression;
  15778. var gl = this._gl;
  15779. var textureType = this._getWebGLTextureType(type);
  15780. var internalFormat = this._getInternalFormat(format);
  15781. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15782. var needConversion = false;
  15783. if (internalFormat === gl.RGB) {
  15784. internalFormat = gl.RGBA;
  15785. needConversion = true;
  15786. }
  15787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15788. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15789. if (texture.width % 4 !== 0) {
  15790. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15791. }
  15792. // Data are known to be in +X +Y +Z -X -Y -Z
  15793. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15794. var faceData = data[faceIndex];
  15795. if (compression) {
  15796. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15797. }
  15798. else {
  15799. if (needConversion) {
  15800. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15801. }
  15802. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15803. }
  15804. }
  15805. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15806. if (isPot && texture.generateMipMaps && level === 0) {
  15807. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15808. }
  15809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15810. // this.resetTextureCache();
  15811. texture.isReady = true;
  15812. };
  15813. /**
  15814. * Creates a new raw cube texture
  15815. * @param data defines the array of data to use to create each face
  15816. * @param size defines the size of the textures
  15817. * @param format defines the format of the data
  15818. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15819. * @param generateMipMaps defines if the engine should generate the mip levels
  15820. * @param invertY defines if data must be stored with Y axis inverted
  15821. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15822. * @param compression defines the compression used (null by default)
  15823. * @returns the cube texture as an InternalTexture
  15824. */
  15825. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15826. if (compression === void 0) { compression = null; }
  15827. var gl = this._gl;
  15828. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15829. texture.isCube = true;
  15830. texture.generateMipMaps = generateMipMaps;
  15831. texture.format = format;
  15832. texture.type = type;
  15833. if (!this._doNotHandleContextLost) {
  15834. texture._bufferViewArray = data;
  15835. }
  15836. var textureType = this._getWebGLTextureType(type);
  15837. var internalFormat = this._getInternalFormat(format);
  15838. if (internalFormat === gl.RGB) {
  15839. internalFormat = gl.RGBA;
  15840. }
  15841. var width = size;
  15842. var height = width;
  15843. texture.width = width;
  15844. texture.height = height;
  15845. // Double check on POT to generate Mips.
  15846. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15847. if (!isPot) {
  15848. generateMipMaps = false;
  15849. }
  15850. // Upload data if needed. The texture won't be ready until then.
  15851. if (data) {
  15852. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15853. }
  15854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15855. // Filters
  15856. if (data && generateMipMaps) {
  15857. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15858. }
  15859. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15862. }
  15863. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15866. }
  15867. else {
  15868. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15871. }
  15872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15874. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15875. return texture;
  15876. };
  15877. /**
  15878. * Creates a new raw cube texture from a specified url
  15879. * @param url defines the url where the data is located
  15880. * @param scene defines the current scene
  15881. * @param size defines the size of the textures
  15882. * @param format defines the format of the data
  15883. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15884. * @param noMipmap defines if the engine should avoid generating the mip levels
  15885. * @param callback defines a callback used to extract texture data from loaded data
  15886. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15887. * @param onLoad defines a callback called when texture is loaded
  15888. * @param onError defines a callback called if there is an error
  15889. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15890. * @param invertY defines if data must be stored with Y axis inverted
  15891. * @returns the cube texture as an InternalTexture
  15892. */
  15893. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15894. var _this = this;
  15895. if (onLoad === void 0) { onLoad = null; }
  15896. if (onError === void 0) { onError = null; }
  15897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15898. if (invertY === void 0) { invertY = false; }
  15899. var gl = this._gl;
  15900. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15901. scene._addPendingData(texture);
  15902. texture.url = url;
  15903. this._internalTexturesCache.push(texture);
  15904. var onerror = function (request, exception) {
  15905. scene._removePendingData(texture);
  15906. if (onError && request) {
  15907. onError(request.status + " " + request.statusText, exception);
  15908. }
  15909. };
  15910. var internalCallback = function (data) {
  15911. var width = texture.width;
  15912. var faceDataArrays = callback(data);
  15913. if (!faceDataArrays) {
  15914. return;
  15915. }
  15916. if (mipmapGenerator) {
  15917. var textureType = _this._getWebGLTextureType(type);
  15918. var internalFormat = _this._getInternalFormat(format);
  15919. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15920. var needConversion = false;
  15921. if (internalFormat === gl.RGB) {
  15922. internalFormat = gl.RGBA;
  15923. needConversion = true;
  15924. }
  15925. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15926. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15927. var mipData = mipmapGenerator(faceDataArrays);
  15928. for (var level = 0; level < mipData.length; level++) {
  15929. var mipSize = width >> level;
  15930. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15931. var mipFaceData = mipData[level][faceIndex];
  15932. if (needConversion) {
  15933. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15934. }
  15935. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15936. }
  15937. }
  15938. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15939. }
  15940. else {
  15941. texture.generateMipMaps = !noMipmap;
  15942. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15943. }
  15944. texture.isReady = true;
  15945. // this.resetTextureCache();
  15946. scene._removePendingData(texture);
  15947. if (onLoad) {
  15948. onLoad();
  15949. }
  15950. };
  15951. this._loadFile(url, function (data) {
  15952. internalCallback(data);
  15953. }, undefined, scene.database, true, onerror);
  15954. return texture;
  15955. };
  15956. ;
  15957. /**
  15958. * Update a raw 3D texture
  15959. * @param texture defines the texture to update
  15960. * @param data defines the data to store
  15961. * @param format defines the data format
  15962. * @param invertY defines if data must be stored with Y axis inverted
  15963. * @param compression defines the used compression (can be null)
  15964. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15965. */
  15966. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15967. if (compression === void 0) { compression = null; }
  15968. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15969. var internalType = this._getWebGLTextureType(textureType);
  15970. var internalFormat = this._getInternalFormat(format);
  15971. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15972. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15973. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15974. if (!this._doNotHandleContextLost) {
  15975. texture._bufferView = data;
  15976. texture.format = format;
  15977. texture.invertY = invertY;
  15978. texture._compression = compression;
  15979. }
  15980. if (texture.width % 4 !== 0) {
  15981. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15982. }
  15983. if (compression && data) {
  15984. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15985. }
  15986. else {
  15987. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15988. }
  15989. if (texture.generateMipMaps) {
  15990. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15991. }
  15992. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15993. // this.resetTextureCache();
  15994. texture.isReady = true;
  15995. };
  15996. /**
  15997. * Creates a new raw 3D texture
  15998. * @param data defines the data used to create the texture
  15999. * @param width defines the width of the texture
  16000. * @param height defines the height of the texture
  16001. * @param depth defines the depth of the texture
  16002. * @param format defines the format of the texture
  16003. * @param generateMipMaps defines if the engine must generate mip levels
  16004. * @param invertY defines if data must be stored with Y axis inverted
  16005. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16006. * @param compression defines the compressed used (can be null)
  16007. * @param textureType defines the compressed used (can be null)
  16008. * @returns a new raw 3D texture (stored in an InternalTexture)
  16009. */
  16010. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16011. if (compression === void 0) { compression = null; }
  16012. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16013. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16014. texture.baseWidth = width;
  16015. texture.baseHeight = height;
  16016. texture.baseDepth = depth;
  16017. texture.width = width;
  16018. texture.height = height;
  16019. texture.depth = depth;
  16020. texture.format = format;
  16021. texture.type = textureType;
  16022. texture.generateMipMaps = generateMipMaps;
  16023. texture.samplingMode = samplingMode;
  16024. texture.is3D = true;
  16025. if (!this._doNotHandleContextLost) {
  16026. texture._bufferView = data;
  16027. }
  16028. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16029. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16030. // Filters
  16031. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16032. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16033. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16034. if (generateMipMaps) {
  16035. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16036. }
  16037. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16038. this._internalTexturesCache.push(texture);
  16039. return texture;
  16040. };
  16041. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16042. var gl = this._gl;
  16043. if (!gl) {
  16044. return;
  16045. }
  16046. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16049. if (!noMipmap && !isCompressed) {
  16050. gl.generateMipmap(gl.TEXTURE_2D);
  16051. }
  16052. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16053. // this.resetTextureCache();
  16054. if (scene) {
  16055. scene._removePendingData(texture);
  16056. }
  16057. texture.onLoadedObservable.notifyObservers(texture);
  16058. texture.onLoadedObservable.clear();
  16059. };
  16060. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16061. var _this = this;
  16062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16063. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16064. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16065. var gl = this._gl;
  16066. if (!gl) {
  16067. return;
  16068. }
  16069. if (!texture._webGLTexture) {
  16070. // this.resetTextureCache();
  16071. if (scene) {
  16072. scene._removePendingData(texture);
  16073. }
  16074. return;
  16075. }
  16076. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16077. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16078. texture.baseWidth = width;
  16079. texture.baseHeight = height;
  16080. texture.width = potWidth;
  16081. texture.height = potHeight;
  16082. texture.isReady = true;
  16083. if (processFunction(potWidth, potHeight, function () {
  16084. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16085. })) {
  16086. // Returning as texture needs extra async steps
  16087. return;
  16088. }
  16089. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16090. };
  16091. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16092. // Create new RGBA data container.
  16093. var rgbaData;
  16094. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16095. rgbaData = new Float32Array(width * height * 4);
  16096. }
  16097. else {
  16098. rgbaData = new Uint32Array(width * height * 4);
  16099. }
  16100. // Convert each pixel.
  16101. for (var x = 0; x < width; x++) {
  16102. for (var y = 0; y < height; y++) {
  16103. var index = (y * width + x) * 3;
  16104. var newIndex = (y * width + x) * 4;
  16105. // Map Old Value to new value.
  16106. rgbaData[newIndex + 0] = rgbData[index + 0];
  16107. rgbaData[newIndex + 1] = rgbData[index + 1];
  16108. rgbaData[newIndex + 2] = rgbData[index + 2];
  16109. // Add fully opaque alpha channel.
  16110. rgbaData[newIndex + 3] = 1;
  16111. }
  16112. }
  16113. return rgbaData;
  16114. };
  16115. /** @hidden */
  16116. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16117. var gl = this._gl;
  16118. if (texture._framebuffer) {
  16119. gl.deleteFramebuffer(texture._framebuffer);
  16120. texture._framebuffer = null;
  16121. }
  16122. if (texture._depthStencilBuffer) {
  16123. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16124. texture._depthStencilBuffer = null;
  16125. }
  16126. if (texture._MSAAFramebuffer) {
  16127. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16128. texture._MSAAFramebuffer = null;
  16129. }
  16130. if (texture._MSAARenderBuffer) {
  16131. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16132. texture._MSAARenderBuffer = null;
  16133. }
  16134. };
  16135. /** @hidden */
  16136. Engine.prototype._releaseTexture = function (texture) {
  16137. var gl = this._gl;
  16138. this._releaseFramebufferObjects(texture);
  16139. gl.deleteTexture(texture._webGLTexture);
  16140. // Unbind channels
  16141. this.unbindAllTextures();
  16142. var index = this._internalTexturesCache.indexOf(texture);
  16143. if (index !== -1) {
  16144. this._internalTexturesCache.splice(index, 1);
  16145. }
  16146. // Integrated fixed lod samplers.
  16147. if (texture._lodTextureHigh) {
  16148. texture._lodTextureHigh.dispose();
  16149. }
  16150. if (texture._lodTextureMid) {
  16151. texture._lodTextureMid.dispose();
  16152. }
  16153. if (texture._lodTextureLow) {
  16154. texture._lodTextureLow.dispose();
  16155. }
  16156. // Set output texture of post process to null if the texture has been released/disposed
  16157. this.scenes.forEach(function (scene) {
  16158. scene.postProcesses.forEach(function (postProcess) {
  16159. if (postProcess._outputTexture == texture) {
  16160. postProcess._outputTexture = null;
  16161. }
  16162. });
  16163. scene.cameras.forEach(function (camera) {
  16164. camera._postProcesses.forEach(function (postProcess) {
  16165. if (postProcess) {
  16166. if (postProcess._outputTexture == texture) {
  16167. postProcess._outputTexture = null;
  16168. }
  16169. }
  16170. });
  16171. });
  16172. });
  16173. };
  16174. Engine.prototype.setProgram = function (program) {
  16175. if (this._currentProgram !== program) {
  16176. this._gl.useProgram(program);
  16177. this._currentProgram = program;
  16178. }
  16179. };
  16180. /**
  16181. * Binds an effect to the webGL context
  16182. * @param effect defines the effect to bind
  16183. */
  16184. Engine.prototype.bindSamplers = function (effect) {
  16185. this.setProgram(effect.getProgram());
  16186. var samplers = effect.getSamplers();
  16187. for (var index = 0; index < samplers.length; index++) {
  16188. var uniform = effect.getUniform(samplers[index]);
  16189. if (uniform) {
  16190. this._boundUniforms[index] = uniform;
  16191. }
  16192. }
  16193. this._currentEffect = null;
  16194. };
  16195. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16196. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16197. return;
  16198. }
  16199. // Remove
  16200. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16201. // Bind last to it
  16202. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16203. // Bind to dummy
  16204. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16205. };
  16206. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16207. if (!internalTexture) {
  16208. return -1;
  16209. }
  16210. internalTexture._initialSlot = channel;
  16211. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16212. if (channel !== internalTexture._designatedSlot) {
  16213. this._textureCollisions.addCount(1, false);
  16214. }
  16215. }
  16216. else {
  16217. if (channel !== internalTexture._designatedSlot) {
  16218. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16219. return internalTexture._designatedSlot;
  16220. }
  16221. else {
  16222. // No slot for this texture, let's pick a new one (if we find a free slot)
  16223. if (this._nextFreeTextureSlots.length) {
  16224. return this._nextFreeTextureSlots[0];
  16225. }
  16226. // We need to recycle the oldest bound texture, sorry.
  16227. this._textureCollisions.addCount(1, false);
  16228. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16229. }
  16230. }
  16231. }
  16232. return channel;
  16233. };
  16234. Engine.prototype._linkTrackers = function (previous, next) {
  16235. previous.next = next;
  16236. next.previous = previous;
  16237. };
  16238. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16239. var currentSlot = internalTexture._designatedSlot;
  16240. if (currentSlot === -1) {
  16241. return -1;
  16242. }
  16243. internalTexture._designatedSlot = -1;
  16244. if (this.disableTextureBindingOptimization) {
  16245. return -1;
  16246. }
  16247. // Remove from bound list
  16248. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16249. // Free the slot
  16250. this._boundTexturesCache[currentSlot] = null;
  16251. this._nextFreeTextureSlots.push(currentSlot);
  16252. return currentSlot;
  16253. };
  16254. Engine.prototype._activateCurrentTexture = function () {
  16255. if (this._currentTextureChannel !== this._activeChannel) {
  16256. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16257. this._currentTextureChannel = this._activeChannel;
  16258. }
  16259. };
  16260. /** @hidden */
  16261. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16262. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16263. if (force === void 0) { force = false; }
  16264. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16265. this._activeChannel = texture._designatedSlot;
  16266. }
  16267. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16268. var isTextureForRendering = texture && texture._initialSlot > -1;
  16269. if (currentTextureBound !== texture || force) {
  16270. if (currentTextureBound) {
  16271. this._removeDesignatedSlot(currentTextureBound);
  16272. }
  16273. this._activateCurrentTexture();
  16274. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16275. this._boundTexturesCache[this._activeChannel] = texture;
  16276. if (texture) {
  16277. if (!this.disableTextureBindingOptimization) {
  16278. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16279. if (slotIndex > -1) {
  16280. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16281. }
  16282. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16283. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16284. }
  16285. texture._designatedSlot = this._activeChannel;
  16286. }
  16287. }
  16288. else if (forTextureDataUpdate) {
  16289. this._activateCurrentTexture();
  16290. }
  16291. if (isTextureForRendering && !forTextureDataUpdate) {
  16292. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16293. }
  16294. };
  16295. /** @hidden */
  16296. Engine.prototype._bindTexture = function (channel, texture) {
  16297. if (channel < 0) {
  16298. return;
  16299. }
  16300. if (texture) {
  16301. channel = this._getCorrectTextureChannel(channel, texture);
  16302. }
  16303. this._activeChannel = channel;
  16304. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16305. };
  16306. /**
  16307. * Sets a texture to the webGL context from a postprocess
  16308. * @param channel defines the channel to use
  16309. * @param postProcess defines the source postprocess
  16310. */
  16311. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16312. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16313. };
  16314. /**
  16315. * Binds the output of the passed in post process to the texture channel specified
  16316. * @param channel The channel the texture should be bound to
  16317. * @param postProcess The post process which's output should be bound
  16318. */
  16319. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16320. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16321. };
  16322. /**
  16323. * Unbind all textures from the webGL context
  16324. */
  16325. Engine.prototype.unbindAllTextures = function () {
  16326. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16327. this._activeChannel = channel;
  16328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16329. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16330. if (this.webGLVersion > 1) {
  16331. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16332. }
  16333. }
  16334. };
  16335. /**
  16336. * Sets a texture to the according uniform.
  16337. * @param channel The texture channel
  16338. * @param uniform The uniform to set
  16339. * @param texture The texture to apply
  16340. */
  16341. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16342. if (channel < 0) {
  16343. return;
  16344. }
  16345. if (uniform) {
  16346. this._boundUniforms[channel] = uniform;
  16347. }
  16348. this._setTexture(channel, texture);
  16349. };
  16350. /**
  16351. * Sets a depth stencil texture from a render target to the according uniform.
  16352. * @param channel The texture channel
  16353. * @param uniform The uniform to set
  16354. * @param texture The render target texture containing the depth stencil texture to apply
  16355. */
  16356. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16357. if (channel < 0) {
  16358. return;
  16359. }
  16360. if (uniform) {
  16361. this._boundUniforms[channel] = uniform;
  16362. }
  16363. if (!texture || !texture.depthStencilTexture) {
  16364. this._setTexture(channel, null);
  16365. }
  16366. else {
  16367. this._setTexture(channel, texture, false, true);
  16368. }
  16369. };
  16370. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16371. var uniform = this._boundUniforms[sourceSlot];
  16372. if (uniform._currentState === destination) {
  16373. return;
  16374. }
  16375. this._gl.uniform1i(uniform, destination);
  16376. uniform._currentState = destination;
  16377. };
  16378. Engine.prototype._getTextureWrapMode = function (mode) {
  16379. switch (mode) {
  16380. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16381. return this._gl.REPEAT;
  16382. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16383. return this._gl.CLAMP_TO_EDGE;
  16384. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16385. return this._gl.MIRRORED_REPEAT;
  16386. }
  16387. return this._gl.REPEAT;
  16388. };
  16389. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16390. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16391. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16392. // Not ready?
  16393. if (!texture) {
  16394. if (this._boundTexturesCache[channel] != null) {
  16395. this._activeChannel = channel;
  16396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16398. if (this.webGLVersion > 1) {
  16399. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16400. }
  16401. }
  16402. return false;
  16403. }
  16404. // Video
  16405. if (texture.video) {
  16406. this._activeChannel = channel;
  16407. texture.update();
  16408. }
  16409. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16410. texture.delayLoad();
  16411. return false;
  16412. }
  16413. var internalTexture;
  16414. if (depthStencilTexture) {
  16415. internalTexture = texture.depthStencilTexture;
  16416. }
  16417. else if (texture.isReady()) {
  16418. internalTexture = texture.getInternalTexture();
  16419. }
  16420. else if (texture.isCube) {
  16421. internalTexture = this.emptyCubeTexture;
  16422. }
  16423. else if (texture.is3D) {
  16424. internalTexture = this.emptyTexture3D;
  16425. }
  16426. else {
  16427. internalTexture = this.emptyTexture;
  16428. }
  16429. if (!isPartOfTextureArray) {
  16430. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16431. }
  16432. var needToBind = true;
  16433. if (this._boundTexturesCache[channel] === internalTexture) {
  16434. this._moveBoundTextureOnTop(internalTexture);
  16435. if (!isPartOfTextureArray) {
  16436. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16437. }
  16438. needToBind = false;
  16439. }
  16440. this._activeChannel = channel;
  16441. if (internalTexture && internalTexture.is3D) {
  16442. if (needToBind) {
  16443. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16444. }
  16445. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16446. internalTexture._cachedWrapU = texture.wrapU;
  16447. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16448. }
  16449. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16450. internalTexture._cachedWrapV = texture.wrapV;
  16451. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16452. }
  16453. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16454. internalTexture._cachedWrapR = texture.wrapR;
  16455. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16456. }
  16457. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16458. }
  16459. else if (internalTexture && internalTexture.isCube) {
  16460. if (needToBind) {
  16461. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16462. }
  16463. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16464. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16465. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16466. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16467. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16468. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16469. }
  16470. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16471. }
  16472. else {
  16473. if (needToBind) {
  16474. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16475. }
  16476. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16477. internalTexture._cachedWrapU = texture.wrapU;
  16478. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16479. }
  16480. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16481. internalTexture._cachedWrapV = texture.wrapV;
  16482. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16483. }
  16484. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16485. }
  16486. return true;
  16487. };
  16488. /**
  16489. * Sets an array of texture to the webGL context
  16490. * @param channel defines the channel where the texture array must be set
  16491. * @param uniform defines the associated uniform location
  16492. * @param textures defines the array of textures to bind
  16493. */
  16494. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16495. if (channel < 0 || !uniform) {
  16496. return;
  16497. }
  16498. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16499. this._textureUnits = new Int32Array(textures.length);
  16500. }
  16501. for (var i = 0; i < textures.length; i++) {
  16502. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16503. }
  16504. this._gl.uniform1iv(uniform, this._textureUnits);
  16505. for (var index = 0; index < textures.length; index++) {
  16506. this._setTexture(this._textureUnits[index], textures[index], true);
  16507. }
  16508. };
  16509. /** @hidden */
  16510. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16511. var internalTexture = texture.getInternalTexture();
  16512. if (!internalTexture) {
  16513. return;
  16514. }
  16515. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16516. var value = texture.anisotropicFilteringLevel;
  16517. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16518. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16519. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16520. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16521. }
  16522. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16523. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16524. internalTexture._cachedAnisotropicFilteringLevel = value;
  16525. }
  16526. };
  16527. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16528. this._bindTextureDirectly(target, texture, true, true);
  16529. this._gl.texParameterf(target, parameter, value);
  16530. };
  16531. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16532. if (texture) {
  16533. this._bindTextureDirectly(target, texture, true, true);
  16534. }
  16535. this._gl.texParameteri(target, parameter, value);
  16536. };
  16537. /**
  16538. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16539. * @param x defines the x coordinate of the rectangle where pixels must be read
  16540. * @param y defines the y coordinate of the rectangle where pixels must be read
  16541. * @param width defines the width of the rectangle where pixels must be read
  16542. * @param height defines the height of the rectangle where pixels must be read
  16543. * @returns a Uint8Array containing RGBA colors
  16544. */
  16545. Engine.prototype.readPixels = function (x, y, width, height) {
  16546. var data = new Uint8Array(height * width * 4);
  16547. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16548. return data;
  16549. };
  16550. /**
  16551. * Add an externaly attached data from its key.
  16552. * This method call will fail and return false, if such key already exists.
  16553. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16554. * @param key the unique key that identifies the data
  16555. * @param data the data object to associate to the key for this Engine instance
  16556. * @return true if no such key were already present and the data was added successfully, false otherwise
  16557. */
  16558. Engine.prototype.addExternalData = function (key, data) {
  16559. if (!this._externalData) {
  16560. this._externalData = new BABYLON.StringDictionary();
  16561. }
  16562. return this._externalData.add(key, data);
  16563. };
  16564. /**
  16565. * Get an externaly attached data from its key
  16566. * @param key the unique key that identifies the data
  16567. * @return the associated data, if present (can be null), or undefined if not present
  16568. */
  16569. Engine.prototype.getExternalData = function (key) {
  16570. if (!this._externalData) {
  16571. this._externalData = new BABYLON.StringDictionary();
  16572. }
  16573. return this._externalData.get(key);
  16574. };
  16575. /**
  16576. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16577. * @param key the unique key that identifies the data
  16578. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16579. * @return the associated data, can be null if the factory returned null.
  16580. */
  16581. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16582. if (!this._externalData) {
  16583. this._externalData = new BABYLON.StringDictionary();
  16584. }
  16585. return this._externalData.getOrAddWithFactory(key, factory);
  16586. };
  16587. /**
  16588. * Remove an externaly attached data from the Engine instance
  16589. * @param key the unique key that identifies the data
  16590. * @return true if the data was successfully removed, false if it doesn't exist
  16591. */
  16592. Engine.prototype.removeExternalData = function (key) {
  16593. if (!this._externalData) {
  16594. this._externalData = new BABYLON.StringDictionary();
  16595. }
  16596. return this._externalData.remove(key);
  16597. };
  16598. /**
  16599. * Unbind all vertex attributes from the webGL context
  16600. */
  16601. Engine.prototype.unbindAllAttributes = function () {
  16602. if (this._mustWipeVertexAttributes) {
  16603. this._mustWipeVertexAttributes = false;
  16604. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16605. this._gl.disableVertexAttribArray(i);
  16606. this._vertexAttribArraysEnabled[i] = false;
  16607. this._currentBufferPointers[i].active = false;
  16608. }
  16609. return;
  16610. }
  16611. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16612. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16613. continue;
  16614. }
  16615. this._gl.disableVertexAttribArray(i);
  16616. this._vertexAttribArraysEnabled[i] = false;
  16617. this._currentBufferPointers[i].active = false;
  16618. }
  16619. };
  16620. /**
  16621. * 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
  16622. */
  16623. Engine.prototype.releaseEffects = function () {
  16624. for (var name in this._compiledEffects) {
  16625. this._deleteProgram(this._compiledEffects[name]._program);
  16626. }
  16627. this._compiledEffects = {};
  16628. };
  16629. /**
  16630. * Dispose and release all associated resources
  16631. */
  16632. Engine.prototype.dispose = function () {
  16633. this.hideLoadingUI();
  16634. this.stopRenderLoop();
  16635. // Release postProcesses
  16636. while (this.postProcesses.length) {
  16637. this.postProcesses[0].dispose();
  16638. }
  16639. // Empty texture
  16640. if (this._emptyTexture) {
  16641. this._releaseTexture(this._emptyTexture);
  16642. this._emptyTexture = null;
  16643. }
  16644. if (this._emptyCubeTexture) {
  16645. this._releaseTexture(this._emptyCubeTexture);
  16646. this._emptyCubeTexture = null;
  16647. }
  16648. // Rescale PP
  16649. if (this._rescalePostProcess) {
  16650. this._rescalePostProcess.dispose();
  16651. }
  16652. // Release scenes
  16653. while (this.scenes.length) {
  16654. this.scenes[0].dispose();
  16655. }
  16656. // Release audio engine
  16657. if (Engine.audioEngine) {
  16658. Engine.audioEngine.dispose();
  16659. }
  16660. // Release effects
  16661. this.releaseEffects();
  16662. // Unbind
  16663. this.unbindAllAttributes();
  16664. this._boundUniforms = [];
  16665. if (this._dummyFramebuffer) {
  16666. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16667. }
  16668. //WebVR
  16669. this.disableVR();
  16670. // Events
  16671. if (BABYLON.Tools.IsWindowObjectExist()) {
  16672. window.removeEventListener("blur", this._onBlur);
  16673. window.removeEventListener("focus", this._onFocus);
  16674. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16675. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16676. if (this._renderingCanvas) {
  16677. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16678. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16679. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16680. if (!this._doNotHandleContextLost) {
  16681. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16682. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16683. }
  16684. }
  16685. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16686. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16687. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16688. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16689. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16690. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16691. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16692. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16693. if (this._onVrDisplayConnect) {
  16694. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16695. if (this._onVrDisplayDisconnect) {
  16696. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16697. }
  16698. if (this._onVrDisplayPresentChange) {
  16699. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16700. }
  16701. this._onVrDisplayConnect = null;
  16702. this._onVrDisplayDisconnect = null;
  16703. }
  16704. }
  16705. // Remove from Instances
  16706. var index = Engine.Instances.indexOf(this);
  16707. if (index >= 0) {
  16708. Engine.Instances.splice(index, 1);
  16709. }
  16710. this._workingCanvas = null;
  16711. this._workingContext = null;
  16712. this._currentBufferPointers = [];
  16713. this._renderingCanvas = null;
  16714. this._currentProgram = null;
  16715. this._bindedRenderFunction = null;
  16716. this.onResizeObservable.clear();
  16717. this.onCanvasBlurObservable.clear();
  16718. this.onCanvasFocusObservable.clear();
  16719. this.onCanvasPointerOutObservable.clear();
  16720. this.onBeginFrameObservable.clear();
  16721. this.onEndFrameObservable.clear();
  16722. BABYLON.Effect.ResetCache();
  16723. // Abort active requests
  16724. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16725. var request = _a[_i];
  16726. request.abort();
  16727. }
  16728. };
  16729. // Loading screen
  16730. /**
  16731. * Display the loading screen
  16732. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16733. */
  16734. Engine.prototype.displayLoadingUI = function () {
  16735. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16736. return;
  16737. }
  16738. var loadingScreen = this.loadingScreen;
  16739. if (loadingScreen) {
  16740. loadingScreen.displayLoadingUI();
  16741. }
  16742. };
  16743. /**
  16744. * Hide the loading screen
  16745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16746. */
  16747. Engine.prototype.hideLoadingUI = function () {
  16748. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16749. return;
  16750. }
  16751. var loadingScreen = this.loadingScreen;
  16752. if (loadingScreen) {
  16753. loadingScreen.hideLoadingUI();
  16754. }
  16755. };
  16756. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16757. /**
  16758. * Gets the current loading screen object
  16759. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16760. */
  16761. get: function () {
  16762. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16763. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16764. return this._loadingScreen;
  16765. },
  16766. /**
  16767. * Sets the current loading screen object
  16768. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16769. */
  16770. set: function (loadingScreen) {
  16771. this._loadingScreen = loadingScreen;
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16777. /**
  16778. * Sets the current loading screen text
  16779. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16780. */
  16781. set: function (text) {
  16782. this.loadingScreen.loadingUIText = text;
  16783. },
  16784. enumerable: true,
  16785. configurable: true
  16786. });
  16787. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16788. /**
  16789. * Sets the current loading screen background color
  16790. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16791. */
  16792. set: function (color) {
  16793. this.loadingScreen.loadingUIBackgroundColor = color;
  16794. },
  16795. enumerable: true,
  16796. configurable: true
  16797. });
  16798. /**
  16799. * Attach a new callback raised when context lost event is fired
  16800. * @param callback defines the callback to call
  16801. */
  16802. Engine.prototype.attachContextLostEvent = function (callback) {
  16803. if (this._renderingCanvas) {
  16804. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16805. }
  16806. };
  16807. /**
  16808. * Attach a new callback raised when context restored event is fired
  16809. * @param callback defines the callback to call
  16810. */
  16811. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16812. if (this._renderingCanvas) {
  16813. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16814. }
  16815. };
  16816. /**
  16817. * Gets the source code of the vertex shader associated with a specific webGL program
  16818. * @param program defines the program to use
  16819. * @returns a string containing the source code of the vertex shader associated with the program
  16820. */
  16821. Engine.prototype.getVertexShaderSource = function (program) {
  16822. var shaders = this._gl.getAttachedShaders(program);
  16823. if (!shaders) {
  16824. return null;
  16825. }
  16826. return this._gl.getShaderSource(shaders[0]);
  16827. };
  16828. /**
  16829. * Gets the source code of the fragment shader associated with a specific webGL program
  16830. * @param program defines the program to use
  16831. * @returns a string containing the source code of the fragment shader associated with the program
  16832. */
  16833. Engine.prototype.getFragmentShaderSource = function (program) {
  16834. var shaders = this._gl.getAttachedShaders(program);
  16835. if (!shaders) {
  16836. return null;
  16837. }
  16838. return this._gl.getShaderSource(shaders[1]);
  16839. };
  16840. /**
  16841. * Get the current error code of the webGL context
  16842. * @returns the error code
  16843. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16844. */
  16845. Engine.prototype.getError = function () {
  16846. return this._gl.getError();
  16847. };
  16848. // FPS
  16849. /**
  16850. * Gets the current framerate
  16851. * @returns a number representing the framerate
  16852. */
  16853. Engine.prototype.getFps = function () {
  16854. return this._fps;
  16855. };
  16856. /**
  16857. * Gets the time spent between current and previous frame
  16858. * @returns a number representing the delta time in ms
  16859. */
  16860. Engine.prototype.getDeltaTime = function () {
  16861. return this._deltaTime;
  16862. };
  16863. Engine.prototype._measureFps = function () {
  16864. this._performanceMonitor.sampleFrame();
  16865. this._fps = this._performanceMonitor.averageFPS;
  16866. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16867. };
  16868. /** @hidden */
  16869. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16870. if (faceIndex === void 0) { faceIndex = -1; }
  16871. var gl = this._gl;
  16872. if (!this._dummyFramebuffer) {
  16873. var dummy = gl.createFramebuffer();
  16874. if (!dummy) {
  16875. throw new Error("Unable to create dummy framebuffer");
  16876. }
  16877. this._dummyFramebuffer = dummy;
  16878. }
  16879. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16880. if (faceIndex > -1) {
  16881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16882. }
  16883. else {
  16884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16885. }
  16886. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16887. var buffer;
  16888. switch (readType) {
  16889. case gl.UNSIGNED_BYTE:
  16890. buffer = new Uint8Array(4 * width * height);
  16891. readType = gl.UNSIGNED_BYTE;
  16892. break;
  16893. default:
  16894. buffer = new Float32Array(4 * width * height);
  16895. readType = gl.FLOAT;
  16896. break;
  16897. }
  16898. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16899. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16900. return buffer;
  16901. };
  16902. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16903. if (this._webGLVersion > 1) {
  16904. return this._caps.colorBufferFloat;
  16905. }
  16906. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16907. };
  16908. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16909. if (this._webGLVersion > 1) {
  16910. return this._caps.colorBufferFloat;
  16911. }
  16912. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16913. };
  16914. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16915. Engine.prototype._canRenderToFramebuffer = function (type) {
  16916. var gl = this._gl;
  16917. //clear existing errors
  16918. while (gl.getError() !== gl.NO_ERROR) { }
  16919. var successful = true;
  16920. var texture = gl.createTexture();
  16921. gl.bindTexture(gl.TEXTURE_2D, texture);
  16922. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16923. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16925. var fb = gl.createFramebuffer();
  16926. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16928. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16929. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16930. successful = successful && (gl.getError() === gl.NO_ERROR);
  16931. //try render by clearing frame buffer's color buffer
  16932. if (successful) {
  16933. gl.clear(gl.COLOR_BUFFER_BIT);
  16934. successful = successful && (gl.getError() === gl.NO_ERROR);
  16935. }
  16936. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16937. if (successful) {
  16938. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16939. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16940. var readFormat = gl.RGBA;
  16941. var readType = gl.UNSIGNED_BYTE;
  16942. var buffer = new Uint8Array(4);
  16943. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16944. successful = successful && (gl.getError() === gl.NO_ERROR);
  16945. }
  16946. //clean up
  16947. gl.deleteTexture(texture);
  16948. gl.deleteFramebuffer(fb);
  16949. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16950. //clear accumulated errors
  16951. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16952. return successful;
  16953. };
  16954. /** @hidden */
  16955. Engine.prototype._getWebGLTextureType = function (type) {
  16956. if (type === Engine.TEXTURETYPE_FLOAT) {
  16957. return this._gl.FLOAT;
  16958. }
  16959. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16960. // Add Half Float Constant.
  16961. return this._gl.HALF_FLOAT_OES;
  16962. }
  16963. return this._gl.UNSIGNED_BYTE;
  16964. };
  16965. ;
  16966. Engine.prototype._getInternalFormat = function (format) {
  16967. var internalFormat = this._gl.RGBA;
  16968. switch (format) {
  16969. case Engine.TEXTUREFORMAT_ALPHA:
  16970. internalFormat = this._gl.ALPHA;
  16971. break;
  16972. case Engine.TEXTUREFORMAT_LUMINANCE:
  16973. internalFormat = this._gl.LUMINANCE;
  16974. break;
  16975. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16976. internalFormat = this._gl.LUMINANCE_ALPHA;
  16977. break;
  16978. case Engine.TEXTUREFORMAT_RGB:
  16979. internalFormat = this._gl.RGB;
  16980. break;
  16981. case Engine.TEXTUREFORMAT_RGBA:
  16982. internalFormat = this._gl.RGBA;
  16983. break;
  16984. case Engine.TEXTUREFORMAT_R:
  16985. internalFormat = this._gl.RED;
  16986. break;
  16987. case Engine.TEXTUREFORMAT_RG:
  16988. internalFormat = this._gl.RG;
  16989. break;
  16990. }
  16991. return internalFormat;
  16992. };
  16993. /** @hidden */
  16994. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16995. if (this._webGLVersion === 1) {
  16996. if (format !== undefined) {
  16997. switch (format) {
  16998. case Engine.TEXTUREFORMAT_LUMINANCE:
  16999. return this._gl.LUMINANCE;
  17000. case Engine.TEXTUREFORMAT_ALPHA:
  17001. return this._gl.ALPHA;
  17002. }
  17003. }
  17004. return this._gl.RGBA;
  17005. }
  17006. if (type === Engine.TEXTURETYPE_FLOAT) {
  17007. if (format !== undefined) {
  17008. switch (format) {
  17009. case Engine.TEXTUREFORMAT_R:
  17010. return this._gl.R32F;
  17011. case Engine.TEXTUREFORMAT_RG:
  17012. return this._gl.RG32F;
  17013. case Engine.TEXTUREFORMAT_RGB:
  17014. return this._gl.RGB32F;
  17015. }
  17016. }
  17017. return this._gl.RGBA32F;
  17018. }
  17019. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17020. if (format) {
  17021. switch (format) {
  17022. case Engine.TEXTUREFORMAT_R:
  17023. return this._gl.R16F;
  17024. case Engine.TEXTUREFORMAT_RG:
  17025. return this._gl.RG16F;
  17026. case Engine.TEXTUREFORMAT_RGB:
  17027. return this._gl.RGB16F;
  17028. }
  17029. }
  17030. return this._gl.RGBA16F;
  17031. }
  17032. if (format !== undefined) {
  17033. switch (format) {
  17034. case Engine.TEXTUREFORMAT_LUMINANCE:
  17035. return this._gl.LUMINANCE;
  17036. case Engine.TEXTUREFORMAT_RGB:
  17037. return this._gl.RGB;
  17038. case Engine.TEXTUREFORMAT_R:
  17039. return this._gl.R8;
  17040. case Engine.TEXTUREFORMAT_RG:
  17041. return this._gl.RG8;
  17042. case Engine.TEXTUREFORMAT_ALPHA:
  17043. return this._gl.ALPHA;
  17044. }
  17045. }
  17046. return this._gl.RGBA;
  17047. };
  17048. ;
  17049. /** @hidden */
  17050. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17051. if (type === Engine.TEXTURETYPE_FLOAT) {
  17052. return this._gl.RGBA32F;
  17053. }
  17054. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17055. return this._gl.RGBA16F;
  17056. }
  17057. return this._gl.RGBA8;
  17058. };
  17059. ;
  17060. /**
  17061. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17062. * @return the new query
  17063. */
  17064. Engine.prototype.createQuery = function () {
  17065. return this._gl.createQuery();
  17066. };
  17067. /**
  17068. * Delete and release a webGL query
  17069. * @param query defines the query to delete
  17070. * @return the current engine
  17071. */
  17072. Engine.prototype.deleteQuery = function (query) {
  17073. this._gl.deleteQuery(query);
  17074. return this;
  17075. };
  17076. /**
  17077. * Check if a given query has resolved and got its value
  17078. * @param query defines the query to check
  17079. * @returns true if the query got its value
  17080. */
  17081. Engine.prototype.isQueryResultAvailable = function (query) {
  17082. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17083. };
  17084. /**
  17085. * Gets the value of a given query
  17086. * @param query defines the query to check
  17087. * @returns the value of the query
  17088. */
  17089. Engine.prototype.getQueryResult = function (query) {
  17090. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17091. };
  17092. /**
  17093. * Initiates an occlusion query
  17094. * @param algorithmType defines the algorithm to use
  17095. * @param query defines the query to use
  17096. * @returns the current engine
  17097. * @see http://doc.babylonjs.com/features/occlusionquery
  17098. */
  17099. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17100. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17101. this._gl.beginQuery(glAlgorithm, query);
  17102. return this;
  17103. };
  17104. /**
  17105. * Ends an occlusion query
  17106. * @see http://doc.babylonjs.com/features/occlusionquery
  17107. * @param algorithmType defines the algorithm to use
  17108. * @returns the current engine
  17109. */
  17110. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17111. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17112. this._gl.endQuery(glAlgorithm);
  17113. return this;
  17114. };
  17115. /* Time queries */
  17116. Engine.prototype._createTimeQuery = function () {
  17117. var timerQuery = this._caps.timerQuery;
  17118. if (timerQuery.createQueryEXT) {
  17119. return timerQuery.createQueryEXT();
  17120. }
  17121. return this.createQuery();
  17122. };
  17123. Engine.prototype._deleteTimeQuery = function (query) {
  17124. var timerQuery = this._caps.timerQuery;
  17125. if (timerQuery.deleteQueryEXT) {
  17126. timerQuery.deleteQueryEXT(query);
  17127. return;
  17128. }
  17129. this.deleteQuery(query);
  17130. };
  17131. Engine.prototype._getTimeQueryResult = function (query) {
  17132. var timerQuery = this._caps.timerQuery;
  17133. if (timerQuery.getQueryObjectEXT) {
  17134. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17135. }
  17136. return this.getQueryResult(query);
  17137. };
  17138. Engine.prototype._getTimeQueryAvailability = function (query) {
  17139. var timerQuery = this._caps.timerQuery;
  17140. if (timerQuery.getQueryObjectEXT) {
  17141. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17142. }
  17143. return this.isQueryResultAvailable(query);
  17144. };
  17145. /**
  17146. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17147. * Please note that only one query can be issued at a time
  17148. * @returns a time token used to track the time span
  17149. */
  17150. Engine.prototype.startTimeQuery = function () {
  17151. var timerQuery = this._caps.timerQuery;
  17152. if (!timerQuery) {
  17153. return null;
  17154. }
  17155. var token = new BABYLON._TimeToken();
  17156. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17157. if (this._caps.canUseTimestampForTimerQuery) {
  17158. token._startTimeQuery = this._createTimeQuery();
  17159. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17160. }
  17161. else {
  17162. if (this._currentNonTimestampToken) {
  17163. return this._currentNonTimestampToken;
  17164. }
  17165. token._timeElapsedQuery = this._createTimeQuery();
  17166. if (timerQuery.beginQueryEXT) {
  17167. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17168. }
  17169. else {
  17170. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17171. }
  17172. this._currentNonTimestampToken = token;
  17173. }
  17174. return token;
  17175. };
  17176. /**
  17177. * Ends a time query
  17178. * @param token defines the token used to measure the time span
  17179. * @returns the time spent (in ns)
  17180. */
  17181. Engine.prototype.endTimeQuery = function (token) {
  17182. var timerQuery = this._caps.timerQuery;
  17183. if (!timerQuery || !token) {
  17184. return -1;
  17185. }
  17186. if (this._caps.canUseTimestampForTimerQuery) {
  17187. if (!token._startTimeQuery) {
  17188. return -1;
  17189. }
  17190. if (!token._endTimeQuery) {
  17191. token._endTimeQuery = this._createTimeQuery();
  17192. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17193. }
  17194. }
  17195. else if (!token._timeElapsedQueryEnded) {
  17196. if (!token._timeElapsedQuery) {
  17197. return -1;
  17198. }
  17199. if (timerQuery.endQueryEXT) {
  17200. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17201. }
  17202. else {
  17203. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17204. }
  17205. token._timeElapsedQueryEnded = true;
  17206. }
  17207. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17208. var available = false;
  17209. if (token._endTimeQuery) {
  17210. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17211. }
  17212. else if (token._timeElapsedQuery) {
  17213. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17214. }
  17215. if (available && !disjoint) {
  17216. var result = 0;
  17217. if (this._caps.canUseTimestampForTimerQuery) {
  17218. if (!token._startTimeQuery || !token._endTimeQuery) {
  17219. return -1;
  17220. }
  17221. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17222. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17223. result = timeEnd - timeStart;
  17224. this._deleteTimeQuery(token._startTimeQuery);
  17225. this._deleteTimeQuery(token._endTimeQuery);
  17226. token._startTimeQuery = null;
  17227. token._endTimeQuery = null;
  17228. }
  17229. else {
  17230. if (!token._timeElapsedQuery) {
  17231. return -1;
  17232. }
  17233. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17234. this._deleteTimeQuery(token._timeElapsedQuery);
  17235. token._timeElapsedQuery = null;
  17236. token._timeElapsedQueryEnded = false;
  17237. this._currentNonTimestampToken = null;
  17238. }
  17239. return result;
  17240. }
  17241. return -1;
  17242. };
  17243. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17244. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17245. };
  17246. // Transform feedback
  17247. /**
  17248. * Creates a webGL transform feedback object
  17249. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17250. * @returns the webGL transform feedback object
  17251. */
  17252. Engine.prototype.createTransformFeedback = function () {
  17253. return this._gl.createTransformFeedback();
  17254. };
  17255. /**
  17256. * Delete a webGL transform feedback object
  17257. * @param value defines the webGL transform feedback object to delete
  17258. */
  17259. Engine.prototype.deleteTransformFeedback = function (value) {
  17260. this._gl.deleteTransformFeedback(value);
  17261. };
  17262. /**
  17263. * Bind a webGL transform feedback object to the webgl context
  17264. * @param value defines the webGL transform feedback object to bind
  17265. */
  17266. Engine.prototype.bindTransformFeedback = function (value) {
  17267. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17268. };
  17269. /**
  17270. * Begins a transform feedback operation
  17271. * @param usePoints defines if points or triangles must be used
  17272. */
  17273. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17274. if (usePoints === void 0) { usePoints = true; }
  17275. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17276. };
  17277. /**
  17278. * Ends a transform feedback operation
  17279. */
  17280. Engine.prototype.endTransformFeedback = function () {
  17281. this._gl.endTransformFeedback();
  17282. };
  17283. /**
  17284. * Specify the varyings to use with transform feedback
  17285. * @param program defines the associated webGL program
  17286. * @param value defines the list of strings representing the varying names
  17287. */
  17288. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17289. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17290. };
  17291. /**
  17292. * Bind a webGL buffer for a transform feedback operation
  17293. * @param value defines the webGL buffer to bind
  17294. */
  17295. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17296. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17297. };
  17298. /** @hidden */
  17299. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17300. var _this = this;
  17301. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17302. this._activeRequests.push(request);
  17303. request.onCompleteObservable.add(function (request) {
  17304. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17305. });
  17306. return request;
  17307. };
  17308. /** @hidden */
  17309. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17310. var _this = this;
  17311. return new Promise(function (resolve, reject) {
  17312. _this._loadFile(url, function (data) {
  17313. resolve(data);
  17314. }, undefined, database, useArrayBuffer, function (request, exception) {
  17315. reject(exception);
  17316. });
  17317. });
  17318. };
  17319. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17320. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17321. var onload = function (data) {
  17322. loadedFiles[index] = data;
  17323. loadedFiles._internalCount++;
  17324. if (loadedFiles._internalCount === 6) {
  17325. onfinish(loadedFiles);
  17326. }
  17327. };
  17328. var onerror = function (request, exception) {
  17329. if (onErrorCallBack && request) {
  17330. onErrorCallBack(request.status + " " + request.statusText, exception);
  17331. }
  17332. };
  17333. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17334. };
  17335. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17336. if (onError === void 0) { onError = null; }
  17337. var loadedFiles = [];
  17338. loadedFiles._internalCount = 0;
  17339. for (var index = 0; index < 6; index++) {
  17340. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17341. }
  17342. };
  17343. // Statics
  17344. /**
  17345. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17346. * @returns true if the engine can be created
  17347. * @ignorenaming
  17348. */
  17349. Engine.isSupported = function () {
  17350. try {
  17351. var tempcanvas = document.createElement("canvas");
  17352. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17353. return gl != null && !!window.WebGLRenderingContext;
  17354. }
  17355. catch (e) {
  17356. return false;
  17357. }
  17358. };
  17359. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17360. Engine.ExceptionList = [
  17361. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17362. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17363. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17364. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17365. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17366. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17367. ];
  17368. /** Gets the list of created engines */
  17369. Engine.Instances = new Array();
  17370. // Const statics
  17371. Engine._ALPHA_DISABLE = 0;
  17372. Engine._ALPHA_ADD = 1;
  17373. Engine._ALPHA_COMBINE = 2;
  17374. Engine._ALPHA_SUBTRACT = 3;
  17375. Engine._ALPHA_MULTIPLY = 4;
  17376. Engine._ALPHA_MAXIMIZED = 5;
  17377. Engine._ALPHA_ONEONE = 6;
  17378. Engine._ALPHA_PREMULTIPLIED = 7;
  17379. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17380. Engine._ALPHA_INTERPOLATE = 9;
  17381. Engine._ALPHA_SCREENMODE = 10;
  17382. Engine._DELAYLOADSTATE_NONE = 0;
  17383. Engine._DELAYLOADSTATE_LOADED = 1;
  17384. Engine._DELAYLOADSTATE_LOADING = 2;
  17385. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17386. Engine._TEXTUREFORMAT_ALPHA = 0;
  17387. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17388. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17389. Engine._TEXTUREFORMAT_RGB = 4;
  17390. Engine._TEXTUREFORMAT_RGBA = 5;
  17391. Engine._TEXTUREFORMAT_R = 6;
  17392. Engine._TEXTUREFORMAT_RG = 7;
  17393. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17394. Engine._TEXTURETYPE_FLOAT = 1;
  17395. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17396. // Depht or Stencil test Constants.
  17397. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17398. 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.
  17399. 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.
  17400. 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.
  17401. 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.
  17402. 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.
  17403. 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.
  17404. 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.
  17405. // Stencil Actions Constants.
  17406. Engine._KEEP = 0x1E00;
  17407. Engine._REPLACE = 0x1E01;
  17408. Engine._INCR = 0x1E02;
  17409. Engine._DECR = 0x1E03;
  17410. Engine._INVERT = 0x150A;
  17411. Engine._INCR_WRAP = 0x8507;
  17412. Engine._DECR_WRAP = 0x8508;
  17413. // Texture rescaling mode
  17414. Engine._SCALEMODE_FLOOR = 1;
  17415. Engine._SCALEMODE_NEAREST = 2;
  17416. Engine._SCALEMODE_CEILING = 3;
  17417. // Updatable statics so stick with vars here
  17418. /**
  17419. * Gets or sets the epsilon value used by collision engine
  17420. */
  17421. Engine.CollisionsEpsilon = 0.001;
  17422. /**
  17423. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17424. */
  17425. Engine.CodeRepository = "src/";
  17426. /**
  17427. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17428. */
  17429. Engine.ShadersRepository = "src/Shaders/";
  17430. return Engine;
  17431. }());
  17432. BABYLON.Engine = Engine;
  17433. })(BABYLON || (BABYLON = {}));
  17434. //# sourceMappingURL=babylon.engine.js.map
  17435. var BABYLON;
  17436. (function (BABYLON) {
  17437. /**
  17438. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17439. */
  17440. var Node = /** @class */ (function () {
  17441. /**
  17442. * Creates a new Node
  17443. * @param {string} name - the name and id to be given to this node
  17444. * @param {BABYLON.Scene} the scene this node will be added to
  17445. */
  17446. function Node(name, scene) {
  17447. if (scene === void 0) { scene = null; }
  17448. /**
  17449. * Gets or sets a string used to store user defined state for the node
  17450. */
  17451. this.state = "";
  17452. /**
  17453. * Gets or sets an object used to store user defined information for the node
  17454. */
  17455. this.metadata = null;
  17456. /**
  17457. * Gets or sets a boolean used to define if the node must be serialized
  17458. */
  17459. this.doNotSerialize = false;
  17460. /** @hidden */
  17461. this._isDisposed = false;
  17462. /**
  17463. * Gets a list of Animations associated with the node
  17464. */
  17465. this.animations = new Array();
  17466. this._ranges = {};
  17467. this._isEnabled = true;
  17468. this._isReady = true;
  17469. /** @hidden */
  17470. this._currentRenderId = -1;
  17471. this._parentRenderId = -1;
  17472. this._childRenderId = -1;
  17473. this._animationPropertiesOverride = null;
  17474. /**
  17475. * An event triggered when the mesh is disposed
  17476. */
  17477. this.onDisposeObservable = new BABYLON.Observable();
  17478. // Behaviors
  17479. this._behaviors = new Array();
  17480. this.name = name;
  17481. this.id = name;
  17482. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17483. this.uniqueId = this._scene.getUniqueId();
  17484. this._initCache();
  17485. }
  17486. /**
  17487. * Gets a boolean indicating if the node has been disposed
  17488. * @returns true if the node was disposed
  17489. */
  17490. Node.prototype.isDisposed = function () {
  17491. return this._isDisposed;
  17492. };
  17493. Object.defineProperty(Node.prototype, "parent", {
  17494. get: function () {
  17495. return this._parentNode;
  17496. },
  17497. /**
  17498. * Gets or sets the parent of the node
  17499. */
  17500. set: function (parent) {
  17501. if (this._parentNode === parent) {
  17502. return;
  17503. }
  17504. // Remove self from list of children of parent
  17505. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17506. var index = this._parentNode._children.indexOf(this);
  17507. if (index !== -1) {
  17508. this._parentNode._children.splice(index, 1);
  17509. }
  17510. }
  17511. // Store new parent
  17512. this._parentNode = parent;
  17513. // Add as child to new parent
  17514. if (this._parentNode) {
  17515. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17516. this._parentNode._children = new Array();
  17517. }
  17518. this._parentNode._children.push(this);
  17519. }
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17525. /**
  17526. * Gets or sets the animation properties override
  17527. */
  17528. get: function () {
  17529. if (!this._animationPropertiesOverride) {
  17530. return this._scene.animationPropertiesOverride;
  17531. }
  17532. return this._animationPropertiesOverride;
  17533. },
  17534. set: function (value) {
  17535. this._animationPropertiesOverride = value;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. /**
  17541. * Gets a string idenfifying the name of the class
  17542. * @returns "Node" string
  17543. */
  17544. Node.prototype.getClassName = function () {
  17545. return "Node";
  17546. };
  17547. Object.defineProperty(Node.prototype, "onDispose", {
  17548. /**
  17549. * Sets a callback that will be raised when the node will be disposed
  17550. */
  17551. set: function (callback) {
  17552. if (this._onDisposeObserver) {
  17553. this.onDisposeObservable.remove(this._onDisposeObserver);
  17554. }
  17555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. /**
  17561. * Gets the scene of the node
  17562. * @returns a {BABYLON.Scene}
  17563. */
  17564. Node.prototype.getScene = function () {
  17565. return this._scene;
  17566. };
  17567. /**
  17568. * Gets the engine of the node
  17569. * @returns a {BABYLON.Engine}
  17570. */
  17571. Node.prototype.getEngine = function () {
  17572. return this._scene.getEngine();
  17573. };
  17574. /**
  17575. * Attach a behavior to the node
  17576. * @see http://doc.babylonjs.com/features/behaviour
  17577. * @param behavior defines the behavior to attach
  17578. * @returns the current Node
  17579. */
  17580. Node.prototype.addBehavior = function (behavior) {
  17581. var _this = this;
  17582. var index = this._behaviors.indexOf(behavior);
  17583. if (index !== -1) {
  17584. return this;
  17585. }
  17586. behavior.init();
  17587. if (this._scene.isLoading) {
  17588. // We defer the attach when the scene will be loaded
  17589. this._scene.onDataLoadedObservable.addOnce(function () {
  17590. behavior.attach(_this);
  17591. });
  17592. }
  17593. else {
  17594. behavior.attach(this);
  17595. }
  17596. this._behaviors.push(behavior);
  17597. return this;
  17598. };
  17599. /**
  17600. * Remove an attached behavior
  17601. * @see http://doc.babylonjs.com/features/behaviour
  17602. * @param behavior defines the behavior to attach
  17603. * @returns the current Node
  17604. */
  17605. Node.prototype.removeBehavior = function (behavior) {
  17606. var index = this._behaviors.indexOf(behavior);
  17607. if (index === -1) {
  17608. return this;
  17609. }
  17610. this._behaviors[index].detach();
  17611. this._behaviors.splice(index, 1);
  17612. return this;
  17613. };
  17614. Object.defineProperty(Node.prototype, "behaviors", {
  17615. /**
  17616. * Gets the list of attached behaviors
  17617. * @see http://doc.babylonjs.com/features/behaviour
  17618. */
  17619. get: function () {
  17620. return this._behaviors;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. /**
  17626. * Gets an attached behavior by name
  17627. * @param name defines the name of the behavior to look for
  17628. * @see http://doc.babylonjs.com/features/behaviour
  17629. * @returns null if behavior was not found else the requested behavior
  17630. */
  17631. Node.prototype.getBehaviorByName = function (name) {
  17632. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17633. var behavior = _a[_i];
  17634. if (behavior.name === name) {
  17635. return behavior;
  17636. }
  17637. }
  17638. return null;
  17639. };
  17640. /**
  17641. * Returns the world matrix of the node
  17642. * @returns a matrix containing the node's world matrix
  17643. */
  17644. Node.prototype.getWorldMatrix = function () {
  17645. return BABYLON.Matrix.Identity();
  17646. };
  17647. /** @hidden */
  17648. Node.prototype._getWorldMatrixDeterminant = function () {
  17649. return 1;
  17650. };
  17651. // override it in derived class if you add new variables to the cache
  17652. // and call the parent class method
  17653. /** @hidden */
  17654. Node.prototype._initCache = function () {
  17655. this._cache = {};
  17656. this._cache.parent = undefined;
  17657. };
  17658. /** @hidden */
  17659. Node.prototype.updateCache = function (force) {
  17660. if (!force && this.isSynchronized())
  17661. return;
  17662. this._cache.parent = this.parent;
  17663. this._updateCache();
  17664. };
  17665. // override it in derived class if you add new variables to the cache
  17666. // and call the parent class method if !ignoreParentClass
  17667. /** @hidden */
  17668. Node.prototype._updateCache = function (ignoreParentClass) {
  17669. };
  17670. // override it in derived class if you add new variables to the cache
  17671. /** @hidden */
  17672. Node.prototype._isSynchronized = function () {
  17673. return true;
  17674. };
  17675. /** @hidden */
  17676. Node.prototype._markSyncedWithParent = function () {
  17677. if (this.parent) {
  17678. this._parentRenderId = this.parent._childRenderId;
  17679. }
  17680. };
  17681. /** @hidden */
  17682. Node.prototype.isSynchronizedWithParent = function () {
  17683. if (!this.parent) {
  17684. return true;
  17685. }
  17686. if (this._parentRenderId !== this.parent._childRenderId) {
  17687. return false;
  17688. }
  17689. return this.parent.isSynchronized();
  17690. };
  17691. /** @hidden */
  17692. Node.prototype.isSynchronized = function (updateCache) {
  17693. var check = this.hasNewParent();
  17694. check = check || !this.isSynchronizedWithParent();
  17695. check = check || !this._isSynchronized();
  17696. if (updateCache)
  17697. this.updateCache(true);
  17698. return !check;
  17699. };
  17700. /** @hidden */
  17701. Node.prototype.hasNewParent = function (update) {
  17702. if (this._cache.parent === this.parent)
  17703. return false;
  17704. if (update)
  17705. this._cache.parent = this.parent;
  17706. return true;
  17707. };
  17708. /**
  17709. * Is this node ready to be used/rendered
  17710. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17711. * @return true if the node is ready
  17712. */
  17713. Node.prototype.isReady = function (completeCheck) {
  17714. if (completeCheck === void 0) { completeCheck = false; }
  17715. return this._isReady;
  17716. };
  17717. /**
  17718. * Is this node enabled?
  17719. * 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
  17720. * @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
  17721. * @return whether this node (and its parent) is enabled
  17722. */
  17723. Node.prototype.isEnabled = function (checkAncestors) {
  17724. if (checkAncestors === void 0) { checkAncestors = true; }
  17725. if (checkAncestors === false) {
  17726. return this._isEnabled;
  17727. }
  17728. if (this._isEnabled === false) {
  17729. return false;
  17730. }
  17731. if (this.parent !== undefined && this.parent !== null) {
  17732. return this.parent.isEnabled(checkAncestors);
  17733. }
  17734. return true;
  17735. };
  17736. /**
  17737. * Set the enabled state of this node
  17738. * @param value defines the new enabled state
  17739. */
  17740. Node.prototype.setEnabled = function (value) {
  17741. this._isEnabled = value;
  17742. };
  17743. /**
  17744. * Is this node a descendant of the given node?
  17745. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17746. * @param ancestor defines the parent node to inspect
  17747. * @returns a boolean indicating if this node is a descendant of the given node
  17748. */
  17749. Node.prototype.isDescendantOf = function (ancestor) {
  17750. if (this.parent) {
  17751. if (this.parent === ancestor) {
  17752. return true;
  17753. }
  17754. return this.parent.isDescendantOf(ancestor);
  17755. }
  17756. return false;
  17757. };
  17758. /** @hidden */
  17759. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17760. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17761. if (!this._children) {
  17762. return;
  17763. }
  17764. for (var index = 0; index < this._children.length; index++) {
  17765. var item = this._children[index];
  17766. if (!predicate || predicate(item)) {
  17767. results.push(item);
  17768. }
  17769. if (!directDescendantsOnly) {
  17770. item._getDescendants(results, false, predicate);
  17771. }
  17772. }
  17773. };
  17774. /**
  17775. * Will return all nodes that have this node as ascendant
  17776. * @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
  17777. * @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
  17778. * @return all children nodes of all types
  17779. */
  17780. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17781. var results = new Array();
  17782. this._getDescendants(results, directDescendantsOnly, predicate);
  17783. return results;
  17784. };
  17785. /**
  17786. * Get all child-meshes of this node
  17787. * @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
  17788. * @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
  17789. * @returns an array of {BABYLON.AbstractMesh}
  17790. */
  17791. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17792. var results = [];
  17793. this._getDescendants(results, directDescendantsOnly, function (node) {
  17794. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17795. });
  17796. return results;
  17797. };
  17798. /**
  17799. * Get all child-transformNodes of this node
  17800. * @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
  17801. * @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
  17802. * @returns an array of {BABYLON.TransformNode}
  17803. */
  17804. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17805. var results = [];
  17806. this._getDescendants(results, directDescendantsOnly, function (node) {
  17807. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17808. });
  17809. return results;
  17810. };
  17811. /**
  17812. * Get all direct children of this node
  17813. * @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
  17814. * @returns an array of {BABYLON.Node}
  17815. */
  17816. Node.prototype.getChildren = function (predicate) {
  17817. return this.getDescendants(true, predicate);
  17818. };
  17819. /** @hidden */
  17820. Node.prototype._setReady = function (state) {
  17821. if (state === this._isReady) {
  17822. return;
  17823. }
  17824. if (!state) {
  17825. this._isReady = false;
  17826. return;
  17827. }
  17828. if (this.onReady) {
  17829. this.onReady(this);
  17830. }
  17831. this._isReady = true;
  17832. };
  17833. /**
  17834. * Get an animation by name
  17835. * @param name defines the name of the animation to look for
  17836. * @returns null if not found else the requested animation
  17837. */
  17838. Node.prototype.getAnimationByName = function (name) {
  17839. for (var i = 0; i < this.animations.length; i++) {
  17840. var animation = this.animations[i];
  17841. if (animation.name === name) {
  17842. return animation;
  17843. }
  17844. }
  17845. return null;
  17846. };
  17847. /**
  17848. * Creates an animation range for this node
  17849. * @param name defines the name of the range
  17850. * @param from defines the starting key
  17851. * @param to defines the end key
  17852. */
  17853. Node.prototype.createAnimationRange = function (name, from, to) {
  17854. // check name not already in use
  17855. if (!this._ranges[name]) {
  17856. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17857. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17858. if (this.animations[i]) {
  17859. this.animations[i].createRange(name, from, to);
  17860. }
  17861. }
  17862. }
  17863. };
  17864. /**
  17865. * Delete a specific animation range
  17866. * @param name defines the name of the range to delete
  17867. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17868. */
  17869. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17870. if (deleteFrames === void 0) { deleteFrames = true; }
  17871. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17872. if (this.animations[i]) {
  17873. this.animations[i].deleteRange(name, deleteFrames);
  17874. }
  17875. }
  17876. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17877. };
  17878. /**
  17879. * Get an animation range by name
  17880. * @param name defines the name of the animation range to look for
  17881. * @returns null if not found else the requested animation range
  17882. */
  17883. Node.prototype.getAnimationRange = function (name) {
  17884. return this._ranges[name];
  17885. };
  17886. /**
  17887. * Will start the animation sequence
  17888. * @param name defines the range frames for animation sequence
  17889. * @param loop defines if the animation should loop (false by default)
  17890. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17891. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17892. * @returns the object created for this animation. If range does not exist, it will return null
  17893. */
  17894. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17895. var range = this.getAnimationRange(name);
  17896. if (!range) {
  17897. return null;
  17898. }
  17899. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17900. };
  17901. /**
  17902. * Serialize animation ranges into a JSON compatible object
  17903. * @returns serialization object
  17904. */
  17905. Node.prototype.serializeAnimationRanges = function () {
  17906. var serializationRanges = [];
  17907. for (var name in this._ranges) {
  17908. var localRange = this._ranges[name];
  17909. if (!localRange) {
  17910. continue;
  17911. }
  17912. var range = {};
  17913. range.name = name;
  17914. range.from = localRange.from;
  17915. range.to = localRange.to;
  17916. serializationRanges.push(range);
  17917. }
  17918. return serializationRanges;
  17919. };
  17920. /**
  17921. * Computes the world matrix of the node
  17922. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17923. * @returns the world matrix
  17924. */
  17925. Node.prototype.computeWorldMatrix = function (force) {
  17926. return BABYLON.Matrix.Identity();
  17927. };
  17928. /**
  17929. * Releases resources associated with this node.
  17930. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17931. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17932. */
  17933. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17934. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17935. if (!doNotRecurse) {
  17936. var nodes = this.getDescendants(true);
  17937. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17938. var node = nodes_1[_i];
  17939. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17940. }
  17941. }
  17942. else {
  17943. var transformNodes = this.getChildTransformNodes(true);
  17944. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17945. var transformNode = transformNodes_1[_a];
  17946. transformNode.parent = null;
  17947. transformNode.computeWorldMatrix(true);
  17948. }
  17949. }
  17950. this.parent = null;
  17951. // Callback
  17952. this.onDisposeObservable.notifyObservers(this);
  17953. this.onDisposeObservable.clear();
  17954. // Behaviors
  17955. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17956. var behavior = _c[_b];
  17957. behavior.detach();
  17958. }
  17959. this._behaviors = [];
  17960. this._isDisposed = true;
  17961. };
  17962. /**
  17963. * Parse animation range data from a serialization object and store them into a given node
  17964. * @param node defines where to store the animation ranges
  17965. * @param parsedNode defines the serialization object to read data from
  17966. * @param scene defines the hosting scene
  17967. */
  17968. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17969. if (parsedNode.ranges) {
  17970. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17971. var data = parsedNode.ranges[index];
  17972. node.createAnimationRange(data.name, data.from, data.to);
  17973. }
  17974. }
  17975. };
  17976. __decorate([
  17977. BABYLON.serialize()
  17978. ], Node.prototype, "name", void 0);
  17979. __decorate([
  17980. BABYLON.serialize()
  17981. ], Node.prototype, "id", void 0);
  17982. __decorate([
  17983. BABYLON.serialize()
  17984. ], Node.prototype, "uniqueId", void 0);
  17985. __decorate([
  17986. BABYLON.serialize()
  17987. ], Node.prototype, "state", void 0);
  17988. __decorate([
  17989. BABYLON.serialize()
  17990. ], Node.prototype, "metadata", void 0);
  17991. return Node;
  17992. }());
  17993. BABYLON.Node = Node;
  17994. })(BABYLON || (BABYLON = {}));
  17995. //# sourceMappingURL=babylon.node.js.map
  17996. var BABYLON;
  17997. (function (BABYLON) {
  17998. var BoundingSphere = /** @class */ (function () {
  17999. /**
  18000. * Creates a new bounding sphere
  18001. * @param min defines the minimum vector (in local space)
  18002. * @param max defines the maximum vector (in local space)
  18003. */
  18004. function BoundingSphere(min, max) {
  18005. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18006. this.reConstruct(min, max);
  18007. }
  18008. /**
  18009. * Recreates the entire bounding sphere from scratch
  18010. * @param min defines the new minimum vector (in local space)
  18011. * @param max defines the new maximum vector (in local space)
  18012. */
  18013. BoundingSphere.prototype.reConstruct = function (min, max) {
  18014. this.minimum = min.clone();
  18015. this.maximum = max.clone();
  18016. var distance = BABYLON.Vector3.Distance(min, max);
  18017. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18018. this.radius = distance * 0.5;
  18019. this.centerWorld = BABYLON.Vector3.Zero();
  18020. this._update(BABYLON.Matrix.Identity());
  18021. };
  18022. // Methods
  18023. BoundingSphere.prototype._update = function (world) {
  18024. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18025. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18026. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18027. };
  18028. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18029. for (var i = 0; i < 6; i++) {
  18030. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18031. return false;
  18032. }
  18033. return true;
  18034. };
  18035. BoundingSphere.prototype.intersectsPoint = function (point) {
  18036. var x = this.centerWorld.x - point.x;
  18037. var y = this.centerWorld.y - point.y;
  18038. var z = this.centerWorld.z - point.z;
  18039. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18040. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18041. return false;
  18042. return true;
  18043. };
  18044. // Statics
  18045. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18046. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18047. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18048. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18049. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18050. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18051. return false;
  18052. return true;
  18053. };
  18054. return BoundingSphere;
  18055. }());
  18056. BABYLON.BoundingSphere = BoundingSphere;
  18057. })(BABYLON || (BABYLON = {}));
  18058. //# sourceMappingURL=babylon.boundingSphere.js.map
  18059. var BABYLON;
  18060. (function (BABYLON) {
  18061. var BoundingBox = /** @class */ (function () {
  18062. /**
  18063. * Creates a new bounding box
  18064. * @param min defines the minimum vector (in local space)
  18065. * @param max defines the maximum vector (in local space)
  18066. */
  18067. function BoundingBox(min, max) {
  18068. this.vectorsWorld = new Array();
  18069. this.reConstruct(min, max);
  18070. }
  18071. // Methods
  18072. /**
  18073. * Recreates the entire bounding box from scratch
  18074. * @param min defines the new minimum vector (in local space)
  18075. * @param max defines the new maximum vector (in local space)
  18076. */
  18077. BoundingBox.prototype.reConstruct = function (min, max) {
  18078. this.minimum = min.clone();
  18079. this.maximum = max.clone();
  18080. // Bounding vectors
  18081. this.vectors = new Array();
  18082. this.vectors.push(this.minimum.clone());
  18083. this.vectors.push(this.maximum.clone());
  18084. this.vectors.push(this.minimum.clone());
  18085. this.vectors[2].x = this.maximum.x;
  18086. this.vectors.push(this.minimum.clone());
  18087. this.vectors[3].y = this.maximum.y;
  18088. this.vectors.push(this.minimum.clone());
  18089. this.vectors[4].z = this.maximum.z;
  18090. this.vectors.push(this.maximum.clone());
  18091. this.vectors[5].z = this.minimum.z;
  18092. this.vectors.push(this.maximum.clone());
  18093. this.vectors[6].x = this.minimum.x;
  18094. this.vectors.push(this.maximum.clone());
  18095. this.vectors[7].y = this.minimum.y;
  18096. // OBB
  18097. this.center = this.maximum.add(this.minimum).scale(0.5);
  18098. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18099. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18100. // World
  18101. for (var index = 0; index < this.vectors.length; index++) {
  18102. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18103. }
  18104. this.minimumWorld = BABYLON.Vector3.Zero();
  18105. this.maximumWorld = BABYLON.Vector3.Zero();
  18106. this.centerWorld = BABYLON.Vector3.Zero();
  18107. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18108. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18109. };
  18110. BoundingBox.prototype.getWorldMatrix = function () {
  18111. return this._worldMatrix;
  18112. };
  18113. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18114. this._worldMatrix.copyFrom(matrix);
  18115. return this;
  18116. };
  18117. BoundingBox.prototype._update = function (world) {
  18118. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18119. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18120. for (var index = 0; index < this.vectors.length; index++) {
  18121. var v = this.vectorsWorld[index];
  18122. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18123. if (v.x < this.minimumWorld.x)
  18124. this.minimumWorld.x = v.x;
  18125. if (v.y < this.minimumWorld.y)
  18126. this.minimumWorld.y = v.y;
  18127. if (v.z < this.minimumWorld.z)
  18128. this.minimumWorld.z = v.z;
  18129. if (v.x > this.maximumWorld.x)
  18130. this.maximumWorld.x = v.x;
  18131. if (v.y > this.maximumWorld.y)
  18132. this.maximumWorld.y = v.y;
  18133. if (v.z > this.maximumWorld.z)
  18134. this.maximumWorld.z = v.z;
  18135. }
  18136. // Extend
  18137. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18138. this.extendSizeWorld.scaleInPlace(0.5);
  18139. // OBB
  18140. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18141. this.centerWorld.scaleInPlace(0.5);
  18142. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18143. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18144. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18145. this._worldMatrix = world;
  18146. };
  18147. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18148. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18149. };
  18150. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18151. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18152. };
  18153. BoundingBox.prototype.intersectsPoint = function (point) {
  18154. var delta = -BABYLON.Epsilon;
  18155. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18156. return false;
  18157. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18158. return false;
  18159. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18160. return false;
  18161. return true;
  18162. };
  18163. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18164. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18165. };
  18166. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18167. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18168. return false;
  18169. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18170. return false;
  18171. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18172. return false;
  18173. return true;
  18174. };
  18175. // Statics
  18176. BoundingBox.Intersects = function (box0, box1) {
  18177. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18178. return false;
  18179. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18180. return false;
  18181. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18182. return false;
  18183. return true;
  18184. };
  18185. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18186. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18187. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18188. return (num <= (sphereRadius * sphereRadius));
  18189. };
  18190. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18191. for (var p = 0; p < 6; p++) {
  18192. for (var i = 0; i < 8; i++) {
  18193. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18194. return false;
  18195. }
  18196. }
  18197. }
  18198. return true;
  18199. };
  18200. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18201. for (var p = 0; p < 6; p++) {
  18202. var inCount = 8;
  18203. for (var i = 0; i < 8; i++) {
  18204. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18205. --inCount;
  18206. }
  18207. else {
  18208. break;
  18209. }
  18210. }
  18211. if (inCount === 0)
  18212. return false;
  18213. }
  18214. return true;
  18215. };
  18216. return BoundingBox;
  18217. }());
  18218. BABYLON.BoundingBox = BoundingBox;
  18219. })(BABYLON || (BABYLON = {}));
  18220. //# sourceMappingURL=babylon.boundingBox.js.map
  18221. var BABYLON;
  18222. (function (BABYLON) {
  18223. var computeBoxExtents = function (axis, box) {
  18224. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18225. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18226. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18227. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18228. var r = r0 + r1 + r2;
  18229. return {
  18230. min: p - r,
  18231. max: p + r
  18232. };
  18233. };
  18234. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18235. var axisOverlap = function (axis, box0, box1) {
  18236. var result0 = computeBoxExtents(axis, box0);
  18237. var result1 = computeBoxExtents(axis, box1);
  18238. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18239. };
  18240. var BoundingInfo = /** @class */ (function () {
  18241. function BoundingInfo(minimum, maximum) {
  18242. this.minimum = minimum;
  18243. this.maximum = maximum;
  18244. this._isLocked = false;
  18245. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18246. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18247. }
  18248. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18249. get: function () {
  18250. return this._isLocked;
  18251. },
  18252. set: function (value) {
  18253. this._isLocked = value;
  18254. },
  18255. enumerable: true,
  18256. configurable: true
  18257. });
  18258. // Methods
  18259. BoundingInfo.prototype.update = function (world) {
  18260. if (this._isLocked) {
  18261. return;
  18262. }
  18263. this.boundingBox._update(world);
  18264. this.boundingSphere._update(world);
  18265. };
  18266. /**
  18267. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18268. * @param center New center of the bounding info
  18269. * @param extend New extend of the bounding info
  18270. */
  18271. BoundingInfo.prototype.centerOn = function (center, extend) {
  18272. this.minimum = center.subtract(extend);
  18273. this.maximum = center.add(extend);
  18274. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18275. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18276. return this;
  18277. };
  18278. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18279. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18280. return false;
  18281. return this.boundingBox.isInFrustum(frustumPlanes);
  18282. };
  18283. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18284. /**
  18285. * Gets the world distance between the min and max points of the bounding box
  18286. */
  18287. get: function () {
  18288. var boundingBox = this.boundingBox;
  18289. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18290. return size.length();
  18291. },
  18292. enumerable: true,
  18293. configurable: true
  18294. });
  18295. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18296. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18297. };
  18298. BoundingInfo.prototype._checkCollision = function (collider) {
  18299. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18300. };
  18301. BoundingInfo.prototype.intersectsPoint = function (point) {
  18302. if (!this.boundingSphere.centerWorld) {
  18303. return false;
  18304. }
  18305. if (!this.boundingSphere.intersectsPoint(point)) {
  18306. return false;
  18307. }
  18308. if (!this.boundingBox.intersectsPoint(point)) {
  18309. return false;
  18310. }
  18311. return true;
  18312. };
  18313. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18314. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18315. return false;
  18316. }
  18317. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18318. return false;
  18319. }
  18320. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18321. return false;
  18322. }
  18323. if (!precise) {
  18324. return true;
  18325. }
  18326. var box0 = this.boundingBox;
  18327. var box1 = boundingInfo.boundingBox;
  18328. if (!axisOverlap(box0.directions[0], box0, box1))
  18329. return false;
  18330. if (!axisOverlap(box0.directions[1], box0, box1))
  18331. return false;
  18332. if (!axisOverlap(box0.directions[2], box0, box1))
  18333. return false;
  18334. if (!axisOverlap(box1.directions[0], box0, box1))
  18335. return false;
  18336. if (!axisOverlap(box1.directions[1], box0, box1))
  18337. return false;
  18338. if (!axisOverlap(box1.directions[2], box0, box1))
  18339. return false;
  18340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18341. return false;
  18342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18343. return false;
  18344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18345. return false;
  18346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18353. return false;
  18354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18355. return false;
  18356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18357. return false;
  18358. return true;
  18359. };
  18360. return BoundingInfo;
  18361. }());
  18362. BABYLON.BoundingInfo = BoundingInfo;
  18363. })(BABYLON || (BABYLON = {}));
  18364. //# sourceMappingURL=babylon.boundingInfo.js.map
  18365. var BABYLON;
  18366. (function (BABYLON) {
  18367. var TransformNode = /** @class */ (function (_super) {
  18368. __extends(TransformNode, _super);
  18369. function TransformNode(name, scene, isPure) {
  18370. if (scene === void 0) { scene = null; }
  18371. if (isPure === void 0) { isPure = true; }
  18372. var _this = _super.call(this, name, scene) || this;
  18373. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18374. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18375. _this._up = new BABYLON.Vector3(0, 1, 0);
  18376. _this._right = new BABYLON.Vector3(1, 0, 0);
  18377. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18378. // Properties
  18379. _this._rotation = BABYLON.Vector3.Zero();
  18380. _this._scaling = BABYLON.Vector3.One();
  18381. _this._isDirty = false;
  18382. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18383. _this.scalingDeterminant = 1;
  18384. _this.infiniteDistance = false;
  18385. /**
  18386. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18387. * By default the system will update normals to compensate
  18388. */
  18389. _this.ignoreNonUniformScaling = false;
  18390. _this.position = BABYLON.Vector3.Zero();
  18391. _this._localWorld = BABYLON.Matrix.Zero();
  18392. _this._worldMatrix = BABYLON.Matrix.Zero();
  18393. _this._worldMatrixDeterminant = 0;
  18394. _this._absolutePosition = BABYLON.Vector3.Zero();
  18395. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18396. _this._postMultiplyPivotMatrix = false;
  18397. _this._isWorldMatrixFrozen = false;
  18398. /**
  18399. * An event triggered after the world matrix is updated
  18400. */
  18401. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18402. _this._nonUniformScaling = false;
  18403. if (isPure) {
  18404. _this.getScene().addTransformNode(_this);
  18405. }
  18406. return _this;
  18407. }
  18408. /**
  18409. * Gets a string idenfifying the name of the class
  18410. * @returns "TransformNode" string
  18411. */
  18412. TransformNode.prototype.getClassName = function () {
  18413. return "TransformNode";
  18414. };
  18415. Object.defineProperty(TransformNode.prototype, "rotation", {
  18416. /**
  18417. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18418. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18419. * Default : (0.0, 0.0, 0.0)
  18420. */
  18421. get: function () {
  18422. return this._rotation;
  18423. },
  18424. set: function (newRotation) {
  18425. this._rotation = newRotation;
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(TransformNode.prototype, "scaling", {
  18431. /**
  18432. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18433. * Default : (1.0, 1.0, 1.0)
  18434. */
  18435. get: function () {
  18436. return this._scaling;
  18437. },
  18438. /**
  18439. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18440. * Default : (1.0, 1.0, 1.0)
  18441. */
  18442. set: function (newScaling) {
  18443. this._scaling = newScaling;
  18444. },
  18445. enumerable: true,
  18446. configurable: true
  18447. });
  18448. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18449. /**
  18450. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18451. * It's null by default.
  18452. * 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)
  18453. */
  18454. get: function () {
  18455. return this._rotationQuaternion;
  18456. },
  18457. set: function (quaternion) {
  18458. this._rotationQuaternion = quaternion;
  18459. //reset the rotation vector.
  18460. if (quaternion && this.rotation.length()) {
  18461. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18462. }
  18463. },
  18464. enumerable: true,
  18465. configurable: true
  18466. });
  18467. Object.defineProperty(TransformNode.prototype, "forward", {
  18468. /**
  18469. * The forward direction of that transform in world space.
  18470. */
  18471. get: function () {
  18472. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. Object.defineProperty(TransformNode.prototype, "up", {
  18478. /**
  18479. * The up direction of that transform in world space.
  18480. */
  18481. get: function () {
  18482. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(TransformNode.prototype, "right", {
  18488. /**
  18489. * The right direction of that transform in world space.
  18490. */
  18491. get: function () {
  18492. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18493. },
  18494. enumerable: true,
  18495. configurable: true
  18496. });
  18497. /**
  18498. * Returns the latest update of the World matrix
  18499. * Returns a Matrix.
  18500. */
  18501. TransformNode.prototype.getWorldMatrix = function () {
  18502. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18503. this.computeWorldMatrix();
  18504. }
  18505. return this._worldMatrix;
  18506. };
  18507. /** @hidden */
  18508. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18509. return this._worldMatrixDeterminant;
  18510. };
  18511. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18512. /**
  18513. * Returns directly the latest state of the mesh World matrix.
  18514. * A Matrix is returned.
  18515. */
  18516. get: function () {
  18517. return this._worldMatrix;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. /**
  18523. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18524. * Returns the TransformNode.
  18525. */
  18526. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18527. this._poseMatrix.copyFrom(matrix);
  18528. return this;
  18529. };
  18530. /**
  18531. * Returns the mesh Pose matrix.
  18532. * Returned object : Matrix
  18533. */
  18534. TransformNode.prototype.getPoseMatrix = function () {
  18535. return this._poseMatrix;
  18536. };
  18537. TransformNode.prototype._isSynchronized = function () {
  18538. if (this._isDirty) {
  18539. return false;
  18540. }
  18541. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18542. return false;
  18543. if (this._cache.pivotMatrixUpdated) {
  18544. return false;
  18545. }
  18546. if (this.infiniteDistance) {
  18547. return false;
  18548. }
  18549. if (!this._cache.position.equals(this.position))
  18550. return false;
  18551. if (this.rotationQuaternion) {
  18552. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18553. return false;
  18554. }
  18555. if (!this._cache.rotation.equals(this.rotation))
  18556. return false;
  18557. if (!this._cache.scaling.equals(this.scaling))
  18558. return false;
  18559. return true;
  18560. };
  18561. TransformNode.prototype._initCache = function () {
  18562. _super.prototype._initCache.call(this);
  18563. this._cache.localMatrixUpdated = false;
  18564. this._cache.position = BABYLON.Vector3.Zero();
  18565. this._cache.scaling = BABYLON.Vector3.Zero();
  18566. this._cache.rotation = BABYLON.Vector3.Zero();
  18567. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18568. this._cache.billboardMode = -1;
  18569. };
  18570. TransformNode.prototype.markAsDirty = function (property) {
  18571. if (property === "rotation") {
  18572. this.rotationQuaternion = null;
  18573. }
  18574. this._currentRenderId = Number.MAX_VALUE;
  18575. this._isDirty = true;
  18576. return this;
  18577. };
  18578. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18579. /**
  18580. * Returns the current mesh absolute position.
  18581. * Retuns a Vector3.
  18582. */
  18583. get: function () {
  18584. return this._absolutePosition;
  18585. },
  18586. enumerable: true,
  18587. configurable: true
  18588. });
  18589. /**
  18590. * Sets a new matrix to apply before all other transformation
  18591. * @param matrix defines the transform matrix
  18592. * @returns the current TransformNode
  18593. */
  18594. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18595. return this.setPivotMatrix(matrix, false);
  18596. };
  18597. /**
  18598. * Sets a new pivot matrix to the current node
  18599. * @param matrix defines the new pivot matrix to use
  18600. * @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
  18601. * @returns the current TransformNode
  18602. */
  18603. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18604. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18605. this._pivotMatrix = matrix.clone();
  18606. this._cache.pivotMatrixUpdated = true;
  18607. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18608. if (this._postMultiplyPivotMatrix) {
  18609. if (!this._pivotMatrixInverse) {
  18610. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18611. }
  18612. else {
  18613. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18614. }
  18615. }
  18616. return this;
  18617. };
  18618. /**
  18619. * Returns the mesh pivot matrix.
  18620. * Default : Identity.
  18621. * A Matrix is returned.
  18622. */
  18623. TransformNode.prototype.getPivotMatrix = function () {
  18624. return this._pivotMatrix;
  18625. };
  18626. /**
  18627. * Prevents the World matrix to be computed any longer.
  18628. * Returns the TransformNode.
  18629. */
  18630. TransformNode.prototype.freezeWorldMatrix = function () {
  18631. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18632. this.computeWorldMatrix(true);
  18633. this._isWorldMatrixFrozen = true;
  18634. return this;
  18635. };
  18636. /**
  18637. * Allows back the World matrix computation.
  18638. * Returns the TransformNode.
  18639. */
  18640. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18641. this._isWorldMatrixFrozen = false;
  18642. this.computeWorldMatrix(true);
  18643. return this;
  18644. };
  18645. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18646. /**
  18647. * True if the World matrix has been frozen.
  18648. * Returns a boolean.
  18649. */
  18650. get: function () {
  18651. return this._isWorldMatrixFrozen;
  18652. },
  18653. enumerable: true,
  18654. configurable: true
  18655. });
  18656. /**
  18657. * Retuns the mesh absolute position in the World.
  18658. * Returns a Vector3.
  18659. */
  18660. TransformNode.prototype.getAbsolutePosition = function () {
  18661. this.computeWorldMatrix();
  18662. return this._absolutePosition;
  18663. };
  18664. /**
  18665. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18666. * Returns the TransformNode.
  18667. */
  18668. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18669. if (!absolutePosition) {
  18670. return this;
  18671. }
  18672. var absolutePositionX;
  18673. var absolutePositionY;
  18674. var absolutePositionZ;
  18675. if (absolutePosition.x === undefined) {
  18676. if (arguments.length < 3) {
  18677. return this;
  18678. }
  18679. absolutePositionX = arguments[0];
  18680. absolutePositionY = arguments[1];
  18681. absolutePositionZ = arguments[2];
  18682. }
  18683. else {
  18684. absolutePositionX = absolutePosition.x;
  18685. absolutePositionY = absolutePosition.y;
  18686. absolutePositionZ = absolutePosition.z;
  18687. }
  18688. if (this.parent) {
  18689. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18690. invertParentWorldMatrix.invert();
  18691. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18692. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18693. }
  18694. else {
  18695. this.position.x = absolutePositionX;
  18696. this.position.y = absolutePositionY;
  18697. this.position.z = absolutePositionZ;
  18698. }
  18699. return this;
  18700. };
  18701. /**
  18702. * Sets the mesh position in its local space.
  18703. * Returns the TransformNode.
  18704. */
  18705. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18706. this.computeWorldMatrix();
  18707. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18708. return this;
  18709. };
  18710. /**
  18711. * Returns the mesh position in the local space from the current World matrix values.
  18712. * Returns a new Vector3.
  18713. */
  18714. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18715. this.computeWorldMatrix();
  18716. var invLocalWorldMatrix = this._localWorld.clone();
  18717. invLocalWorldMatrix.invert();
  18718. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18719. };
  18720. /**
  18721. * Translates the mesh along the passed Vector3 in its local space.
  18722. * Returns the TransformNode.
  18723. */
  18724. TransformNode.prototype.locallyTranslate = function (vector3) {
  18725. this.computeWorldMatrix(true);
  18726. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18727. return this;
  18728. };
  18729. /**
  18730. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18731. * @param targetPoint the position (must be in same space as current mesh) to look at
  18732. * @param yawCor optional yaw (y-axis) correction in radians
  18733. * @param pitchCor optional pitch (x-axis) correction in radians
  18734. * @param rollCor optional roll (z-axis) correction in radians
  18735. * @param space the choosen space of the target
  18736. * @returns the TransformNode.
  18737. */
  18738. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18739. if (yawCor === void 0) { yawCor = 0; }
  18740. if (pitchCor === void 0) { pitchCor = 0; }
  18741. if (rollCor === void 0) { rollCor = 0; }
  18742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18743. var dv = TransformNode._lookAtVectorCache;
  18744. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18745. targetPoint.subtractToRef(pos, dv);
  18746. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18747. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18748. var pitch = Math.atan2(dv.y, len);
  18749. if (this.rotationQuaternion) {
  18750. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18751. }
  18752. else {
  18753. this.rotation.x = pitch + pitchCor;
  18754. this.rotation.y = yaw + yawCor;
  18755. this.rotation.z = rollCor;
  18756. }
  18757. return this;
  18758. };
  18759. /**
  18760. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18761. * This Vector3 is expressed in the World space.
  18762. */
  18763. TransformNode.prototype.getDirection = function (localAxis) {
  18764. var result = BABYLON.Vector3.Zero();
  18765. this.getDirectionToRef(localAxis, result);
  18766. return result;
  18767. };
  18768. /**
  18769. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18770. * localAxis is expressed in the mesh local space.
  18771. * result is computed in the Wordl space from the mesh World matrix.
  18772. * Returns the TransformNode.
  18773. */
  18774. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18775. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18776. return this;
  18777. };
  18778. /**
  18779. * Sets a new pivot point to the current node
  18780. * @param point defines the new pivot point to use
  18781. * @param space defines if the point is in world or local space (local by default)
  18782. * @returns the current TransformNode
  18783. */
  18784. TransformNode.prototype.setPivotPoint = function (point, space) {
  18785. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18786. if (this.getScene().getRenderId() == 0) {
  18787. this.computeWorldMatrix(true);
  18788. }
  18789. var wm = this.getWorldMatrix();
  18790. if (space == BABYLON.Space.WORLD) {
  18791. var tmat = BABYLON.Tmp.Matrix[0];
  18792. wm.invertToRef(tmat);
  18793. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18794. }
  18795. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18796. };
  18797. /**
  18798. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18799. */
  18800. TransformNode.prototype.getPivotPoint = function () {
  18801. var point = BABYLON.Vector3.Zero();
  18802. this.getPivotPointToRef(point);
  18803. return point;
  18804. };
  18805. /**
  18806. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18807. * Returns the TransformNode.
  18808. */
  18809. TransformNode.prototype.getPivotPointToRef = function (result) {
  18810. result.x = -this._pivotMatrix.m[12];
  18811. result.y = -this._pivotMatrix.m[13];
  18812. result.z = -this._pivotMatrix.m[14];
  18813. return this;
  18814. };
  18815. /**
  18816. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18817. */
  18818. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18819. var point = BABYLON.Vector3.Zero();
  18820. this.getAbsolutePivotPointToRef(point);
  18821. return point;
  18822. };
  18823. /**
  18824. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18825. * Returns the TransformNode.
  18826. */
  18827. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18828. result.x = this._pivotMatrix.m[12];
  18829. result.y = this._pivotMatrix.m[13];
  18830. result.z = this._pivotMatrix.m[14];
  18831. this.getPivotPointToRef(result);
  18832. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18833. return this;
  18834. };
  18835. /**
  18836. * Defines the passed node as the parent of the current node.
  18837. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18838. * Returns the TransformNode.
  18839. */
  18840. TransformNode.prototype.setParent = function (node) {
  18841. if (node === null) {
  18842. var rotation = BABYLON.Tmp.Quaternion[0];
  18843. var position = BABYLON.Tmp.Vector3[0];
  18844. var scale = BABYLON.Tmp.Vector3[1];
  18845. if (this.parent && this.parent.computeWorldMatrix) {
  18846. this.parent.computeWorldMatrix(true);
  18847. }
  18848. this.computeWorldMatrix(true);
  18849. this.getWorldMatrix().decompose(scale, rotation, position);
  18850. if (this.rotationQuaternion) {
  18851. this.rotationQuaternion.copyFrom(rotation);
  18852. }
  18853. else {
  18854. rotation.toEulerAnglesToRef(this.rotation);
  18855. }
  18856. this.scaling.x = scale.x;
  18857. this.scaling.y = scale.y;
  18858. this.scaling.z = scale.z;
  18859. this.position.x = position.x;
  18860. this.position.y = position.y;
  18861. this.position.z = position.z;
  18862. }
  18863. else {
  18864. var rotation = BABYLON.Tmp.Quaternion[0];
  18865. var position = BABYLON.Tmp.Vector3[0];
  18866. var scale = BABYLON.Tmp.Vector3[1];
  18867. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18868. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18869. this.computeWorldMatrix(true);
  18870. node.computeWorldMatrix(true);
  18871. node.getWorldMatrix().invertToRef(invParentMatrix);
  18872. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18873. diffMatrix.decompose(scale, rotation, position);
  18874. if (this.rotationQuaternion) {
  18875. this.rotationQuaternion.copyFrom(rotation);
  18876. }
  18877. else {
  18878. rotation.toEulerAnglesToRef(this.rotation);
  18879. }
  18880. this.position.x = position.x;
  18881. this.position.y = position.y;
  18882. this.position.z = position.z;
  18883. this.scaling.x = scale.x;
  18884. this.scaling.y = scale.y;
  18885. this.scaling.z = scale.z;
  18886. }
  18887. this.parent = node;
  18888. return this;
  18889. };
  18890. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18891. get: function () {
  18892. return this._nonUniformScaling;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18898. if (this._nonUniformScaling === value) {
  18899. return false;
  18900. }
  18901. this._nonUniformScaling = value;
  18902. return true;
  18903. };
  18904. /**
  18905. * Attach the current TransformNode to another TransformNode associated with a bone
  18906. * @param bone Bone affecting the TransformNode
  18907. * @param affectedTransformNode TransformNode associated with the bone
  18908. */
  18909. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18910. this._transformToBoneReferal = affectedTransformNode;
  18911. this.parent = bone;
  18912. if (bone.getWorldMatrix().determinant() < 0) {
  18913. this.scalingDeterminant *= -1;
  18914. }
  18915. return this;
  18916. };
  18917. TransformNode.prototype.detachFromBone = function () {
  18918. if (!this.parent) {
  18919. return this;
  18920. }
  18921. if (this.parent.getWorldMatrix().determinant() < 0) {
  18922. this.scalingDeterminant *= -1;
  18923. }
  18924. this._transformToBoneReferal = null;
  18925. this.parent = null;
  18926. return this;
  18927. };
  18928. /**
  18929. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18930. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18931. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18932. * The passed axis is also normalized.
  18933. * Returns the TransformNode.
  18934. */
  18935. TransformNode.prototype.rotate = function (axis, amount, space) {
  18936. axis.normalize();
  18937. if (!this.rotationQuaternion) {
  18938. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18939. this.rotation = BABYLON.Vector3.Zero();
  18940. }
  18941. var rotationQuaternion;
  18942. if (!space || space === BABYLON.Space.LOCAL) {
  18943. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18944. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18945. }
  18946. else {
  18947. if (this.parent) {
  18948. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18949. invertParentWorldMatrix.invert();
  18950. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18951. }
  18952. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18953. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18954. }
  18955. return this;
  18956. };
  18957. /**
  18958. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18959. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18960. * The passed axis is also normalized.
  18961. * Returns the TransformNode.
  18962. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18963. */
  18964. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18965. axis.normalize();
  18966. if (!this.rotationQuaternion) {
  18967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18968. this.rotation.copyFromFloats(0, 0, 0);
  18969. }
  18970. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18971. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18972. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18973. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18974. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18975. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18976. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18977. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18978. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18979. return this;
  18980. };
  18981. /**
  18982. * Translates the mesh along the axis vector for the passed distance in the given space.
  18983. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18984. * Returns the TransformNode.
  18985. */
  18986. TransformNode.prototype.translate = function (axis, distance, space) {
  18987. var displacementVector = axis.scale(distance);
  18988. if (!space || space === BABYLON.Space.LOCAL) {
  18989. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18990. this.setPositionWithLocalVector(tempV3);
  18991. }
  18992. else {
  18993. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18994. }
  18995. return this;
  18996. };
  18997. /**
  18998. * Adds a rotation step to the mesh current rotation.
  18999. * x, y, z are Euler angles expressed in radians.
  19000. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19001. * This means this rotation is made in the mesh local space only.
  19002. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19003. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19004. * ```javascript
  19005. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19006. * ```
  19007. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19008. * 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.
  19009. * Returns the TransformNode.
  19010. */
  19011. TransformNode.prototype.addRotation = function (x, y, z) {
  19012. var rotationQuaternion;
  19013. if (this.rotationQuaternion) {
  19014. rotationQuaternion = this.rotationQuaternion;
  19015. }
  19016. else {
  19017. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19018. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19019. }
  19020. var accumulation = BABYLON.Tmp.Quaternion[0];
  19021. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19022. rotationQuaternion.multiplyInPlace(accumulation);
  19023. if (!this.rotationQuaternion) {
  19024. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19025. }
  19026. return this;
  19027. };
  19028. /**
  19029. * Computes the mesh World matrix and returns it.
  19030. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19031. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19032. * If the parameter `force`is set to `true`, the actual computation is done.
  19033. * Returns the mesh World Matrix.
  19034. */
  19035. TransformNode.prototype.computeWorldMatrix = function (force) {
  19036. if (this._isWorldMatrixFrozen) {
  19037. return this._worldMatrix;
  19038. }
  19039. if (!force && this.isSynchronized(true)) {
  19040. this._currentRenderId = this.getScene().getRenderId();
  19041. return this._worldMatrix;
  19042. }
  19043. this._cache.position.copyFrom(this.position);
  19044. this._cache.scaling.copyFrom(this.scaling);
  19045. this._cache.pivotMatrixUpdated = false;
  19046. this._cache.billboardMode = this.billboardMode;
  19047. this._currentRenderId = this.getScene().getRenderId();
  19048. this._childRenderId = this.getScene().getRenderId();
  19049. this._isDirty = false;
  19050. // Scaling
  19051. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19052. // Rotation
  19053. //rotate, if quaternion is set and rotation was used
  19054. if (this.rotationQuaternion) {
  19055. var len = this.rotation.length();
  19056. if (len) {
  19057. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19058. this.rotation.copyFromFloats(0, 0, 0);
  19059. }
  19060. }
  19061. if (this.rotationQuaternion) {
  19062. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19063. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19064. }
  19065. else {
  19066. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19067. this._cache.rotation.copyFrom(this.rotation);
  19068. }
  19069. // Translation
  19070. var camera = this.getScene().activeCamera;
  19071. if (this.infiniteDistance && !this.parent && camera) {
  19072. var cameraWorldMatrix = camera.getWorldMatrix();
  19073. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19074. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19075. }
  19076. else {
  19077. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19078. }
  19079. // Composing transformations
  19080. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19081. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19082. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19083. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19084. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19085. // Need to decompose each rotation here
  19086. var currentPosition = BABYLON.Tmp.Vector3[3];
  19087. if (this.parent && this.parent.getWorldMatrix) {
  19088. if (this._transformToBoneReferal) {
  19089. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19090. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19091. }
  19092. else {
  19093. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19094. }
  19095. }
  19096. else {
  19097. currentPosition.copyFrom(this.position);
  19098. }
  19099. currentPosition.subtractInPlace(camera.globalPosition);
  19100. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19101. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19102. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19103. }
  19104. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19105. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19106. }
  19107. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19108. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19109. }
  19110. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19111. }
  19112. else {
  19113. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19114. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19115. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19116. }
  19117. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19118. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19119. }
  19120. // Local world
  19121. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19122. // Parent
  19123. if (this.parent && this.parent.getWorldMatrix) {
  19124. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19125. if (this._transformToBoneReferal) {
  19126. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19127. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19128. }
  19129. else {
  19130. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19131. }
  19132. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19133. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19134. this._worldMatrix.copyFrom(this._localWorld);
  19135. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19136. }
  19137. else {
  19138. if (this._transformToBoneReferal) {
  19139. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19140. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19141. }
  19142. else {
  19143. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19144. }
  19145. }
  19146. this._markSyncedWithParent();
  19147. }
  19148. else {
  19149. this._worldMatrix.copyFrom(this._localWorld);
  19150. }
  19151. // Post multiply inverse of pivotMatrix
  19152. if (this._postMultiplyPivotMatrix) {
  19153. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19154. }
  19155. // Normal matrix
  19156. if (!this.ignoreNonUniformScaling) {
  19157. if (this.scaling.isNonUniform) {
  19158. this._updateNonUniformScalingState(true);
  19159. }
  19160. else if (this.parent && this.parent._nonUniformScaling) {
  19161. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19162. }
  19163. else {
  19164. this._updateNonUniformScalingState(false);
  19165. }
  19166. }
  19167. else {
  19168. this._updateNonUniformScalingState(false);
  19169. }
  19170. this._afterComputeWorldMatrix();
  19171. // Absolute position
  19172. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19173. // Callbacks
  19174. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19175. if (!this._poseMatrix) {
  19176. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19177. }
  19178. // Cache the determinant
  19179. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19180. return this._worldMatrix;
  19181. };
  19182. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19183. };
  19184. /**
  19185. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19186. * @param func: callback function to add
  19187. *
  19188. * Returns the TransformNode.
  19189. */
  19190. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19191. this.onAfterWorldMatrixUpdateObservable.add(func);
  19192. return this;
  19193. };
  19194. /**
  19195. * Removes a registered callback function.
  19196. * Returns the TransformNode.
  19197. */
  19198. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19199. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19200. return this;
  19201. };
  19202. /**
  19203. * Clone the current transform node
  19204. * Returns the new transform node
  19205. * @param name Name of the new clone
  19206. * @param newParent New parent for the clone
  19207. * @param doNotCloneChildren Do not clone children hierarchy
  19208. */
  19209. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19210. var _this = this;
  19211. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19212. result.name = name;
  19213. result.id = name;
  19214. if (newParent) {
  19215. result.parent = newParent;
  19216. }
  19217. if (!doNotCloneChildren) {
  19218. // Children
  19219. var directDescendants = this.getDescendants(true);
  19220. for (var index = 0; index < directDescendants.length; index++) {
  19221. var child = directDescendants[index];
  19222. if (child.clone) {
  19223. child.clone(name + "." + child.name, result);
  19224. }
  19225. }
  19226. }
  19227. return result;
  19228. };
  19229. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19230. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19231. serializationObject.type = this.getClassName();
  19232. // Parent
  19233. if (this.parent) {
  19234. serializationObject.parentId = this.parent.id;
  19235. }
  19236. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19237. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19238. }
  19239. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19240. serializationObject.isEnabled = this.isEnabled();
  19241. // Parent
  19242. if (this.parent) {
  19243. serializationObject.parentId = this.parent.id;
  19244. }
  19245. return serializationObject;
  19246. };
  19247. // Statics
  19248. /**
  19249. * Returns a new TransformNode object parsed from the source provided.
  19250. * The parameter `parsedMesh` is the source.
  19251. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19252. */
  19253. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19254. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19255. if (BABYLON.Tags) {
  19256. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19257. }
  19258. if (parsedTransformNode.localMatrix) {
  19259. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19260. }
  19261. else if (parsedTransformNode.pivotMatrix) {
  19262. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19263. }
  19264. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19265. // Parent
  19266. if (parsedTransformNode.parentId) {
  19267. transformNode._waitingParentId = parsedTransformNode.parentId;
  19268. }
  19269. return transformNode;
  19270. };
  19271. /**
  19272. * Releases resources associated with this transform node.
  19273. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19274. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19275. */
  19276. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19277. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19278. // Animations
  19279. this.getScene().stopAnimation(this);
  19280. // Remove from scene
  19281. this.getScene().removeTransformNode(this);
  19282. this.onAfterWorldMatrixUpdateObservable.clear();
  19283. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19284. };
  19285. // Statics
  19286. TransformNode.BILLBOARDMODE_NONE = 0;
  19287. TransformNode.BILLBOARDMODE_X = 1;
  19288. TransformNode.BILLBOARDMODE_Y = 2;
  19289. TransformNode.BILLBOARDMODE_Z = 4;
  19290. TransformNode.BILLBOARDMODE_ALL = 7;
  19291. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19292. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19293. __decorate([
  19294. BABYLON.serializeAsVector3()
  19295. ], TransformNode.prototype, "_rotation", void 0);
  19296. __decorate([
  19297. BABYLON.serializeAsQuaternion()
  19298. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19299. __decorate([
  19300. BABYLON.serializeAsVector3()
  19301. ], TransformNode.prototype, "_scaling", void 0);
  19302. __decorate([
  19303. BABYLON.serialize()
  19304. ], TransformNode.prototype, "billboardMode", void 0);
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], TransformNode.prototype, "infiniteDistance", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19314. __decorate([
  19315. BABYLON.serializeAsVector3()
  19316. ], TransformNode.prototype, "position", void 0);
  19317. return TransformNode;
  19318. }(BABYLON.Node));
  19319. BABYLON.TransformNode = TransformNode;
  19320. })(BABYLON || (BABYLON = {}));
  19321. //# sourceMappingURL=babylon.transformNode.js.map
  19322. var BABYLON;
  19323. (function (BABYLON) {
  19324. /**
  19325. * Class used to store all common mesh properties
  19326. */
  19327. var AbstractMesh = /** @class */ (function (_super) {
  19328. __extends(AbstractMesh, _super);
  19329. // Constructor
  19330. /**
  19331. * Creates a new AbstractMesh
  19332. * @param name defines the name of the mesh
  19333. * @param scene defines the hosting scene
  19334. */
  19335. function AbstractMesh(name, scene) {
  19336. if (scene === void 0) { scene = null; }
  19337. var _this = _super.call(this, name, scene, false) || this;
  19338. _this._facetNb = 0; // facet number
  19339. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19340. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19341. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19342. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19343. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19344. _this._subDiv = {
  19345. max: 1,
  19346. X: 1,
  19347. Y: 1,
  19348. Z: 1
  19349. };
  19350. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19351. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19352. // Events
  19353. /**
  19354. * An event triggered when this mesh collides with another one
  19355. */
  19356. _this.onCollideObservable = new BABYLON.Observable();
  19357. /**
  19358. * An event triggered when the collision's position changes
  19359. */
  19360. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19361. /**
  19362. * An event triggered when material is changed
  19363. */
  19364. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19365. // Properties
  19366. /**
  19367. * Gets or sets the orientation for POV movement & rotation
  19368. */
  19369. _this.definedFacingForward = true;
  19370. /**
  19371. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19372. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19373. * * 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.
  19374. * @see http://doc.babylonjs.com/features/occlusionquery
  19375. */
  19376. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19377. /**
  19378. * 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:
  19379. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19380. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19381. * * 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.
  19382. * @see http://doc.babylonjs.com/features/occlusionquery
  19383. */
  19384. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19385. /**
  19386. * 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.
  19387. * The default value is -1 which means don't break the query and wait till the result
  19388. * @see http://doc.babylonjs.com/features/occlusionquery
  19389. */
  19390. _this.occlusionRetryCount = -1;
  19391. _this._occlusionInternalRetryCounter = 0;
  19392. _this._isOccluded = false;
  19393. _this._isOcclusionQueryInProgress = false;
  19394. _this._visibility = 1.0;
  19395. /** Gets or sets the alpha index used to sort transparent meshes
  19396. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19397. */
  19398. _this.alphaIndex = Number.MAX_VALUE;
  19399. /**
  19400. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19401. */
  19402. _this.isVisible = true;
  19403. /**
  19404. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19405. */
  19406. _this.isPickable = true;
  19407. /**
  19408. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19409. */
  19410. _this.showBoundingBox = false;
  19411. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19412. _this.showSubMeshesBoundingBox = false;
  19413. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19414. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19415. */
  19416. _this.isBlocker = false;
  19417. /**
  19418. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19419. */
  19420. _this.enablePointerMoveEvents = false;
  19421. /**
  19422. * Specifies the rendering group id for this mesh (0 by default)
  19423. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19424. */
  19425. _this.renderingGroupId = 0;
  19426. _this._receiveShadows = false;
  19427. /**
  19428. * Gets or sets a boolean indicating if the outline must be rendered as well
  19429. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19430. */
  19431. _this.renderOutline = false;
  19432. /** Defines color to use when rendering outline */
  19433. _this.outlineColor = BABYLON.Color3.Red();
  19434. /** Define width to use when rendering outline */
  19435. _this.outlineWidth = 0.02;
  19436. /**
  19437. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19438. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19439. */
  19440. _this.renderOverlay = false;
  19441. /** Defines color to use when rendering overlay */
  19442. _this.overlayColor = BABYLON.Color3.Red();
  19443. /** Defines alpha to use when rendering overlay */
  19444. _this.overlayAlpha = 0.5;
  19445. _this._hasVertexAlpha = false;
  19446. _this._useVertexColors = true;
  19447. _this._computeBonesUsingShaders = true;
  19448. _this._numBoneInfluencers = 4;
  19449. _this._applyFog = true;
  19450. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19451. _this.useOctreeForRenderingSelection = true;
  19452. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19453. _this.useOctreeForPicking = true;
  19454. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19455. _this.useOctreeForCollisions = true;
  19456. _this._layerMask = 0x0FFFFFFF;
  19457. /**
  19458. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19459. */
  19460. _this.alwaysSelectAsActiveMesh = false;
  19461. /**
  19462. * Gets or sets the current action manager
  19463. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19464. */
  19465. _this.actionManager = null;
  19466. /**
  19467. * Gets or sets impostor used for physic simulation
  19468. * @see http://doc.babylonjs.com/features/physics_engine
  19469. */
  19470. _this.physicsImpostor = null;
  19471. // Collisions
  19472. _this._checkCollisions = false;
  19473. _this._collisionMask = -1;
  19474. _this._collisionGroup = -1;
  19475. /**
  19476. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19477. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19478. */
  19479. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19480. /**
  19481. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19482. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19483. */
  19484. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19485. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19486. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19487. // Edges
  19488. /**
  19489. * Defines edge width used when edgesRenderer is enabled
  19490. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19491. */
  19492. _this.edgesWidth = 1;
  19493. /**
  19494. * Defines edge color used when edgesRenderer is enabled
  19495. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19496. */
  19497. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19498. // Cache
  19499. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19500. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19501. /** @hidden */
  19502. _this._renderId = 0;
  19503. /** @hidden */
  19504. _this._intersectionsInProgress = new Array();
  19505. /** @hidden */
  19506. _this._unIndexed = false;
  19507. /** @hidden */
  19508. _this._lightSources = new Array();
  19509. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19510. if (collidedMesh === void 0) { collidedMesh = null; }
  19511. //TODO move this to the collision coordinator!
  19512. if (_this.getScene().workerCollisions)
  19513. newPosition.multiplyInPlace(_this._collider._radius);
  19514. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19515. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19516. _this.position.addInPlace(_this._diffPositionForCollisions);
  19517. }
  19518. if (collidedMesh) {
  19519. _this.onCollideObservable.notifyObservers(collidedMesh);
  19520. }
  19521. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19522. };
  19523. _this.getScene().addMesh(_this);
  19524. _this._resyncLightSources();
  19525. return _this;
  19526. }
  19527. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19528. /**
  19529. * No billboard
  19530. */
  19531. get: function () {
  19532. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19538. /** Billboard on X axis */
  19539. get: function () {
  19540. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19546. /** Billboard on Y axis */
  19547. get: function () {
  19548. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19554. /** Billboard on Z axis */
  19555. get: function () {
  19556. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19562. /** Billboard on all axes */
  19563. get: function () {
  19564. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19570. /**
  19571. * Gets the number of facets in the mesh
  19572. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19573. */
  19574. get: function () {
  19575. return this._facetNb;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19581. /**
  19582. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19583. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19584. */
  19585. get: function () {
  19586. return this._partitioningSubdivisions;
  19587. },
  19588. set: function (nb) {
  19589. this._partitioningSubdivisions = nb;
  19590. },
  19591. enumerable: true,
  19592. configurable: true
  19593. });
  19594. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19595. /**
  19596. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19597. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19598. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19599. */
  19600. get: function () {
  19601. return this._partitioningBBoxRatio;
  19602. },
  19603. set: function (ratio) {
  19604. this._partitioningBBoxRatio = ratio;
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19610. /**
  19611. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19612. * Works only for updatable meshes.
  19613. * Doesn't work with multi-materials
  19614. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19615. */
  19616. get: function () {
  19617. return this._facetDepthSort;
  19618. },
  19619. set: function (sort) {
  19620. this._facetDepthSort = sort;
  19621. },
  19622. enumerable: true,
  19623. configurable: true
  19624. });
  19625. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19626. /**
  19627. * The location (Vector3) where the facet depth sort must be computed from.
  19628. * By default, the active camera position.
  19629. * Used only when facet depth sort is enabled
  19630. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19631. */
  19632. get: function () {
  19633. return this._facetDepthSortFrom;
  19634. },
  19635. set: function (location) {
  19636. this._facetDepthSortFrom = location;
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19642. /**
  19643. * gets a boolean indicating if facetData is enabled
  19644. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19645. */
  19646. get: function () {
  19647. return this._facetDataEnabled;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. /** @hidden */
  19653. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19654. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19655. return false;
  19656. }
  19657. this._markSubMeshesAsMiscDirty();
  19658. return true;
  19659. };
  19660. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19661. /** Set a function to call when this mesh collides with another one */
  19662. set: function (callback) {
  19663. if (this._onCollideObserver) {
  19664. this.onCollideObservable.remove(this._onCollideObserver);
  19665. }
  19666. this._onCollideObserver = this.onCollideObservable.add(callback);
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19672. /** Set a function to call when the collision's position changes */
  19673. set: function (callback) {
  19674. if (this._onCollisionPositionChangeObserver) {
  19675. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19676. }
  19677. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19683. /**
  19684. * 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
  19685. * @see http://doc.babylonjs.com/features/occlusionquery
  19686. */
  19687. get: function () {
  19688. return this._isOccluded;
  19689. },
  19690. set: function (value) {
  19691. this._isOccluded = value;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19697. /**
  19698. * Flag to check the progress status of the query
  19699. * @see http://doc.babylonjs.com/features/occlusionquery
  19700. */
  19701. get: function () {
  19702. return this._isOcclusionQueryInProgress;
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19708. /**
  19709. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19710. */
  19711. get: function () {
  19712. return this._visibility;
  19713. },
  19714. /**
  19715. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19716. */
  19717. set: function (value) {
  19718. if (this._visibility === value) {
  19719. return;
  19720. }
  19721. this._visibility = value;
  19722. this._markSubMeshesAsMiscDirty();
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(AbstractMesh.prototype, "material", {
  19728. /** Gets or sets current material */
  19729. get: function () {
  19730. return this._material;
  19731. },
  19732. set: function (value) {
  19733. if (this._material === value) {
  19734. return;
  19735. }
  19736. this._material = value;
  19737. if (this.onMaterialChangedObservable.hasObservers) {
  19738. this.onMaterialChangedObservable.notifyObservers(this);
  19739. }
  19740. if (!this.subMeshes) {
  19741. return;
  19742. }
  19743. this._unBindEffect();
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19749. /**
  19750. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19751. * @see http://doc.babylonjs.com/babylon101/shadows
  19752. */
  19753. get: function () {
  19754. return this._receiveShadows;
  19755. },
  19756. set: function (value) {
  19757. if (this._receiveShadows === value) {
  19758. return;
  19759. }
  19760. this._receiveShadows = value;
  19761. this._markSubMeshesAsLightDirty();
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19767. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19768. get: function () {
  19769. return this._hasVertexAlpha;
  19770. },
  19771. set: function (value) {
  19772. if (this._hasVertexAlpha === value) {
  19773. return;
  19774. }
  19775. this._hasVertexAlpha = value;
  19776. this._markSubMeshesAsAttributesDirty();
  19777. this._markSubMeshesAsMiscDirty();
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19783. /** 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) */
  19784. get: function () {
  19785. return this._useVertexColors;
  19786. },
  19787. set: function (value) {
  19788. if (this._useVertexColors === value) {
  19789. return;
  19790. }
  19791. this._useVertexColors = value;
  19792. this._markSubMeshesAsAttributesDirty();
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19798. /**
  19799. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19800. */
  19801. get: function () {
  19802. return this._computeBonesUsingShaders;
  19803. },
  19804. set: function (value) {
  19805. if (this._computeBonesUsingShaders === value) {
  19806. return;
  19807. }
  19808. this._computeBonesUsingShaders = value;
  19809. this._markSubMeshesAsAttributesDirty();
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19815. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19816. get: function () {
  19817. return this._numBoneInfluencers;
  19818. },
  19819. set: function (value) {
  19820. if (this._numBoneInfluencers === value) {
  19821. return;
  19822. }
  19823. this._numBoneInfluencers = value;
  19824. this._markSubMeshesAsAttributesDirty();
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19830. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19831. get: function () {
  19832. return this._applyFog;
  19833. },
  19834. set: function (value) {
  19835. if (this._applyFog === value) {
  19836. return;
  19837. }
  19838. this._applyFog = value;
  19839. this._markSubMeshesAsMiscDirty();
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19845. /**
  19846. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19847. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19848. */
  19849. get: function () {
  19850. return this._layerMask;
  19851. },
  19852. set: function (value) {
  19853. if (value === this._layerMask) {
  19854. return;
  19855. }
  19856. this._layerMask = value;
  19857. this._resyncLightSources();
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19863. /**
  19864. * Gets or sets a collision mask used to mask collisions (default is -1).
  19865. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19866. */
  19867. get: function () {
  19868. return this._collisionMask;
  19869. },
  19870. set: function (mask) {
  19871. this._collisionMask = !isNaN(mask) ? mask : -1;
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19877. /**
  19878. * Gets or sets the current collision group mask (-1 by default).
  19879. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19880. */
  19881. get: function () {
  19882. return this._collisionGroup;
  19883. },
  19884. set: function (mask) {
  19885. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19891. /** @hidden */
  19892. get: function () {
  19893. return null;
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19899. get: function () {
  19900. return this._skeleton;
  19901. },
  19902. /**
  19903. * Gets or sets a skeleton to apply skining transformations
  19904. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19905. */
  19906. set: function (value) {
  19907. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19908. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19909. }
  19910. if (value && value.needInitialSkinMatrix) {
  19911. value._registerMeshWithPoseMatrix(this);
  19912. }
  19913. this._skeleton = value;
  19914. if (!this._skeleton) {
  19915. this._bonesTransformMatrices = null;
  19916. }
  19917. this._markSubMeshesAsAttributesDirty();
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. /**
  19923. * Returns the string "AbstractMesh"
  19924. * @returns "AbstractMesh"
  19925. */
  19926. AbstractMesh.prototype.getClassName = function () {
  19927. return "AbstractMesh";
  19928. };
  19929. /**
  19930. * Gets a string representation of the current mesh
  19931. * @param fullDetails defines a boolean indicating if full details must be included
  19932. * @returns a string representation of the current mesh
  19933. */
  19934. AbstractMesh.prototype.toString = function (fullDetails) {
  19935. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19936. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19937. if (this._skeleton) {
  19938. ret += ", skeleton: " + this._skeleton.name;
  19939. }
  19940. if (fullDetails) {
  19941. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19942. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19943. }
  19944. return ret;
  19945. };
  19946. /** @hidden */
  19947. AbstractMesh.prototype._rebuild = function () {
  19948. if (this._occlusionQuery) {
  19949. this._occlusionQuery = null;
  19950. }
  19951. if (this._edgesRenderer) {
  19952. this._edgesRenderer._rebuild();
  19953. }
  19954. if (!this.subMeshes) {
  19955. return;
  19956. }
  19957. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19958. var subMesh = _a[_i];
  19959. subMesh._rebuild();
  19960. }
  19961. };
  19962. /** @hidden */
  19963. AbstractMesh.prototype._resyncLightSources = function () {
  19964. this._lightSources.length = 0;
  19965. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19966. var light = _a[_i];
  19967. if (!light.isEnabled()) {
  19968. continue;
  19969. }
  19970. if (light.canAffectMesh(this)) {
  19971. this._lightSources.push(light);
  19972. }
  19973. }
  19974. this._markSubMeshesAsLightDirty();
  19975. };
  19976. /** @hidden */
  19977. AbstractMesh.prototype._resyncLighSource = function (light) {
  19978. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19979. var index = this._lightSources.indexOf(light);
  19980. if (index === -1) {
  19981. if (!isIn) {
  19982. return;
  19983. }
  19984. this._lightSources.push(light);
  19985. }
  19986. else {
  19987. if (isIn) {
  19988. return;
  19989. }
  19990. this._lightSources.splice(index, 1);
  19991. }
  19992. this._markSubMeshesAsLightDirty();
  19993. };
  19994. /** @hidden */
  19995. AbstractMesh.prototype._unBindEffect = function () {
  19996. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19997. var subMesh = _a[_i];
  19998. subMesh.setEffect(null);
  19999. }
  20000. };
  20001. /** @hidden */
  20002. AbstractMesh.prototype._removeLightSource = function (light) {
  20003. var index = this._lightSources.indexOf(light);
  20004. if (index === -1) {
  20005. return;
  20006. }
  20007. this._lightSources.splice(index, 1);
  20008. this._markSubMeshesAsLightDirty();
  20009. };
  20010. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20011. if (!this.subMeshes) {
  20012. return;
  20013. }
  20014. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20015. var subMesh = _a[_i];
  20016. if (subMesh._materialDefines) {
  20017. func(subMesh._materialDefines);
  20018. }
  20019. }
  20020. };
  20021. /** @hidden */
  20022. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20023. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20024. };
  20025. /** @hidden */
  20026. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20027. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20028. };
  20029. /** @hidden */
  20030. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20031. if (!this.subMeshes) {
  20032. return;
  20033. }
  20034. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20035. var subMesh = _a[_i];
  20036. var material = subMesh.getMaterial();
  20037. if (material) {
  20038. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20039. }
  20040. }
  20041. };
  20042. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20043. /**
  20044. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20045. */
  20046. get: function () {
  20047. return this._scaling;
  20048. },
  20049. set: function (newScaling) {
  20050. this._scaling = newScaling;
  20051. if (this.physicsImpostor) {
  20052. this.physicsImpostor.forceUpdate();
  20053. }
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. // Methods
  20059. /**
  20060. * Disables the mesh edge rendering mode
  20061. * @returns the currentAbstractMesh
  20062. */
  20063. AbstractMesh.prototype.disableEdgesRendering = function () {
  20064. if (this._edgesRenderer) {
  20065. this._edgesRenderer.dispose();
  20066. this._edgesRenderer = null;
  20067. }
  20068. return this;
  20069. };
  20070. /**
  20071. * Enables the edge rendering mode on the mesh.
  20072. * This mode makes the mesh edges visible
  20073. * @param epsilon defines the maximal distance between two angles to detect a face
  20074. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20075. * @returns the currentAbstractMesh
  20076. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20077. */
  20078. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20079. if (epsilon === void 0) { epsilon = 0.95; }
  20080. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20081. this.disableEdgesRendering();
  20082. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20083. return this;
  20084. };
  20085. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20086. /**
  20087. * Gets the edgesRenderer associated with the mesh
  20088. */
  20089. get: function () {
  20090. return this._edgesRenderer;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20096. /**
  20097. * Returns true if the mesh is blocked. Implemented by child classes
  20098. */
  20099. get: function () {
  20100. return false;
  20101. },
  20102. enumerable: true,
  20103. configurable: true
  20104. });
  20105. /**
  20106. * Returns the mesh itself by default. Implemented by child classes
  20107. * @param camera defines the camera to use to pick the right LOD level
  20108. * @returns the currentAbstractMesh
  20109. */
  20110. AbstractMesh.prototype.getLOD = function (camera) {
  20111. return this;
  20112. };
  20113. /**
  20114. * Returns 0 by default. Implemented by child classes
  20115. * @returns an integer
  20116. */
  20117. AbstractMesh.prototype.getTotalVertices = function () {
  20118. return 0;
  20119. };
  20120. /**
  20121. * Returns null by default. Implemented by child classes
  20122. * @returns null
  20123. */
  20124. AbstractMesh.prototype.getIndices = function () {
  20125. return null;
  20126. };
  20127. /**
  20128. * Returns the array of the requested vertex data kind. Implemented by child classes
  20129. * @param kind defines the vertex data kind to use
  20130. * @returns null
  20131. */
  20132. AbstractMesh.prototype.getVerticesData = function (kind) {
  20133. return null;
  20134. };
  20135. /**
  20136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20138. * Note that a new underlying VertexBuffer object is created each call.
  20139. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20140. * @param kind defines vertex data kind:
  20141. * * BABYLON.VertexBuffer.PositionKind
  20142. * * BABYLON.VertexBuffer.UVKind
  20143. * * BABYLON.VertexBuffer.UV2Kind
  20144. * * BABYLON.VertexBuffer.UV3Kind
  20145. * * BABYLON.VertexBuffer.UV4Kind
  20146. * * BABYLON.VertexBuffer.UV5Kind
  20147. * * BABYLON.VertexBuffer.UV6Kind
  20148. * * BABYLON.VertexBuffer.ColorKind
  20149. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20150. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20151. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20152. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20153. * @param data defines the data source
  20154. * @param updatable defines if the data must be flagged as updatable (or static)
  20155. * @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
  20156. * @returns the current mesh
  20157. */
  20158. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20159. return this;
  20160. };
  20161. /**
  20162. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20163. * If the mesh has no geometry, it is simply returned as it is.
  20164. * @param kind defines vertex data kind:
  20165. * * BABYLON.VertexBuffer.PositionKind
  20166. * * BABYLON.VertexBuffer.UVKind
  20167. * * BABYLON.VertexBuffer.UV2Kind
  20168. * * BABYLON.VertexBuffer.UV3Kind
  20169. * * BABYLON.VertexBuffer.UV4Kind
  20170. * * BABYLON.VertexBuffer.UV5Kind
  20171. * * BABYLON.VertexBuffer.UV6Kind
  20172. * * BABYLON.VertexBuffer.ColorKind
  20173. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20174. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20175. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20176. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20177. * @param data defines the data source
  20178. * @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
  20179. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20180. * @returns the current mesh
  20181. */
  20182. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20183. return this;
  20184. };
  20185. /**
  20186. * Sets the mesh indices,
  20187. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20188. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20189. * @param totalVertices Defines the total number of vertices
  20190. * @returns the current mesh
  20191. */
  20192. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20193. return this;
  20194. };
  20195. /**
  20196. * Gets a boolean indicating if specific vertex data is present
  20197. * @param kind defines the vertex data kind to use
  20198. * @returns true is data kind is present
  20199. */
  20200. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20201. return false;
  20202. };
  20203. /**
  20204. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20205. * @returns a BoundingInfo
  20206. */
  20207. AbstractMesh.prototype.getBoundingInfo = function () {
  20208. if (this._masterMesh) {
  20209. return this._masterMesh.getBoundingInfo();
  20210. }
  20211. if (!this._boundingInfo) {
  20212. // this._boundingInfo is being created here
  20213. this._updateBoundingInfo();
  20214. }
  20215. // cannot be null.
  20216. return this._boundingInfo;
  20217. };
  20218. /**
  20219. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20220. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20221. * @returns the current mesh
  20222. */
  20223. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20224. if (includeDescendants === void 0) { includeDescendants = true; }
  20225. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20226. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20227. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20228. if (maxDimension === 0) {
  20229. return this;
  20230. }
  20231. var scale = 1 / maxDimension;
  20232. this.scaling.scaleInPlace(scale);
  20233. return this;
  20234. };
  20235. /**
  20236. * Overwrite the current bounding info
  20237. * @param boundingInfo defines the new bounding info
  20238. * @returns the current mesh
  20239. */
  20240. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20241. this._boundingInfo = boundingInfo;
  20242. return this;
  20243. };
  20244. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20245. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20246. get: function () {
  20247. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. /** @hidden */
  20253. AbstractMesh.prototype._preActivate = function () {
  20254. };
  20255. /** @hidden */
  20256. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20257. };
  20258. /** @hidden */
  20259. AbstractMesh.prototype._activate = function (renderId) {
  20260. this._renderId = renderId;
  20261. };
  20262. /**
  20263. * Gets the current world matrix
  20264. * @returns a Matrix
  20265. */
  20266. AbstractMesh.prototype.getWorldMatrix = function () {
  20267. if (this._masterMesh) {
  20268. return this._masterMesh.getWorldMatrix();
  20269. }
  20270. return _super.prototype.getWorldMatrix.call(this);
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20274. if (this._masterMesh) {
  20275. return this._masterMesh._getWorldMatrixDeterminant();
  20276. }
  20277. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20278. };
  20279. // ================================== Point of View Movement =================================
  20280. /**
  20281. * Perform relative position change from the point of view of behind the front of the mesh.
  20282. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20283. * Supports definition of mesh facing forward or backward
  20284. * @param amountRight defines the distance on the right axis
  20285. * @param amountUp defines the distance on the up axis
  20286. * @param amountForward defines the distance on the forward axis
  20287. * @returns the current mesh
  20288. */
  20289. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20290. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20291. return this;
  20292. };
  20293. /**
  20294. * Calculate relative position change from the point of view of behind the front of the mesh.
  20295. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20296. * Supports definition of mesh facing forward or backward
  20297. * @param amountRight defines the distance on the right axis
  20298. * @param amountUp defines the distance on the up axis
  20299. * @param amountForward defines the distance on the forward axis
  20300. * @returns the new displacement vector
  20301. */
  20302. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20303. var rotMatrix = new BABYLON.Matrix();
  20304. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20305. rotQuaternion.toRotationMatrix(rotMatrix);
  20306. var translationDelta = BABYLON.Vector3.Zero();
  20307. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20309. return translationDelta;
  20310. };
  20311. // ================================== Point of View Rotation =================================
  20312. /**
  20313. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20314. * Supports definition of mesh facing forward or backward
  20315. * @param flipBack defines the flip
  20316. * @param twirlClockwise defines the twirl
  20317. * @param tiltRight defines the tilt
  20318. * @returns the current mesh
  20319. */
  20320. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20321. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20322. return this;
  20323. };
  20324. /**
  20325. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20326. * Supports definition of mesh facing forward or backward.
  20327. * @param flipBack defines the flip
  20328. * @param twirlClockwise defines the twirl
  20329. * @param tiltRight defines the tilt
  20330. * @returns the new rotation vector
  20331. */
  20332. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20333. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20334. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20335. };
  20336. /**
  20337. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20338. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20339. * @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
  20340. * @returns the new bounding vectors
  20341. */
  20342. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20343. if (includeDescendants === void 0) { includeDescendants = true; }
  20344. if (predicate === void 0) { predicate = null; }
  20345. // Ensures that all world matrix will be recomputed.
  20346. this.getScene().incrementRenderId();
  20347. this.computeWorldMatrix(true);
  20348. var min;
  20349. var max;
  20350. var boundingInfo = this.getBoundingInfo();
  20351. if (!this.subMeshes) {
  20352. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20353. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20354. }
  20355. else {
  20356. min = boundingInfo.boundingBox.minimumWorld;
  20357. max = boundingInfo.boundingBox.maximumWorld;
  20358. }
  20359. if (includeDescendants) {
  20360. var descendants = this.getDescendants(false);
  20361. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20362. var descendant = descendants_1[_i];
  20363. var childMesh = descendant;
  20364. childMesh.computeWorldMatrix(true);
  20365. // Filters meshes based on custom predicate function.
  20366. if (predicate && !predicate(childMesh)) {
  20367. continue;
  20368. }
  20369. //make sure we have the needed params to get mix and max
  20370. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20371. continue;
  20372. }
  20373. var childBoundingInfo = childMesh.getBoundingInfo();
  20374. var boundingBox = childBoundingInfo.boundingBox;
  20375. var minBox = boundingBox.minimumWorld;
  20376. var maxBox = boundingBox.maximumWorld;
  20377. BABYLON.Tools.CheckExtends(minBox, min, max);
  20378. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20379. }
  20380. }
  20381. return {
  20382. min: min,
  20383. max: max
  20384. };
  20385. };
  20386. /** @hidden */
  20387. AbstractMesh.prototype._updateBoundingInfo = function () {
  20388. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20389. this._boundingInfo.update(this.worldMatrixFromCache);
  20390. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20391. return this;
  20392. };
  20393. /** @hidden */
  20394. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20395. if (!this.subMeshes) {
  20396. return this;
  20397. }
  20398. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20399. var subMesh = this.subMeshes[subIndex];
  20400. if (!subMesh.IsGlobal) {
  20401. subMesh.updateBoundingInfo(matrix);
  20402. }
  20403. }
  20404. return this;
  20405. };
  20406. /** @hidden */
  20407. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20408. // Bounding info
  20409. this._updateBoundingInfo();
  20410. };
  20411. /**
  20412. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20413. * A mesh is in the frustum if its bounding box intersects the frustum
  20414. * @param frustumPlanes defines the frustum to test
  20415. * @returns true if the mesh is in the frustum planes
  20416. */
  20417. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20418. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20419. };
  20420. /**
  20421. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20422. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20423. * @param frustumPlanes defines the frustum to test
  20424. * @returns true if the mesh is completely in the frustum planes
  20425. */
  20426. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20427. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20428. };
  20429. /**
  20430. * True if the mesh intersects another mesh or a SolidParticle object
  20431. * @param mesh defines a target mesh or SolidParticle to test
  20432. * @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)
  20433. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20434. * @returns true if there is an intersection
  20435. */
  20436. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20437. if (precise === void 0) { precise = false; }
  20438. if (!this._boundingInfo || !mesh._boundingInfo) {
  20439. return false;
  20440. }
  20441. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20442. return true;
  20443. }
  20444. if (includeDescendants) {
  20445. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20446. var child = _a[_i];
  20447. if (child.intersectsMesh(mesh, precise, true)) {
  20448. return true;
  20449. }
  20450. }
  20451. }
  20452. return false;
  20453. };
  20454. /**
  20455. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20456. * @param point defines the point to test
  20457. * @returns true if there is an intersection
  20458. */
  20459. AbstractMesh.prototype.intersectsPoint = function (point) {
  20460. if (!this._boundingInfo) {
  20461. return false;
  20462. }
  20463. return this._boundingInfo.intersectsPoint(point);
  20464. };
  20465. /**
  20466. * Gets the current physics impostor
  20467. * @see http://doc.babylonjs.com/features/physics_engine
  20468. * @returns a physics impostor or null
  20469. */
  20470. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20471. return this.physicsImpostor;
  20472. };
  20473. /**
  20474. * Gets the position of the current mesh in camera space
  20475. * @param camera defines the camera to use
  20476. * @returns a position
  20477. */
  20478. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20479. if (camera === void 0) { camera = null; }
  20480. if (!camera) {
  20481. camera = this.getScene().activeCamera;
  20482. }
  20483. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20484. };
  20485. /**
  20486. * Returns the distance from the mesh to the active camera
  20487. * @param camera defines the camera to use
  20488. * @returns the distance
  20489. */
  20490. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20491. if (camera === void 0) { camera = null; }
  20492. if (!camera) {
  20493. camera = this.getScene().activeCamera;
  20494. }
  20495. return this.absolutePosition.subtract(camera.position).length();
  20496. };
  20497. /**
  20498. * Apply a physic impulse to the mesh
  20499. * @param force defines the force to apply
  20500. * @param contactPoint defines where to apply the force
  20501. * @returns the current mesh
  20502. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20503. */
  20504. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20505. if (!this.physicsImpostor) {
  20506. return this;
  20507. }
  20508. this.physicsImpostor.applyImpulse(force, contactPoint);
  20509. return this;
  20510. };
  20511. /**
  20512. * Creates a physic joint between two meshes
  20513. * @param otherMesh defines the other mesh to use
  20514. * @param pivot1 defines the pivot to use on this mesh
  20515. * @param pivot2 defines the pivot to use on the other mesh
  20516. * @param options defines additional options (can be plugin dependent)
  20517. * @returns the current mesh
  20518. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20519. */
  20520. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20521. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20522. return this;
  20523. }
  20524. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20525. mainPivot: pivot1,
  20526. connectedPivot: pivot2,
  20527. nativeParams: options
  20528. });
  20529. return this;
  20530. };
  20531. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20532. // Collisions
  20533. /**
  20534. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20535. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20536. */
  20537. get: function () {
  20538. return this._checkCollisions;
  20539. },
  20540. set: function (collisionEnabled) {
  20541. this._checkCollisions = collisionEnabled;
  20542. if (this.getScene().workerCollisions) {
  20543. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20544. }
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20550. /**
  20551. * Gets Collider object used to compute collisions (not physics)
  20552. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20553. */
  20554. get: function () {
  20555. return this._collider;
  20556. },
  20557. enumerable: true,
  20558. configurable: true
  20559. });
  20560. /**
  20561. * Move the mesh using collision engine
  20562. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20563. * @param displacement defines the requested displacement vector
  20564. * @returns the current mesh
  20565. */
  20566. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20567. var globalPosition = this.getAbsolutePosition();
  20568. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20569. if (!this._collider) {
  20570. this._collider = new BABYLON.Collider();
  20571. }
  20572. this._collider._radius = this.ellipsoid;
  20573. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20574. return this;
  20575. };
  20576. // Submeshes octree
  20577. /**
  20578. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20579. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20580. * @param maxCapacity defines the maximum size of each block (64 by default)
  20581. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20582. * @returns the new octree
  20583. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20584. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20585. */
  20586. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20587. if (maxCapacity === void 0) { maxCapacity = 64; }
  20588. if (maxDepth === void 0) { maxDepth = 2; }
  20589. if (!this._submeshesOctree) {
  20590. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20591. }
  20592. this.computeWorldMatrix(true);
  20593. var boundingInfo = this.getBoundingInfo();
  20594. // Update octree
  20595. var bbox = boundingInfo.boundingBox;
  20596. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20597. return this._submeshesOctree;
  20598. };
  20599. // Collisions
  20600. /** @hidden */
  20601. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20602. this._generatePointsArray();
  20603. if (!this._positions) {
  20604. return this;
  20605. }
  20606. // Transformation
  20607. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20608. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20609. subMesh._lastColliderWorldVertices = [];
  20610. subMesh._trianglePlanes = [];
  20611. var start = subMesh.verticesStart;
  20612. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20613. for (var i = start; i < end; i++) {
  20614. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20615. }
  20616. }
  20617. // Collide
  20618. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20619. if (collider.collisionFound) {
  20620. collider.collidedMesh = this;
  20621. }
  20622. return this;
  20623. };
  20624. /** @hidden */
  20625. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20626. var subMeshes;
  20627. var len;
  20628. // Octrees
  20629. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20630. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20631. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20632. len = intersections.length;
  20633. subMeshes = intersections.data;
  20634. }
  20635. else {
  20636. subMeshes = this.subMeshes;
  20637. len = subMeshes.length;
  20638. }
  20639. for (var index = 0; index < len; index++) {
  20640. var subMesh = subMeshes[index];
  20641. // Bounding test
  20642. if (len > 1 && !subMesh._checkCollision(collider))
  20643. continue;
  20644. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20645. }
  20646. return this;
  20647. };
  20648. /** @hidden */
  20649. AbstractMesh.prototype._checkCollision = function (collider) {
  20650. // Bounding box test
  20651. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20652. return this;
  20653. // Transformation matrix
  20654. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20655. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20656. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20657. return this;
  20658. };
  20659. // Picking
  20660. /** @hidden */
  20661. AbstractMesh.prototype._generatePointsArray = function () {
  20662. return false;
  20663. };
  20664. /**
  20665. * Checks if the passed Ray intersects with the mesh
  20666. * @param ray defines the ray to use
  20667. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20668. * @returns the picking info
  20669. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20670. */
  20671. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20672. var pickingInfo = new BABYLON.PickingInfo();
  20673. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20674. return pickingInfo;
  20675. }
  20676. if (!this._generatePointsArray()) {
  20677. return pickingInfo;
  20678. }
  20679. var intersectInfo = null;
  20680. // Octrees
  20681. var subMeshes;
  20682. var len;
  20683. if (this._submeshesOctree && this.useOctreeForPicking) {
  20684. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20685. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20686. len = intersections.length;
  20687. subMeshes = intersections.data;
  20688. }
  20689. else {
  20690. subMeshes = this.subMeshes;
  20691. len = subMeshes.length;
  20692. }
  20693. for (var index = 0; index < len; index++) {
  20694. var subMesh = subMeshes[index];
  20695. // Bounding test
  20696. if (len > 1 && !subMesh.canIntersects(ray))
  20697. continue;
  20698. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20699. if (currentIntersectInfo) {
  20700. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20701. intersectInfo = currentIntersectInfo;
  20702. intersectInfo.subMeshId = index;
  20703. if (fastCheck) {
  20704. break;
  20705. }
  20706. }
  20707. }
  20708. }
  20709. if (intersectInfo) {
  20710. // Get picked point
  20711. var world = this.getWorldMatrix();
  20712. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20713. var direction = ray.direction.clone();
  20714. direction = direction.scale(intersectInfo.distance);
  20715. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20716. var pickedPoint = worldOrigin.add(worldDirection);
  20717. // Return result
  20718. pickingInfo.hit = true;
  20719. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20720. pickingInfo.pickedPoint = pickedPoint;
  20721. pickingInfo.pickedMesh = this;
  20722. pickingInfo.bu = intersectInfo.bu || 0;
  20723. pickingInfo.bv = intersectInfo.bv || 0;
  20724. pickingInfo.faceId = intersectInfo.faceId;
  20725. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20726. return pickingInfo;
  20727. }
  20728. return pickingInfo;
  20729. };
  20730. /**
  20731. * Clones the current mesh
  20732. * @param name defines the mesh name
  20733. * @param newParent defines the new mesh parent
  20734. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20735. * @returns the new mesh
  20736. */
  20737. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20738. return null;
  20739. };
  20740. /**
  20741. * Disposes all the submeshes of the current meshnp
  20742. * @returns the current mesh
  20743. */
  20744. AbstractMesh.prototype.releaseSubMeshes = function () {
  20745. if (this.subMeshes) {
  20746. while (this.subMeshes.length) {
  20747. this.subMeshes[0].dispose();
  20748. }
  20749. }
  20750. else {
  20751. this.subMeshes = new Array();
  20752. }
  20753. return this;
  20754. };
  20755. /**
  20756. * Releases resources associated with this abstract mesh.
  20757. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20758. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20759. */
  20760. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20761. var _this = this;
  20762. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20763. var index;
  20764. // Smart Array Retainers.
  20765. this.getScene().freeActiveMeshes();
  20766. this.getScene().freeRenderingGroups();
  20767. // Action manager
  20768. if (this.actionManager !== undefined && this.actionManager !== null) {
  20769. this.actionManager.dispose();
  20770. this.actionManager = null;
  20771. }
  20772. // Skeleton
  20773. this._skeleton = null;
  20774. // Physics
  20775. if (this.physicsImpostor) {
  20776. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20777. }
  20778. // Intersections in progress
  20779. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20780. var other = this._intersectionsInProgress[index];
  20781. var pos = other._intersectionsInProgress.indexOf(this);
  20782. other._intersectionsInProgress.splice(pos, 1);
  20783. }
  20784. this._intersectionsInProgress = [];
  20785. // Lights
  20786. var lights = this.getScene().lights;
  20787. lights.forEach(function (light) {
  20788. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20789. if (meshIndex !== -1) {
  20790. light.includedOnlyMeshes.splice(meshIndex, 1);
  20791. }
  20792. meshIndex = light.excludedMeshes.indexOf(_this);
  20793. if (meshIndex !== -1) {
  20794. light.excludedMeshes.splice(meshIndex, 1);
  20795. }
  20796. // Shadow generators
  20797. var generator = light.getShadowGenerator();
  20798. if (generator) {
  20799. var shadowMap = generator.getShadowMap();
  20800. if (shadowMap && shadowMap.renderList) {
  20801. meshIndex = shadowMap.renderList.indexOf(_this);
  20802. if (meshIndex !== -1) {
  20803. shadowMap.renderList.splice(meshIndex, 1);
  20804. }
  20805. }
  20806. }
  20807. });
  20808. // Edges
  20809. if (this._edgesRenderer) {
  20810. this._edgesRenderer.dispose();
  20811. this._edgesRenderer = null;
  20812. }
  20813. // SubMeshes
  20814. if (this.getClassName() !== "InstancedMesh") {
  20815. this.releaseSubMeshes();
  20816. }
  20817. // Octree
  20818. var sceneOctree = this.getScene().selectionOctree;
  20819. if (sceneOctree !== undefined && sceneOctree !== null) {
  20820. var index = sceneOctree.dynamicContent.indexOf(this);
  20821. if (index !== -1) {
  20822. sceneOctree.dynamicContent.splice(index, 1);
  20823. }
  20824. }
  20825. // Query
  20826. var engine = this.getScene().getEngine();
  20827. if (this._occlusionQuery) {
  20828. this._isOcclusionQueryInProgress = false;
  20829. engine.deleteQuery(this._occlusionQuery);
  20830. this._occlusionQuery = null;
  20831. }
  20832. // Engine
  20833. engine.wipeCaches();
  20834. // Remove from scene
  20835. this.getScene().removeMesh(this);
  20836. if (disposeMaterialAndTextures) {
  20837. if (this.material) {
  20838. this.material.dispose(false, true);
  20839. }
  20840. }
  20841. if (!doNotRecurse) {
  20842. // Particles
  20843. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20844. if (this.getScene().particleSystems[index].emitter === this) {
  20845. this.getScene().particleSystems[index].dispose();
  20846. index--;
  20847. }
  20848. }
  20849. }
  20850. // facet data
  20851. if (this._facetDataEnabled) {
  20852. this.disableFacetData();
  20853. }
  20854. this.onAfterWorldMatrixUpdateObservable.clear();
  20855. this.onCollideObservable.clear();
  20856. this.onCollisionPositionChangeObservable.clear();
  20857. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20858. };
  20859. /**
  20860. * Adds the passed mesh as a child to the current mesh
  20861. * @param mesh defines the child mesh
  20862. * @returns the current mesh
  20863. */
  20864. AbstractMesh.prototype.addChild = function (mesh) {
  20865. mesh.setParent(this);
  20866. return this;
  20867. };
  20868. /**
  20869. * Removes the passed mesh from the current mesh children list
  20870. * @param mesh defines the child mesh
  20871. * @returns the current mesh
  20872. */
  20873. AbstractMesh.prototype.removeChild = function (mesh) {
  20874. mesh.setParent(null);
  20875. return this;
  20876. };
  20877. // Facet data
  20878. /** @hidden */
  20879. AbstractMesh.prototype._initFacetData = function () {
  20880. if (!this._facetNormals) {
  20881. this._facetNormals = new Array();
  20882. }
  20883. if (!this._facetPositions) {
  20884. this._facetPositions = new Array();
  20885. }
  20886. if (!this._facetPartitioning) {
  20887. this._facetPartitioning = new Array();
  20888. }
  20889. this._facetNb = (this.getIndices().length / 3) | 0;
  20890. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20891. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20892. for (var f = 0; f < this._facetNb; f++) {
  20893. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20894. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20895. }
  20896. this._facetDataEnabled = true;
  20897. return this;
  20898. };
  20899. /**
  20900. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20901. * This method can be called within the render loop.
  20902. * 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
  20903. * @returns the current mesh
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20905. */
  20906. AbstractMesh.prototype.updateFacetData = function () {
  20907. if (!this._facetDataEnabled) {
  20908. this._initFacetData();
  20909. }
  20910. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20911. var indices = this.getIndices();
  20912. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20913. var bInfo = this.getBoundingInfo();
  20914. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20915. // init arrays, matrix and sort function on first call
  20916. this._facetDepthSortEnabled = true;
  20917. if (indices instanceof Uint16Array) {
  20918. this._depthSortedIndices = new Uint16Array(indices);
  20919. }
  20920. else if (indices instanceof Uint32Array) {
  20921. this._depthSortedIndices = new Uint32Array(indices);
  20922. }
  20923. else {
  20924. var needs32bits = false;
  20925. for (var i = 0; i < indices.length; i++) {
  20926. if (indices[i] > 65535) {
  20927. needs32bits = true;
  20928. break;
  20929. }
  20930. }
  20931. if (needs32bits) {
  20932. this._depthSortedIndices = new Uint32Array(indices);
  20933. }
  20934. else {
  20935. this._depthSortedIndices = new Uint16Array(indices);
  20936. }
  20937. }
  20938. this._facetDepthSortFunction = function (f1, f2) {
  20939. return (f2.sqDistance - f1.sqDistance);
  20940. };
  20941. if (!this._facetDepthSortFrom) {
  20942. var camera = this.getScene().activeCamera;
  20943. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20944. }
  20945. this._depthSortedFacets = [];
  20946. for (var f = 0; f < this._facetNb; f++) {
  20947. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20948. this._depthSortedFacets.push(depthSortedFacet);
  20949. }
  20950. this._invertedMatrix = BABYLON.Matrix.Identity();
  20951. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20952. }
  20953. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20954. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20955. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20956. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20957. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20958. this._subDiv.max = this._partitioningSubdivisions;
  20959. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20960. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20961. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20962. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20963. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20964. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20965. // set the parameters for ComputeNormals()
  20966. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20967. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20968. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20969. this._facetParameters.bInfo = bInfo;
  20970. this._facetParameters.bbSize = this._bbSize;
  20971. this._facetParameters.subDiv = this._subDiv;
  20972. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20973. this._facetParameters.depthSort = this._facetDepthSort;
  20974. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20975. this.computeWorldMatrix(true);
  20976. this._worldMatrix.invertToRef(this._invertedMatrix);
  20977. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20978. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20979. }
  20980. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20981. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20982. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20983. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20984. var l = (this._depthSortedIndices.length / 3) | 0;
  20985. for (var f = 0; f < l; f++) {
  20986. var sind = this._depthSortedFacets[f].ind;
  20987. this._depthSortedIndices[f * 3] = indices[sind];
  20988. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20989. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20990. }
  20991. this.updateIndices(this._depthSortedIndices);
  20992. }
  20993. return this;
  20994. };
  20995. /**
  20996. * Returns the facetLocalNormals array.
  20997. * The normals are expressed in the mesh local spac
  20998. * @returns an array of Vector3
  20999. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21000. */
  21001. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21002. if (!this._facetNormals) {
  21003. this.updateFacetData();
  21004. }
  21005. return this._facetNormals;
  21006. };
  21007. /**
  21008. * Returns the facetLocalPositions array.
  21009. * The facet positions are expressed in the mesh local space
  21010. * @returns an array of Vector3
  21011. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21012. */
  21013. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21014. if (!this._facetPositions) {
  21015. this.updateFacetData();
  21016. }
  21017. return this._facetPositions;
  21018. };
  21019. /**
  21020. * Returns the facetLocalPartioning array
  21021. * @returns an array of array of numbers
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21025. if (!this._facetPartitioning) {
  21026. this.updateFacetData();
  21027. }
  21028. return this._facetPartitioning;
  21029. };
  21030. /**
  21031. * Returns the i-th facet position in the world system.
  21032. * This method allocates a new Vector3 per call
  21033. * @param i defines the facet index
  21034. * @returns a new Vector3
  21035. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21036. */
  21037. AbstractMesh.prototype.getFacetPosition = function (i) {
  21038. var pos = BABYLON.Vector3.Zero();
  21039. this.getFacetPositionToRef(i, pos);
  21040. return pos;
  21041. };
  21042. /**
  21043. * Sets the reference Vector3 with the i-th facet position in the world system
  21044. * @param i defines the facet index
  21045. * @param ref defines the target vector
  21046. * @returns the current mesh
  21047. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21048. */
  21049. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21050. var localPos = (this.getFacetLocalPositions())[i];
  21051. var world = this.getWorldMatrix();
  21052. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21053. return this;
  21054. };
  21055. /**
  21056. * Returns the i-th facet normal in the world system.
  21057. * This method allocates a new Vector3 per call
  21058. * @param i defines the facet index
  21059. * @returns a new Vector3
  21060. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21061. */
  21062. AbstractMesh.prototype.getFacetNormal = function (i) {
  21063. var norm = BABYLON.Vector3.Zero();
  21064. this.getFacetNormalToRef(i, norm);
  21065. return norm;
  21066. };
  21067. /**
  21068. * Sets the reference Vector3 with the i-th facet normal in the world system
  21069. * @param i defines the facet index
  21070. * @param ref defines the target vector
  21071. * @returns the current mesh
  21072. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21073. */
  21074. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21075. var localNorm = (this.getFacetLocalNormals())[i];
  21076. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21077. return this;
  21078. };
  21079. /**
  21080. * 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)
  21081. * @param x defines x coordinate
  21082. * @param y defines y coordinate
  21083. * @param z defines z coordinate
  21084. * @returns the array of facet indexes
  21085. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21086. */
  21087. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21088. var bInfo = this.getBoundingInfo();
  21089. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21090. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21091. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21092. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21093. return null;
  21094. }
  21095. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21096. };
  21097. /**
  21098. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21099. * @param projected sets as the (x,y,z) world projection on the facet
  21100. * @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
  21101. * @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
  21102. * @param x defines x coordinate
  21103. * @param y defines y coordinate
  21104. * @param z defines z coordinate
  21105. * @returns the face index if found (or null instead)
  21106. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21107. */
  21108. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21109. if (checkFace === void 0) { checkFace = false; }
  21110. if (facing === void 0) { facing = true; }
  21111. var world = this.getWorldMatrix();
  21112. var invMat = BABYLON.Tmp.Matrix[5];
  21113. world.invertToRef(invMat);
  21114. var invVect = BABYLON.Tmp.Vector3[8];
  21115. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21116. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21117. if (projected) {
  21118. // tranform the local computed projected vector to world coordinates
  21119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21120. }
  21121. return closest;
  21122. };
  21123. /**
  21124. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21125. * @param projected sets as the (x,y,z) local projection on the facet
  21126. * @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
  21127. * @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
  21128. * @param x defines x coordinate
  21129. * @param y defines y coordinate
  21130. * @param z defines z coordinate
  21131. * @returns the face index if found (or null instead)
  21132. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21133. */
  21134. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21135. if (checkFace === void 0) { checkFace = false; }
  21136. if (facing === void 0) { facing = true; }
  21137. var closest = null;
  21138. var tmpx = 0.0;
  21139. var tmpy = 0.0;
  21140. var tmpz = 0.0;
  21141. var d = 0.0; // tmp dot facet normal * facet position
  21142. var t0 = 0.0;
  21143. var projx = 0.0;
  21144. var projy = 0.0;
  21145. var projz = 0.0;
  21146. // Get all the facets in the same partitioning block than (x, y, z)
  21147. var facetPositions = this.getFacetLocalPositions();
  21148. var facetNormals = this.getFacetLocalNormals();
  21149. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21150. if (!facetsInBlock) {
  21151. return null;
  21152. }
  21153. // Get the closest facet to (x, y, z)
  21154. var shortest = Number.MAX_VALUE; // init distance vars
  21155. var tmpDistance = shortest;
  21156. var fib; // current facet in the block
  21157. var norm; // current facet normal
  21158. var p0; // current facet barycenter position
  21159. // loop on all the facets in the current partitioning block
  21160. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21161. fib = facetsInBlock[idx];
  21162. norm = facetNormals[fib];
  21163. p0 = facetPositions[fib];
  21164. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21165. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21166. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21167. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21168. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21169. projx = x + norm.x * t0;
  21170. projy = y + norm.y * t0;
  21171. projz = z + norm.z * t0;
  21172. tmpx = projx - x;
  21173. tmpy = projy - y;
  21174. tmpz = projz - z;
  21175. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21176. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21177. shortest = tmpDistance;
  21178. closest = fib;
  21179. if (projected) {
  21180. projected.x = projx;
  21181. projected.y = projy;
  21182. projected.z = projz;
  21183. }
  21184. }
  21185. }
  21186. }
  21187. return closest;
  21188. };
  21189. /**
  21190. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21191. * @returns the parameters
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getFacetDataParameters = function () {
  21195. return this._facetParameters;
  21196. };
  21197. /**
  21198. * Disables the feature FacetData and frees the related memory
  21199. * @returns the current mesh
  21200. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21201. */
  21202. AbstractMesh.prototype.disableFacetData = function () {
  21203. if (this._facetDataEnabled) {
  21204. this._facetDataEnabled = false;
  21205. this._facetPositions = new Array();
  21206. this._facetNormals = new Array();
  21207. this._facetPartitioning = new Array();
  21208. this._facetParameters = null;
  21209. this._depthSortedIndices = new Uint32Array(0);
  21210. }
  21211. return this;
  21212. };
  21213. /**
  21214. * Updates the AbstractMesh indices array
  21215. * @param indices defines the data source
  21216. * @returns the current mesh
  21217. */
  21218. AbstractMesh.prototype.updateIndices = function (indices) {
  21219. return this;
  21220. };
  21221. /**
  21222. * Creates new normals data for the mesh
  21223. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21224. * @returns the current mesh
  21225. */
  21226. AbstractMesh.prototype.createNormals = function (updatable) {
  21227. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21228. var indices = this.getIndices();
  21229. var normals;
  21230. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21231. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21232. }
  21233. else {
  21234. normals = [];
  21235. }
  21236. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21237. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21238. return this;
  21239. };
  21240. /**
  21241. * Align the mesh with a normal
  21242. * @param normal defines the normal to use
  21243. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21244. * @returns the current mesh
  21245. */
  21246. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21247. if (!upDirection) {
  21248. upDirection = BABYLON.Axis.Y;
  21249. }
  21250. var axisX = BABYLON.Tmp.Vector3[0];
  21251. var axisZ = BABYLON.Tmp.Vector3[1];
  21252. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21253. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21254. if (this.rotationQuaternion) {
  21255. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21256. }
  21257. else {
  21258. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21259. }
  21260. return this;
  21261. };
  21262. /** @hidden */
  21263. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21264. var engine = this.getEngine();
  21265. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21266. this._isOccluded = false;
  21267. return;
  21268. }
  21269. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21270. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21271. if (isOcclusionQueryAvailable) {
  21272. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21273. this._isOcclusionQueryInProgress = false;
  21274. this._occlusionInternalRetryCounter = 0;
  21275. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21276. }
  21277. else {
  21278. this._occlusionInternalRetryCounter++;
  21279. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21280. this._isOcclusionQueryInProgress = false;
  21281. this._occlusionInternalRetryCounter = 0;
  21282. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21283. // if strict continue the last state of the object.
  21284. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21285. }
  21286. else {
  21287. return;
  21288. }
  21289. }
  21290. }
  21291. var scene = this.getScene();
  21292. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21293. if (!this._occlusionQuery) {
  21294. this._occlusionQuery = engine.createQuery();
  21295. }
  21296. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21297. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21298. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21299. this._isOcclusionQueryInProgress = true;
  21300. };
  21301. /** No occlusion */
  21302. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21303. /** Occlusion set to optimisitic */
  21304. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21305. /** Occlusion set to strict */
  21306. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21307. /** Use an accurante occlusion algorithm */
  21308. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21309. /** Use a conservative occlusion algorithm */
  21310. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21311. return AbstractMesh;
  21312. }(BABYLON.TransformNode));
  21313. BABYLON.AbstractMesh = AbstractMesh;
  21314. })(BABYLON || (BABYLON = {}));
  21315. //# sourceMappingURL=babylon.abstractMesh.js.map
  21316. var BABYLON;
  21317. (function (BABYLON) {
  21318. /**
  21319. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21320. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21321. * 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.
  21322. */
  21323. var Light = /** @class */ (function (_super) {
  21324. __extends(Light, _super);
  21325. /**
  21326. * Creates a Light object in the scene.
  21327. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21328. * @param name The firendly name of the light
  21329. * @param scene The scene the light belongs too
  21330. */
  21331. function Light(name, scene) {
  21332. var _this = _super.call(this, name, scene) || this;
  21333. /**
  21334. * Diffuse gives the basic color to an object.
  21335. */
  21336. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21337. /**
  21338. * Specular produces a highlight color on an object.
  21339. * Note: This is note affecting PBR materials.
  21340. */
  21341. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21342. /**
  21343. * Strength of the light.
  21344. * Note: By default it is define in the framework own unit.
  21345. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21346. */
  21347. _this.intensity = 1.0;
  21348. /**
  21349. * Defines how far from the source the light is impacting in scene units.
  21350. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21351. */
  21352. _this.range = Number.MAX_VALUE;
  21353. /**
  21354. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21355. * of light.
  21356. */
  21357. _this._photometricScale = 1.0;
  21358. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21359. _this._radius = 0.00001;
  21360. /**
  21361. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21362. * exceeding the number allowed of the materials.
  21363. */
  21364. _this.renderPriority = 0;
  21365. _this._shadowEnabled = true;
  21366. _this._excludeWithLayerMask = 0;
  21367. _this._includeOnlyWithLayerMask = 0;
  21368. _this._lightmapMode = 0;
  21369. /**
  21370. * @hidden Internal use only.
  21371. */
  21372. _this._excludedMeshesIds = new Array();
  21373. /**
  21374. * @hidden Internal use only.
  21375. */
  21376. _this._includedOnlyMeshesIds = new Array();
  21377. _this.getScene().addLight(_this);
  21378. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21379. _this._buildUniformLayout();
  21380. _this.includedOnlyMeshes = new Array();
  21381. _this.excludedMeshes = new Array();
  21382. _this._resyncMeshes();
  21383. return _this;
  21384. }
  21385. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21386. /**
  21387. * If every light affecting the material is in this lightmapMode,
  21388. * material.lightmapTexture adds or multiplies
  21389. * (depends on material.useLightmapAsShadowmap)
  21390. * after every other light calculations.
  21391. */
  21392. get: function () {
  21393. return Light._LIGHTMAP_DEFAULT;
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21399. /**
  21400. * material.lightmapTexture as only diffuse lighting from this light
  21401. * adds only specular lighting from this light
  21402. * adds dynamic shadows
  21403. */
  21404. get: function () {
  21405. return Light._LIGHTMAP_SPECULAR;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21411. /**
  21412. * material.lightmapTexture as only lighting
  21413. * no light calculation from this light
  21414. * only adds dynamic shadows from this light
  21415. */
  21416. get: function () {
  21417. return Light._LIGHTMAP_SHADOWSONLY;
  21418. },
  21419. enumerable: true,
  21420. configurable: true
  21421. });
  21422. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21423. /**
  21424. * Each light type uses the default quantity according to its type:
  21425. * point/spot lights use luminous intensity
  21426. * directional lights use illuminance
  21427. */
  21428. get: function () {
  21429. return Light._INTENSITYMODE_AUTOMATIC;
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21435. /**
  21436. * lumen (lm)
  21437. */
  21438. get: function () {
  21439. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21445. /**
  21446. * candela (lm/sr)
  21447. */
  21448. get: function () {
  21449. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21455. /**
  21456. * lux (lm/m^2)
  21457. */
  21458. get: function () {
  21459. return Light._INTENSITYMODE_ILLUMINANCE;
  21460. },
  21461. enumerable: true,
  21462. configurable: true
  21463. });
  21464. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21465. /**
  21466. * nit (cd/m^2)
  21467. */
  21468. get: function () {
  21469. return Light._INTENSITYMODE_LUMINANCE;
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21475. /**
  21476. * Light type const id of the point light.
  21477. */
  21478. get: function () {
  21479. return Light._LIGHTTYPEID_POINTLIGHT;
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21485. /**
  21486. * Light type const id of the directional light.
  21487. */
  21488. get: function () {
  21489. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21495. /**
  21496. * Light type const id of the spot light.
  21497. */
  21498. get: function () {
  21499. return Light._LIGHTTYPEID_SPOTLIGHT;
  21500. },
  21501. enumerable: true,
  21502. configurable: true
  21503. });
  21504. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21505. /**
  21506. * Light type const id of the hemispheric light.
  21507. */
  21508. get: function () {
  21509. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21510. },
  21511. enumerable: true,
  21512. configurable: true
  21513. });
  21514. Object.defineProperty(Light.prototype, "intensityMode", {
  21515. /**
  21516. * Gets the photometric scale used to interpret the intensity.
  21517. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21518. */
  21519. get: function () {
  21520. return this._intensityMode;
  21521. },
  21522. /**
  21523. * Sets the photometric scale used to interpret the intensity.
  21524. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21525. */
  21526. set: function (value) {
  21527. this._intensityMode = value;
  21528. this._computePhotometricScale();
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. ;
  21534. ;
  21535. Object.defineProperty(Light.prototype, "radius", {
  21536. /**
  21537. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21538. */
  21539. get: function () {
  21540. return this._radius;
  21541. },
  21542. /**
  21543. * sets the light radius used by PBR Materials to simulate soft area lights.
  21544. */
  21545. set: function (value) {
  21546. this._radius = value;
  21547. this._computePhotometricScale();
  21548. },
  21549. enumerable: true,
  21550. configurable: true
  21551. });
  21552. ;
  21553. ;
  21554. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21555. /**
  21556. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21557. * the current shadow generator.
  21558. */
  21559. get: function () {
  21560. return this._shadowEnabled;
  21561. },
  21562. /**
  21563. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21564. * the current shadow generator.
  21565. */
  21566. set: function (value) {
  21567. if (this._shadowEnabled === value) {
  21568. return;
  21569. }
  21570. this._shadowEnabled = value;
  21571. this._markMeshesAsLightDirty();
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21577. /**
  21578. * Gets the only meshes impacted by this light.
  21579. */
  21580. get: function () {
  21581. return this._includedOnlyMeshes;
  21582. },
  21583. /**
  21584. * Sets the only meshes impacted by this light.
  21585. */
  21586. set: function (value) {
  21587. this._includedOnlyMeshes = value;
  21588. this._hookArrayForIncludedOnly(value);
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21594. /**
  21595. * Gets the meshes not impacted by this light.
  21596. */
  21597. get: function () {
  21598. return this._excludedMeshes;
  21599. },
  21600. /**
  21601. * Sets the meshes not impacted by this light.
  21602. */
  21603. set: function (value) {
  21604. this._excludedMeshes = value;
  21605. this._hookArrayForExcluded(value);
  21606. },
  21607. enumerable: true,
  21608. configurable: true
  21609. });
  21610. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21611. /**
  21612. * Gets the layer id use to find what meshes are not impacted by the light.
  21613. * Inactive if 0
  21614. */
  21615. get: function () {
  21616. return this._excludeWithLayerMask;
  21617. },
  21618. /**
  21619. * Sets the layer id use to find what meshes are not impacted by the light.
  21620. * Inactive if 0
  21621. */
  21622. set: function (value) {
  21623. this._excludeWithLayerMask = value;
  21624. this._resyncMeshes();
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21630. /**
  21631. * Gets the layer id use to find what meshes are impacted by the light.
  21632. * Inactive if 0
  21633. */
  21634. get: function () {
  21635. return this._includeOnlyWithLayerMask;
  21636. },
  21637. /**
  21638. * Sets the layer id use to find what meshes are impacted by the light.
  21639. * Inactive if 0
  21640. */
  21641. set: function (value) {
  21642. this._includeOnlyWithLayerMask = value;
  21643. this._resyncMeshes();
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Light.prototype, "lightmapMode", {
  21649. /**
  21650. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21651. */
  21652. get: function () {
  21653. return this._lightmapMode;
  21654. },
  21655. /**
  21656. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21657. */
  21658. set: function (value) {
  21659. if (this._lightmapMode === value) {
  21660. return;
  21661. }
  21662. this._lightmapMode = value;
  21663. this._markMeshesAsLightDirty();
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. /**
  21669. * Returns the string "Light".
  21670. * @returns the class name
  21671. */
  21672. Light.prototype.getClassName = function () {
  21673. return "Light";
  21674. };
  21675. /**
  21676. * Converts the light information to a readable string for debug purpose.
  21677. * @param fullDetails Supports for multiple levels of logging within scene loading
  21678. * @returns the human readable light info
  21679. */
  21680. Light.prototype.toString = function (fullDetails) {
  21681. var ret = "Name: " + this.name;
  21682. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21683. if (this.animations) {
  21684. for (var i = 0; i < this.animations.length; i++) {
  21685. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21686. }
  21687. }
  21688. if (fullDetails) {
  21689. }
  21690. return ret;
  21691. };
  21692. /**
  21693. * Set the enabled state of this node.
  21694. * @param value - the new enabled state
  21695. */
  21696. Light.prototype.setEnabled = function (value) {
  21697. _super.prototype.setEnabled.call(this, value);
  21698. this._resyncMeshes();
  21699. };
  21700. /**
  21701. * Returns the Light associated shadow generator if any.
  21702. * @return the associated shadow generator.
  21703. */
  21704. Light.prototype.getShadowGenerator = function () {
  21705. return this._shadowGenerator;
  21706. };
  21707. /**
  21708. * Returns a Vector3, the absolute light position in the World.
  21709. * @returns the world space position of the light
  21710. */
  21711. Light.prototype.getAbsolutePosition = function () {
  21712. return BABYLON.Vector3.Zero();
  21713. };
  21714. /**
  21715. * Specifies if the light will affect the passed mesh.
  21716. * @param mesh The mesh to test against the light
  21717. * @return true the mesh is affected otherwise, false.
  21718. */
  21719. Light.prototype.canAffectMesh = function (mesh) {
  21720. if (!mesh) {
  21721. return true;
  21722. }
  21723. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21724. return false;
  21725. }
  21726. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21727. return false;
  21728. }
  21729. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21730. return false;
  21731. }
  21732. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21733. return false;
  21734. }
  21735. return true;
  21736. };
  21737. /**
  21738. * Computes and Returns the light World matrix.
  21739. * @returns the world matrix
  21740. */
  21741. Light.prototype.getWorldMatrix = function () {
  21742. this._currentRenderId = this.getScene().getRenderId();
  21743. this._childRenderId = this._currentRenderId;
  21744. var worldMatrix = this._getWorldMatrix();
  21745. if (this.parent && this.parent.getWorldMatrix) {
  21746. if (!this._parentedWorldMatrix) {
  21747. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21748. }
  21749. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21750. this._markSyncedWithParent();
  21751. return this._parentedWorldMatrix;
  21752. }
  21753. return worldMatrix;
  21754. };
  21755. /**
  21756. * Sort function to order lights for rendering.
  21757. * @param a First Light object to compare to second.
  21758. * @param b Second Light object to compare first.
  21759. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21760. */
  21761. Light.CompareLightsPriority = function (a, b) {
  21762. //shadow-casting lights have priority over non-shadow-casting lights
  21763. //the renderPrioirty is a secondary sort criterion
  21764. if (a.shadowEnabled !== b.shadowEnabled) {
  21765. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21766. }
  21767. return b.renderPriority - a.renderPriority;
  21768. };
  21769. /**
  21770. * Releases resources associated with this node.
  21771. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21772. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21773. */
  21774. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21775. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21776. if (this._shadowGenerator) {
  21777. this._shadowGenerator.dispose();
  21778. this._shadowGenerator = null;
  21779. }
  21780. // Animations
  21781. this.getScene().stopAnimation(this);
  21782. // Remove from meshes
  21783. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21784. var mesh = _a[_i];
  21785. mesh._removeLightSource(this);
  21786. }
  21787. this._uniformBuffer.dispose();
  21788. // Remove from scene
  21789. this.getScene().removeLight(this);
  21790. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21791. };
  21792. /**
  21793. * Returns the light type ID (integer).
  21794. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21795. */
  21796. Light.prototype.getTypeID = function () {
  21797. return 0;
  21798. };
  21799. /**
  21800. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21801. * @returns the scaled intensity in intensity mode unit
  21802. */
  21803. Light.prototype.getScaledIntensity = function () {
  21804. return this._photometricScale * this.intensity;
  21805. };
  21806. /**
  21807. * Returns a new Light object, named "name", from the current one.
  21808. * @param name The name of the cloned light
  21809. * @returns the new created light
  21810. */
  21811. Light.prototype.clone = function (name) {
  21812. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21813. if (!constructor) {
  21814. return null;
  21815. }
  21816. return BABYLON.SerializationHelper.Clone(constructor, this);
  21817. };
  21818. /**
  21819. * Serializes the current light into a Serialization object.
  21820. * @returns the serialized object.
  21821. */
  21822. Light.prototype.serialize = function () {
  21823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21824. // Type
  21825. serializationObject.type = this.getTypeID();
  21826. // Parent
  21827. if (this.parent) {
  21828. serializationObject.parentId = this.parent.id;
  21829. }
  21830. // Inclusion / exclusions
  21831. if (this.excludedMeshes.length > 0) {
  21832. serializationObject.excludedMeshesIds = [];
  21833. this.excludedMeshes.forEach(function (mesh) {
  21834. serializationObject.excludedMeshesIds.push(mesh.id);
  21835. });
  21836. }
  21837. if (this.includedOnlyMeshes.length > 0) {
  21838. serializationObject.includedOnlyMeshesIds = [];
  21839. this.includedOnlyMeshes.forEach(function (mesh) {
  21840. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21841. });
  21842. }
  21843. // Animations
  21844. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21845. serializationObject.ranges = this.serializeAnimationRanges();
  21846. return serializationObject;
  21847. };
  21848. /**
  21849. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21850. * This new light is named "name" and added to the passed scene.
  21851. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21852. * @param name The friendly name of the light
  21853. * @param scene The scene the new light will belong to
  21854. * @returns the constructor function
  21855. */
  21856. Light.GetConstructorFromName = function (type, name, scene) {
  21857. switch (type) {
  21858. case 0:
  21859. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21860. case 1:
  21861. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21862. case 2:
  21863. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21864. case 3:
  21865. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21866. }
  21867. return null;
  21868. };
  21869. /**
  21870. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21871. * @param parsedLight The JSON representation of the light
  21872. * @param scene The scene to create the parsed light in
  21873. * @returns the created light after parsing
  21874. */
  21875. Light.Parse = function (parsedLight, scene) {
  21876. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21877. if (!constructor) {
  21878. return null;
  21879. }
  21880. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21881. // Inclusion / exclusions
  21882. if (parsedLight.excludedMeshesIds) {
  21883. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21884. }
  21885. if (parsedLight.includedOnlyMeshesIds) {
  21886. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21887. }
  21888. // Parent
  21889. if (parsedLight.parentId) {
  21890. light._waitingParentId = parsedLight.parentId;
  21891. }
  21892. // Animations
  21893. if (parsedLight.animations) {
  21894. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21895. var parsedAnimation = parsedLight.animations[animationIndex];
  21896. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21897. }
  21898. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21899. }
  21900. if (parsedLight.autoAnimate) {
  21901. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21902. }
  21903. return light;
  21904. };
  21905. Light.prototype._hookArrayForExcluded = function (array) {
  21906. var _this = this;
  21907. var oldPush = array.push;
  21908. array.push = function () {
  21909. var items = [];
  21910. for (var _i = 0; _i < arguments.length; _i++) {
  21911. items[_i] = arguments[_i];
  21912. }
  21913. var result = oldPush.apply(array, items);
  21914. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21915. var item = items_1[_a];
  21916. item._resyncLighSource(_this);
  21917. }
  21918. return result;
  21919. };
  21920. var oldSplice = array.splice;
  21921. array.splice = function (index, deleteCount) {
  21922. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21923. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21924. var item = deleted_1[_i];
  21925. item._resyncLighSource(_this);
  21926. }
  21927. return deleted;
  21928. };
  21929. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21930. var item = array_1[_i];
  21931. item._resyncLighSource(this);
  21932. }
  21933. };
  21934. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21935. var _this = this;
  21936. var oldPush = array.push;
  21937. array.push = function () {
  21938. var items = [];
  21939. for (var _i = 0; _i < arguments.length; _i++) {
  21940. items[_i] = arguments[_i];
  21941. }
  21942. var result = oldPush.apply(array, items);
  21943. _this._resyncMeshes();
  21944. return result;
  21945. };
  21946. var oldSplice = array.splice;
  21947. array.splice = function (index, deleteCount) {
  21948. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21949. _this._resyncMeshes();
  21950. return deleted;
  21951. };
  21952. this._resyncMeshes();
  21953. };
  21954. Light.prototype._resyncMeshes = function () {
  21955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21956. var mesh = _a[_i];
  21957. mesh._resyncLighSource(this);
  21958. }
  21959. };
  21960. /**
  21961. * Forces the meshes to update their light related information in their rendering used effects
  21962. * @hidden Internal Use Only
  21963. */
  21964. Light.prototype._markMeshesAsLightDirty = function () {
  21965. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21966. var mesh = _a[_i];
  21967. if (mesh._lightSources.indexOf(this) !== -1) {
  21968. mesh._markSubMeshesAsLightDirty();
  21969. }
  21970. }
  21971. };
  21972. /**
  21973. * Recomputes the cached photometric scale if needed.
  21974. */
  21975. Light.prototype._computePhotometricScale = function () {
  21976. this._photometricScale = this._getPhotometricScale();
  21977. this.getScene().resetCachedMaterial();
  21978. };
  21979. /**
  21980. * Returns the Photometric Scale according to the light type and intensity mode.
  21981. */
  21982. Light.prototype._getPhotometricScale = function () {
  21983. var photometricScale = 0.0;
  21984. var lightTypeID = this.getTypeID();
  21985. //get photometric mode
  21986. var photometricMode = this.intensityMode;
  21987. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21988. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21989. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21990. }
  21991. else {
  21992. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21993. }
  21994. }
  21995. //compute photometric scale
  21996. switch (lightTypeID) {
  21997. case Light.LIGHTTYPEID_POINTLIGHT:
  21998. case Light.LIGHTTYPEID_SPOTLIGHT:
  21999. switch (photometricMode) {
  22000. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22001. photometricScale = 1.0 / (4.0 * Math.PI);
  22002. break;
  22003. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22004. photometricScale = 1.0;
  22005. break;
  22006. case Light.INTENSITYMODE_LUMINANCE:
  22007. photometricScale = this.radius * this.radius;
  22008. break;
  22009. }
  22010. break;
  22011. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22012. switch (photometricMode) {
  22013. case Light.INTENSITYMODE_ILLUMINANCE:
  22014. photometricScale = 1.0;
  22015. break;
  22016. case Light.INTENSITYMODE_LUMINANCE:
  22017. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22018. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22019. var apexAngleRadians = this.radius;
  22020. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22021. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22022. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22023. photometricScale = solidAngle;
  22024. break;
  22025. }
  22026. break;
  22027. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22028. // No fall off in hemisperic light.
  22029. photometricScale = 1.0;
  22030. break;
  22031. }
  22032. return photometricScale;
  22033. };
  22034. /**
  22035. * Reorder the light in the scene according to their defined priority.
  22036. * @hidden Internal Use Only
  22037. */
  22038. Light.prototype._reorderLightsInScene = function () {
  22039. var scene = this.getScene();
  22040. if (this._renderPriority != 0) {
  22041. scene.requireLightSorting = true;
  22042. }
  22043. this.getScene().sortLightsByPriority();
  22044. };
  22045. //lightmapMode Consts
  22046. Light._LIGHTMAP_DEFAULT = 0;
  22047. Light._LIGHTMAP_SPECULAR = 1;
  22048. Light._LIGHTMAP_SHADOWSONLY = 2;
  22049. // Intensity Mode Consts
  22050. Light._INTENSITYMODE_AUTOMATIC = 0;
  22051. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22052. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22053. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22054. Light._INTENSITYMODE_LUMINANCE = 4;
  22055. // Light types ids const.
  22056. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22057. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22058. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22059. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22060. __decorate([
  22061. BABYLON.serializeAsColor3()
  22062. ], Light.prototype, "diffuse", void 0);
  22063. __decorate([
  22064. BABYLON.serializeAsColor3()
  22065. ], Light.prototype, "specular", void 0);
  22066. __decorate([
  22067. BABYLON.serialize()
  22068. ], Light.prototype, "intensity", void 0);
  22069. __decorate([
  22070. BABYLON.serialize()
  22071. ], Light.prototype, "range", void 0);
  22072. __decorate([
  22073. BABYLON.serialize()
  22074. ], Light.prototype, "intensityMode", null);
  22075. __decorate([
  22076. BABYLON.serialize()
  22077. ], Light.prototype, "radius", null);
  22078. __decorate([
  22079. BABYLON.serialize()
  22080. ], Light.prototype, "_renderPriority", void 0);
  22081. __decorate([
  22082. BABYLON.expandToProperty("_reorderLightsInScene")
  22083. ], Light.prototype, "renderPriority", void 0);
  22084. __decorate([
  22085. BABYLON.serialize("shadowEnabled")
  22086. ], Light.prototype, "_shadowEnabled", void 0);
  22087. __decorate([
  22088. BABYLON.serialize("excludeWithLayerMask")
  22089. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22090. __decorate([
  22091. BABYLON.serialize("includeOnlyWithLayerMask")
  22092. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22093. __decorate([
  22094. BABYLON.serialize("lightmapMode")
  22095. ], Light.prototype, "_lightmapMode", void 0);
  22096. return Light;
  22097. }(BABYLON.Node));
  22098. BABYLON.Light = Light;
  22099. })(BABYLON || (BABYLON = {}));
  22100. //# sourceMappingURL=babylon.light.js.map
  22101. var BABYLON;
  22102. (function (BABYLON) {
  22103. var Camera = /** @class */ (function (_super) {
  22104. __extends(Camera, _super);
  22105. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22106. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22107. var _this = _super.call(this, name, scene) || this;
  22108. /**
  22109. * The vector the camera should consider as up.
  22110. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22111. */
  22112. _this.upVector = BABYLON.Vector3.Up();
  22113. _this.orthoLeft = null;
  22114. _this.orthoRight = null;
  22115. _this.orthoBottom = null;
  22116. _this.orthoTop = null;
  22117. /**
  22118. * FOV is set in Radians. (default is 0.8)
  22119. */
  22120. _this.fov = 0.8;
  22121. _this.minZ = 1;
  22122. _this.maxZ = 10000.0;
  22123. _this.inertia = 0.9;
  22124. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22125. _this.isIntermediate = false;
  22126. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22127. /**
  22128. * Restricts the camera to viewing objects with the same layerMask.
  22129. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22130. */
  22131. _this.layerMask = 0x0FFFFFFF;
  22132. /**
  22133. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22134. */
  22135. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22136. // Camera rig members
  22137. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22138. _this._rigCameras = new Array();
  22139. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22140. _this._skipRendering = false;
  22141. _this.customRenderTargets = new Array();
  22142. // Observables
  22143. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22144. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22145. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22146. _this.onRestoreStateObservable = new BABYLON.Observable();
  22147. // Cache
  22148. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22149. _this._projectionMatrix = new BABYLON.Matrix();
  22150. _this._doNotComputeProjectionMatrix = false;
  22151. _this._worldMatrix = BABYLON.Matrix.Identity();
  22152. _this._postProcesses = new Array();
  22153. _this._transformMatrix = BABYLON.Matrix.Zero();
  22154. _this._activeMeshes = new BABYLON.SmartArray(256);
  22155. _this._globalPosition = BABYLON.Vector3.Zero();
  22156. _this._refreshFrustumPlanes = true;
  22157. _this.getScene().addCamera(_this);
  22158. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22159. _this.getScene().activeCamera = _this;
  22160. }
  22161. _this.position = position;
  22162. return _this;
  22163. }
  22164. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22165. get: function () {
  22166. return Camera._PERSPECTIVE_CAMERA;
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22172. get: function () {
  22173. return Camera._ORTHOGRAPHIC_CAMERA;
  22174. },
  22175. enumerable: true,
  22176. configurable: true
  22177. });
  22178. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22179. /**
  22180. * This is the default FOV mode for perspective cameras.
  22181. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22182. *
  22183. */
  22184. get: function () {
  22185. return Camera._FOVMODE_VERTICAL_FIXED;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22191. /**
  22192. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22193. *
  22194. */
  22195. get: function () {
  22196. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22202. get: function () {
  22203. return Camera._RIG_MODE_NONE;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22209. get: function () {
  22210. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22216. get: function () {
  22217. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22223. get: function () {
  22224. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22230. get: function () {
  22231. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22237. get: function () {
  22238. return Camera._RIG_MODE_VR;
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22244. get: function () {
  22245. return Camera._RIG_MODE_WEBVR;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. /**
  22251. * Store current camera state (fov, position, etc..)
  22252. */
  22253. Camera.prototype.storeState = function () {
  22254. this._stateStored = true;
  22255. this._storedFov = this.fov;
  22256. return this;
  22257. };
  22258. /**
  22259. * Restores the camera state values if it has been stored. You must call storeState() first
  22260. */
  22261. Camera.prototype._restoreStateValues = function () {
  22262. if (!this._stateStored) {
  22263. return false;
  22264. }
  22265. this.fov = this._storedFov;
  22266. return true;
  22267. };
  22268. /**
  22269. * Restored camera state. You must call storeState() first
  22270. */
  22271. Camera.prototype.restoreState = function () {
  22272. if (this._restoreStateValues()) {
  22273. this.onRestoreStateObservable.notifyObservers(this);
  22274. return true;
  22275. }
  22276. return false;
  22277. };
  22278. Camera.prototype.getClassName = function () {
  22279. return "Camera";
  22280. };
  22281. /**
  22282. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22283. */
  22284. Camera.prototype.toString = function (fullDetails) {
  22285. var ret = "Name: " + this.name;
  22286. ret += ", type: " + this.getClassName();
  22287. if (this.animations) {
  22288. for (var i = 0; i < this.animations.length; i++) {
  22289. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22290. }
  22291. }
  22292. if (fullDetails) {
  22293. }
  22294. return ret;
  22295. };
  22296. Object.defineProperty(Camera.prototype, "globalPosition", {
  22297. get: function () {
  22298. return this._globalPosition;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Camera.prototype.getActiveMeshes = function () {
  22304. return this._activeMeshes;
  22305. };
  22306. Camera.prototype.isActiveMesh = function (mesh) {
  22307. return (this._activeMeshes.indexOf(mesh) !== -1);
  22308. };
  22309. /**
  22310. * Is this camera ready to be used/rendered
  22311. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22312. * @return true if the camera is ready
  22313. */
  22314. Camera.prototype.isReady = function (completeCheck) {
  22315. if (completeCheck === void 0) { completeCheck = false; }
  22316. if (completeCheck) {
  22317. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22318. var pp = _a[_i];
  22319. if (pp && !pp.isReady()) {
  22320. return false;
  22321. }
  22322. }
  22323. }
  22324. return _super.prototype.isReady.call(this, completeCheck);
  22325. };
  22326. //Cache
  22327. Camera.prototype._initCache = function () {
  22328. _super.prototype._initCache.call(this);
  22329. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22330. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22331. this._cache.mode = undefined;
  22332. this._cache.minZ = undefined;
  22333. this._cache.maxZ = undefined;
  22334. this._cache.fov = undefined;
  22335. this._cache.fovMode = undefined;
  22336. this._cache.aspectRatio = undefined;
  22337. this._cache.orthoLeft = undefined;
  22338. this._cache.orthoRight = undefined;
  22339. this._cache.orthoBottom = undefined;
  22340. this._cache.orthoTop = undefined;
  22341. this._cache.renderWidth = undefined;
  22342. this._cache.renderHeight = undefined;
  22343. };
  22344. Camera.prototype._updateCache = function (ignoreParentClass) {
  22345. if (!ignoreParentClass) {
  22346. _super.prototype._updateCache.call(this);
  22347. }
  22348. this._cache.position.copyFrom(this.position);
  22349. this._cache.upVector.copyFrom(this.upVector);
  22350. };
  22351. // Synchronized
  22352. Camera.prototype._isSynchronized = function () {
  22353. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22354. };
  22355. Camera.prototype._isSynchronizedViewMatrix = function () {
  22356. if (!_super.prototype._isSynchronized.call(this))
  22357. return false;
  22358. return this._cache.position.equals(this.position)
  22359. && this._cache.upVector.equals(this.upVector)
  22360. && this.isSynchronizedWithParent();
  22361. };
  22362. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22363. var check = this._cache.mode === this.mode
  22364. && this._cache.minZ === this.minZ
  22365. && this._cache.maxZ === this.maxZ;
  22366. if (!check) {
  22367. return false;
  22368. }
  22369. var engine = this.getEngine();
  22370. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22371. check = this._cache.fov === this.fov
  22372. && this._cache.fovMode === this.fovMode
  22373. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22374. }
  22375. else {
  22376. check = this._cache.orthoLeft === this.orthoLeft
  22377. && this._cache.orthoRight === this.orthoRight
  22378. && this._cache.orthoBottom === this.orthoBottom
  22379. && this._cache.orthoTop === this.orthoTop
  22380. && this._cache.renderWidth === engine.getRenderWidth()
  22381. && this._cache.renderHeight === engine.getRenderHeight();
  22382. }
  22383. return check;
  22384. };
  22385. // Controls
  22386. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22387. };
  22388. Camera.prototype.detachControl = function (element) {
  22389. };
  22390. Camera.prototype.update = function () {
  22391. this._checkInputs();
  22392. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22393. this._updateRigCameras();
  22394. }
  22395. };
  22396. Camera.prototype._checkInputs = function () {
  22397. this.onAfterCheckInputsObservable.notifyObservers(this);
  22398. };
  22399. Object.defineProperty(Camera.prototype, "rigCameras", {
  22400. get: function () {
  22401. return this._rigCameras;
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22407. get: function () {
  22408. return this._rigPostProcess;
  22409. },
  22410. enumerable: true,
  22411. configurable: true
  22412. });
  22413. /**
  22414. * Internal, gets the first post proces.
  22415. * @returns the first post process to be run on this camera.
  22416. */
  22417. Camera.prototype._getFirstPostProcess = function () {
  22418. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22419. if (this._postProcesses[ppIndex] !== null) {
  22420. return this._postProcesses[ppIndex];
  22421. }
  22422. }
  22423. return null;
  22424. };
  22425. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22426. // invalidate framebuffer
  22427. var firstPostProcess = this._getFirstPostProcess();
  22428. if (firstPostProcess) {
  22429. firstPostProcess.markTextureDirty();
  22430. }
  22431. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22432. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22433. var cam = this._rigCameras[i];
  22434. var rigPostProcess = cam._rigPostProcess;
  22435. // for VR rig, there does not have to be a post process
  22436. if (rigPostProcess) {
  22437. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22438. if (isPass) {
  22439. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22440. cam.isIntermediate = this._postProcesses.length === 0;
  22441. }
  22442. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22443. rigPostProcess.markTextureDirty();
  22444. }
  22445. else {
  22446. cam._postProcesses = this._postProcesses.slice(0);
  22447. }
  22448. }
  22449. };
  22450. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22451. if (insertAt === void 0) { insertAt = null; }
  22452. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22453. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22454. return 0;
  22455. }
  22456. if (insertAt == null || insertAt < 0) {
  22457. this._postProcesses.push(postProcess);
  22458. }
  22459. else if (this._postProcesses[insertAt] === null) {
  22460. this._postProcesses[insertAt] = postProcess;
  22461. }
  22462. else {
  22463. this._postProcesses.splice(insertAt, 0, postProcess);
  22464. }
  22465. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22466. return this._postProcesses.indexOf(postProcess);
  22467. };
  22468. Camera.prototype.detachPostProcess = function (postProcess) {
  22469. var idx = this._postProcesses.indexOf(postProcess);
  22470. if (idx !== -1) {
  22471. this._postProcesses[idx] = null;
  22472. }
  22473. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22474. };
  22475. Camera.prototype.getWorldMatrix = function () {
  22476. if (this._isSynchronizedViewMatrix()) {
  22477. return this._worldMatrix;
  22478. }
  22479. // Getting the the view matrix will also compute the world matrix.
  22480. this.getViewMatrix();
  22481. return this._worldMatrix;
  22482. };
  22483. Camera.prototype._getViewMatrix = function () {
  22484. return BABYLON.Matrix.Identity();
  22485. };
  22486. Camera.prototype.getViewMatrix = function (force) {
  22487. if (!force && this._isSynchronizedViewMatrix()) {
  22488. return this._computedViewMatrix;
  22489. }
  22490. this.updateCache();
  22491. this._computedViewMatrix = this._getViewMatrix();
  22492. this._currentRenderId = this.getScene().getRenderId();
  22493. this._childRenderId = this._currentRenderId;
  22494. this._refreshFrustumPlanes = true;
  22495. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22496. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22497. }
  22498. this.onViewMatrixChangedObservable.notifyObservers(this);
  22499. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22500. return this._computedViewMatrix;
  22501. };
  22502. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22503. this._doNotComputeProjectionMatrix = true;
  22504. if (projection !== undefined) {
  22505. this._projectionMatrix = projection;
  22506. }
  22507. };
  22508. ;
  22509. Camera.prototype.unfreezeProjectionMatrix = function () {
  22510. this._doNotComputeProjectionMatrix = false;
  22511. };
  22512. ;
  22513. Camera.prototype.getProjectionMatrix = function (force) {
  22514. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22515. return this._projectionMatrix;
  22516. }
  22517. // Cache
  22518. this._cache.mode = this.mode;
  22519. this._cache.minZ = this.minZ;
  22520. this._cache.maxZ = this.maxZ;
  22521. // Matrix
  22522. this._refreshFrustumPlanes = true;
  22523. var engine = this.getEngine();
  22524. var scene = this.getScene();
  22525. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22526. this._cache.fov = this.fov;
  22527. this._cache.fovMode = this.fovMode;
  22528. this._cache.aspectRatio = engine.getAspectRatio(this);
  22529. if (this.minZ <= 0) {
  22530. this.minZ = 0.1;
  22531. }
  22532. if (scene.useRightHandedSystem) {
  22533. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22534. }
  22535. else {
  22536. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22537. }
  22538. }
  22539. else {
  22540. var halfWidth = engine.getRenderWidth() / 2.0;
  22541. var halfHeight = engine.getRenderHeight() / 2.0;
  22542. if (scene.useRightHandedSystem) {
  22543. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22544. }
  22545. else {
  22546. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22547. }
  22548. this._cache.orthoLeft = this.orthoLeft;
  22549. this._cache.orthoRight = this.orthoRight;
  22550. this._cache.orthoBottom = this.orthoBottom;
  22551. this._cache.orthoTop = this.orthoTop;
  22552. this._cache.renderWidth = engine.getRenderWidth();
  22553. this._cache.renderHeight = engine.getRenderHeight();
  22554. }
  22555. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22556. return this._projectionMatrix;
  22557. };
  22558. Camera.prototype.getTranformationMatrix = function () {
  22559. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22560. return this._transformMatrix;
  22561. };
  22562. Camera.prototype.updateFrustumPlanes = function () {
  22563. if (!this._refreshFrustumPlanes) {
  22564. return;
  22565. }
  22566. this.getTranformationMatrix();
  22567. if (!this._frustumPlanes) {
  22568. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22569. }
  22570. else {
  22571. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22572. }
  22573. this._refreshFrustumPlanes = false;
  22574. };
  22575. Camera.prototype.isInFrustum = function (target) {
  22576. this.updateFrustumPlanes();
  22577. return target.isInFrustum(this._frustumPlanes);
  22578. };
  22579. Camera.prototype.isCompletelyInFrustum = function (target) {
  22580. this.updateFrustumPlanes();
  22581. return target.isCompletelyInFrustum(this._frustumPlanes);
  22582. };
  22583. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22584. if (length === void 0) { length = 100; }
  22585. if (!transform) {
  22586. transform = this.getWorldMatrix();
  22587. }
  22588. if (!origin) {
  22589. origin = this.position;
  22590. }
  22591. var forward = new BABYLON.Vector3(0, 0, 1);
  22592. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22593. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22594. return new BABYLON.Ray(origin, direction, length);
  22595. };
  22596. /**
  22597. * Releases resources associated with this node.
  22598. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22599. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22600. */
  22601. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22602. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22603. // Observables
  22604. this.onViewMatrixChangedObservable.clear();
  22605. this.onProjectionMatrixChangedObservable.clear();
  22606. this.onAfterCheckInputsObservable.clear();
  22607. this.onRestoreStateObservable.clear();
  22608. // Inputs
  22609. if (this.inputs) {
  22610. this.inputs.clear();
  22611. }
  22612. // Animations
  22613. this.getScene().stopAnimation(this);
  22614. // Remove from scene
  22615. this.getScene().removeCamera(this);
  22616. while (this._rigCameras.length > 0) {
  22617. var camera = this._rigCameras.pop();
  22618. if (camera) {
  22619. camera.dispose();
  22620. }
  22621. }
  22622. // Postprocesses
  22623. if (this._rigPostProcess) {
  22624. this._rigPostProcess.dispose(this);
  22625. this._rigPostProcess = null;
  22626. this._postProcesses = [];
  22627. }
  22628. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22629. this._rigPostProcess = null;
  22630. this._postProcesses = [];
  22631. }
  22632. else {
  22633. var i = this._postProcesses.length;
  22634. while (--i >= 0) {
  22635. var postProcess = this._postProcesses[i];
  22636. if (postProcess) {
  22637. postProcess.dispose(this);
  22638. }
  22639. }
  22640. }
  22641. // Render targets
  22642. var i = this.customRenderTargets.length;
  22643. while (--i >= 0) {
  22644. this.customRenderTargets[i].dispose();
  22645. }
  22646. this.customRenderTargets = [];
  22647. // Active Meshes
  22648. this._activeMeshes.dispose();
  22649. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22650. };
  22651. Object.defineProperty(Camera.prototype, "leftCamera", {
  22652. // ---- Camera rigs section ----
  22653. get: function () {
  22654. if (this._rigCameras.length < 1) {
  22655. return null;
  22656. }
  22657. return this._rigCameras[0];
  22658. },
  22659. enumerable: true,
  22660. configurable: true
  22661. });
  22662. Object.defineProperty(Camera.prototype, "rightCamera", {
  22663. get: function () {
  22664. if (this._rigCameras.length < 2) {
  22665. return null;
  22666. }
  22667. return this._rigCameras[1];
  22668. },
  22669. enumerable: true,
  22670. configurable: true
  22671. });
  22672. Camera.prototype.getLeftTarget = function () {
  22673. if (this._rigCameras.length < 1) {
  22674. return null;
  22675. }
  22676. return this._rigCameras[0].getTarget();
  22677. };
  22678. Camera.prototype.getRightTarget = function () {
  22679. if (this._rigCameras.length < 2) {
  22680. return null;
  22681. }
  22682. return this._rigCameras[1].getTarget();
  22683. };
  22684. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22685. if (this.cameraRigMode === mode) {
  22686. return;
  22687. }
  22688. while (this._rigCameras.length > 0) {
  22689. var camera = this._rigCameras.pop();
  22690. if (camera) {
  22691. camera.dispose();
  22692. }
  22693. }
  22694. this.cameraRigMode = mode;
  22695. this._cameraRigParams = {};
  22696. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22697. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22698. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22699. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22700. // create the rig cameras, unless none
  22701. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22702. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22703. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22704. if (leftCamera && rightCamera) {
  22705. this._rigCameras.push(leftCamera);
  22706. this._rigCameras.push(rightCamera);
  22707. }
  22708. }
  22709. switch (this.cameraRigMode) {
  22710. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22711. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22712. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22713. break;
  22714. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22715. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22716. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22717. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22718. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22719. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22720. break;
  22721. case Camera.RIG_MODE_VR:
  22722. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22723. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22724. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22725. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22726. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22727. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22728. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22729. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22730. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22731. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22732. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22733. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22734. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22735. if (metrics.compensateDistortion) {
  22736. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22737. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22738. }
  22739. break;
  22740. case Camera.RIG_MODE_WEBVR:
  22741. if (rigParams.vrDisplay) {
  22742. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22743. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22744. //Left eye
  22745. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22746. this._rigCameras[0].setCameraRigParameter("left", true);
  22747. //leaving this for future reference
  22748. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22749. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22750. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22751. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22752. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22753. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22754. this._rigCameras[0].parent = this;
  22755. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22756. //Right eye
  22757. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22758. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22759. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22760. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22761. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22762. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22763. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22764. this._rigCameras[1].parent = this;
  22765. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22766. if (Camera.UseAlternateWebVRRendering) {
  22767. this._rigCameras[1]._skipRendering = true;
  22768. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22769. }
  22770. }
  22771. break;
  22772. }
  22773. this._cascadePostProcessesToRigCams();
  22774. this.update();
  22775. };
  22776. Camera.prototype._getVRProjectionMatrix = function () {
  22777. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22778. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22779. return this._projectionMatrix;
  22780. };
  22781. Camera.prototype._updateCameraRotationMatrix = function () {
  22782. //Here for WebVR
  22783. };
  22784. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22785. //Here for WebVR
  22786. };
  22787. /**
  22788. * This function MUST be overwritten by the different WebVR cameras available.
  22789. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22790. */
  22791. Camera.prototype._getWebVRProjectionMatrix = function () {
  22792. return BABYLON.Matrix.Identity();
  22793. };
  22794. /**
  22795. * This function MUST be overwritten by the different WebVR cameras available.
  22796. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22797. */
  22798. Camera.prototype._getWebVRViewMatrix = function () {
  22799. return BABYLON.Matrix.Identity();
  22800. };
  22801. Camera.prototype.setCameraRigParameter = function (name, value) {
  22802. if (!this._cameraRigParams) {
  22803. this._cameraRigParams = {};
  22804. }
  22805. this._cameraRigParams[name] = value;
  22806. //provisionnally:
  22807. if (name === "interaxialDistance") {
  22808. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22809. }
  22810. };
  22811. /**
  22812. * needs to be overridden by children so sub has required properties to be copied
  22813. */
  22814. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22815. return null;
  22816. };
  22817. /**
  22818. * May need to be overridden by children
  22819. */
  22820. Camera.prototype._updateRigCameras = function () {
  22821. for (var i = 0; i < this._rigCameras.length; i++) {
  22822. this._rigCameras[i].minZ = this.minZ;
  22823. this._rigCameras[i].maxZ = this.maxZ;
  22824. this._rigCameras[i].fov = this.fov;
  22825. }
  22826. // only update viewport when ANAGLYPH
  22827. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22828. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22829. }
  22830. };
  22831. Camera.prototype._setupInputs = function () {
  22832. };
  22833. Camera.prototype.serialize = function () {
  22834. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22835. // Type
  22836. serializationObject.type = this.getClassName();
  22837. // Parent
  22838. if (this.parent) {
  22839. serializationObject.parentId = this.parent.id;
  22840. }
  22841. if (this.inputs) {
  22842. this.inputs.serialize(serializationObject);
  22843. }
  22844. // Animations
  22845. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22846. serializationObject.ranges = this.serializeAnimationRanges();
  22847. return serializationObject;
  22848. };
  22849. Camera.prototype.clone = function (name) {
  22850. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22851. };
  22852. Camera.prototype.getDirection = function (localAxis) {
  22853. var result = BABYLON.Vector3.Zero();
  22854. this.getDirectionToRef(localAxis, result);
  22855. return result;
  22856. };
  22857. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22858. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22859. };
  22860. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22861. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22862. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22863. switch (type) {
  22864. case "ArcRotateCamera":
  22865. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22866. case "DeviceOrientationCamera":
  22867. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22868. case "FollowCamera":
  22869. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22870. case "ArcFollowCamera":
  22871. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22872. case "GamepadCamera":
  22873. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22874. case "TouchCamera":
  22875. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22876. case "VirtualJoysticksCamera":
  22877. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22878. case "WebVRFreeCamera":
  22879. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22880. case "WebVRGamepadCamera":
  22881. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22882. case "VRDeviceOrientationFreeCamera":
  22883. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22884. case "VRDeviceOrientationGamepadCamera":
  22885. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22886. case "AnaglyphArcRotateCamera":
  22887. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22888. case "AnaglyphFreeCamera":
  22889. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22890. case "AnaglyphGamepadCamera":
  22891. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22892. case "AnaglyphUniversalCamera":
  22893. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22894. case "StereoscopicArcRotateCamera":
  22895. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22896. case "StereoscopicFreeCamera":
  22897. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22898. case "StereoscopicGamepadCamera":
  22899. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22900. case "StereoscopicUniversalCamera":
  22901. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22902. case "FreeCamera": // Forcing Universal here
  22903. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22904. default: // Universal Camera is the default value
  22905. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22906. }
  22907. };
  22908. Camera.prototype.computeWorldMatrix = function () {
  22909. return this.getWorldMatrix();
  22910. };
  22911. Camera.Parse = function (parsedCamera, scene) {
  22912. var type = parsedCamera.type;
  22913. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22914. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22915. // Parent
  22916. if (parsedCamera.parentId) {
  22917. camera._waitingParentId = parsedCamera.parentId;
  22918. }
  22919. //If camera has an input manager, let it parse inputs settings
  22920. if (camera.inputs) {
  22921. camera.inputs.parse(parsedCamera);
  22922. camera._setupInputs();
  22923. }
  22924. if (camera.setPosition) { // need to force position
  22925. camera.position.copyFromFloats(0, 0, 0);
  22926. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22927. }
  22928. // Target
  22929. if (parsedCamera.target) {
  22930. if (camera.setTarget) {
  22931. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22932. }
  22933. }
  22934. // Apply 3d rig, when found
  22935. if (parsedCamera.cameraRigMode) {
  22936. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22937. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22938. }
  22939. // Animations
  22940. if (parsedCamera.animations) {
  22941. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22942. var parsedAnimation = parsedCamera.animations[animationIndex];
  22943. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22944. }
  22945. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22946. }
  22947. if (parsedCamera.autoAnimate) {
  22948. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22949. }
  22950. return camera;
  22951. };
  22952. // Statics
  22953. Camera._PERSPECTIVE_CAMERA = 0;
  22954. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22955. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22956. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22957. Camera._RIG_MODE_NONE = 0;
  22958. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22959. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22960. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22961. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22962. Camera._RIG_MODE_VR = 20;
  22963. Camera._RIG_MODE_WEBVR = 21;
  22964. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22965. Camera.UseAlternateWebVRRendering = false;
  22966. __decorate([
  22967. BABYLON.serializeAsVector3()
  22968. ], Camera.prototype, "position", void 0);
  22969. __decorate([
  22970. BABYLON.serializeAsVector3()
  22971. ], Camera.prototype, "upVector", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], Camera.prototype, "orthoLeft", void 0);
  22975. __decorate([
  22976. BABYLON.serialize()
  22977. ], Camera.prototype, "orthoRight", void 0);
  22978. __decorate([
  22979. BABYLON.serialize()
  22980. ], Camera.prototype, "orthoBottom", void 0);
  22981. __decorate([
  22982. BABYLON.serialize()
  22983. ], Camera.prototype, "orthoTop", void 0);
  22984. __decorate([
  22985. BABYLON.serialize()
  22986. ], Camera.prototype, "fov", void 0);
  22987. __decorate([
  22988. BABYLON.serialize()
  22989. ], Camera.prototype, "minZ", void 0);
  22990. __decorate([
  22991. BABYLON.serialize()
  22992. ], Camera.prototype, "maxZ", void 0);
  22993. __decorate([
  22994. BABYLON.serialize()
  22995. ], Camera.prototype, "inertia", void 0);
  22996. __decorate([
  22997. BABYLON.serialize()
  22998. ], Camera.prototype, "mode", void 0);
  22999. __decorate([
  23000. BABYLON.serialize()
  23001. ], Camera.prototype, "layerMask", void 0);
  23002. __decorate([
  23003. BABYLON.serialize()
  23004. ], Camera.prototype, "fovMode", void 0);
  23005. __decorate([
  23006. BABYLON.serialize()
  23007. ], Camera.prototype, "cameraRigMode", void 0);
  23008. __decorate([
  23009. BABYLON.serialize()
  23010. ], Camera.prototype, "interaxialDistance", void 0);
  23011. __decorate([
  23012. BABYLON.serialize()
  23013. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23014. return Camera;
  23015. }(BABYLON.Node));
  23016. BABYLON.Camera = Camera;
  23017. })(BABYLON || (BABYLON = {}));
  23018. //# sourceMappingURL=babylon.camera.js.map
  23019. var BABYLON;
  23020. (function (BABYLON) {
  23021. var RenderingManager = /** @class */ (function () {
  23022. function RenderingManager(scene) {
  23023. this._renderingGroups = new Array();
  23024. this._autoClearDepthStencil = {};
  23025. this._customOpaqueSortCompareFn = {};
  23026. this._customAlphaTestSortCompareFn = {};
  23027. this._customTransparentSortCompareFn = {};
  23028. this._renderinGroupInfo = null;
  23029. this._scene = scene;
  23030. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23031. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23032. }
  23033. }
  23034. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23035. if (depth === void 0) { depth = true; }
  23036. if (stencil === void 0) { stencil = true; }
  23037. if (this._depthStencilBufferAlreadyCleaned) {
  23038. return;
  23039. }
  23040. this._scene.getEngine().clear(null, false, depth, stencil);
  23041. this._depthStencilBufferAlreadyCleaned = true;
  23042. };
  23043. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23044. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23045. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23046. var info = null;
  23047. if (observable) {
  23048. if (!this._renderinGroupInfo) {
  23049. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23050. }
  23051. info = this._renderinGroupInfo;
  23052. info.scene = this._scene;
  23053. info.camera = this._scene.activeCamera;
  23054. }
  23055. // Dispatch sprites
  23056. if (renderSprites) {
  23057. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23058. var manager = this._scene.spriteManagers[index];
  23059. this.dispatchSprites(manager);
  23060. }
  23061. }
  23062. // Render
  23063. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23064. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23065. var renderingGroup = this._renderingGroups[index];
  23066. if (!renderingGroup && !observable)
  23067. continue;
  23068. var renderingGroupMask = 0;
  23069. // Fire PRECLEAR stage
  23070. if (observable && info) {
  23071. renderingGroupMask = Math.pow(2, index);
  23072. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23073. info.renderingGroupId = index;
  23074. observable.notifyObservers(info, renderingGroupMask);
  23075. }
  23076. // Clear depth/stencil if needed
  23077. if (RenderingManager.AUTOCLEAR) {
  23078. var autoClear = this._autoClearDepthStencil[index];
  23079. if (autoClear && autoClear.autoClear) {
  23080. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23081. }
  23082. }
  23083. if (observable && info) {
  23084. // Fire PREOPAQUE stage
  23085. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23086. observable.notifyObservers(info, renderingGroupMask);
  23087. // Fire PRETRANSPARENT stage
  23088. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23089. observable.notifyObservers(info, renderingGroupMask);
  23090. }
  23091. if (renderingGroup)
  23092. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23093. // Fire POSTTRANSPARENT stage
  23094. if (observable && info) {
  23095. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23096. observable.notifyObservers(info, renderingGroupMask);
  23097. }
  23098. }
  23099. };
  23100. RenderingManager.prototype.reset = function () {
  23101. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23102. var renderingGroup = this._renderingGroups[index];
  23103. if (renderingGroup) {
  23104. renderingGroup.prepare();
  23105. }
  23106. }
  23107. };
  23108. RenderingManager.prototype.dispose = function () {
  23109. this.freeRenderingGroups();
  23110. this._renderingGroups.length = 0;
  23111. };
  23112. /**
  23113. * Clear the info related to rendering groups preventing retention points during dispose.
  23114. */
  23115. RenderingManager.prototype.freeRenderingGroups = function () {
  23116. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23117. var renderingGroup = this._renderingGroups[index];
  23118. if (renderingGroup) {
  23119. renderingGroup.dispose();
  23120. }
  23121. }
  23122. };
  23123. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23124. if (this._renderingGroups[renderingGroupId] === undefined) {
  23125. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23126. }
  23127. };
  23128. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23129. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23130. this._prepareRenderingGroup(renderingGroupId);
  23131. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23132. };
  23133. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23134. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23135. this._prepareRenderingGroup(renderingGroupId);
  23136. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23137. };
  23138. /**
  23139. * @param subMesh The submesh to dispatch
  23140. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23141. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23142. */
  23143. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23144. if (mesh === undefined) {
  23145. mesh = subMesh.getMesh();
  23146. }
  23147. var renderingGroupId = mesh.renderingGroupId || 0;
  23148. this._prepareRenderingGroup(renderingGroupId);
  23149. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23150. };
  23151. /**
  23152. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23153. * This allowed control for front to back rendering or reversly depending of the special needs.
  23154. *
  23155. * @param renderingGroupId The rendering group id corresponding to its index
  23156. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23157. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23158. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23159. */
  23160. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23161. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23162. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23163. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23164. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23165. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23166. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23167. if (this._renderingGroups[renderingGroupId]) {
  23168. var group = this._renderingGroups[renderingGroupId];
  23169. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23170. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23171. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23172. }
  23173. };
  23174. /**
  23175. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23176. *
  23177. * @param renderingGroupId The rendering group id corresponding to its index
  23178. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23179. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23180. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23181. */
  23182. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23183. if (depth === void 0) { depth = true; }
  23184. if (stencil === void 0) { stencil = true; }
  23185. this._autoClearDepthStencil[renderingGroupId] = {
  23186. autoClear: autoClearDepthStencil,
  23187. depth: depth,
  23188. stencil: stencil
  23189. };
  23190. };
  23191. /**
  23192. * The max id used for rendering groups (not included)
  23193. */
  23194. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23195. /**
  23196. * The min id used for rendering groups (included)
  23197. */
  23198. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23199. /**
  23200. * Used to globally prevent autoclearing scenes.
  23201. */
  23202. RenderingManager.AUTOCLEAR = true;
  23203. return RenderingManager;
  23204. }());
  23205. BABYLON.RenderingManager = RenderingManager;
  23206. })(BABYLON || (BABYLON = {}));
  23207. //# sourceMappingURL=babylon.renderingManager.js.map
  23208. var BABYLON;
  23209. (function (BABYLON) {
  23210. var RenderingGroup = /** @class */ (function () {
  23211. /**
  23212. * Creates a new rendering group.
  23213. * @param index The rendering group index
  23214. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23215. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23216. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23217. */
  23218. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23219. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23220. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23221. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23222. this.index = index;
  23223. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23224. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23225. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23226. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23227. this._particleSystems = new BABYLON.SmartArray(256);
  23228. this._spriteManagers = new BABYLON.SmartArray(256);
  23229. this._edgesRenderers = new BABYLON.SmartArray(16);
  23230. this._scene = scene;
  23231. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23232. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23233. this.transparentSortCompareFn = transparentSortCompareFn;
  23234. }
  23235. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23236. /**
  23237. * Set the opaque sort comparison function.
  23238. * If null the sub meshes will be render in the order they were created
  23239. */
  23240. set: function (value) {
  23241. this._opaqueSortCompareFn = value;
  23242. if (value) {
  23243. this._renderOpaque = this.renderOpaqueSorted;
  23244. }
  23245. else {
  23246. this._renderOpaque = RenderingGroup.renderUnsorted;
  23247. }
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23253. /**
  23254. * Set the alpha test sort comparison function.
  23255. * If null the sub meshes will be render in the order they were created
  23256. */
  23257. set: function (value) {
  23258. this._alphaTestSortCompareFn = value;
  23259. if (value) {
  23260. this._renderAlphaTest = this.renderAlphaTestSorted;
  23261. }
  23262. else {
  23263. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23264. }
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23270. /**
  23271. * Set the transparent sort comparison function.
  23272. * If null the sub meshes will be render in the order they were created
  23273. */
  23274. set: function (value) {
  23275. if (value) {
  23276. this._transparentSortCompareFn = value;
  23277. }
  23278. else {
  23279. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23280. }
  23281. this._renderTransparent = this.renderTransparentSorted;
  23282. },
  23283. enumerable: true,
  23284. configurable: true
  23285. });
  23286. /**
  23287. * Render all the sub meshes contained in the group.
  23288. * @param customRenderFunction Used to override the default render behaviour of the group.
  23289. * @returns true if rendered some submeshes.
  23290. */
  23291. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23292. if (customRenderFunction) {
  23293. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23294. return;
  23295. }
  23296. var engine = this._scene.getEngine();
  23297. // Depth only
  23298. if (this._depthOnlySubMeshes.length !== 0) {
  23299. engine.setColorWrite(false);
  23300. this._renderAlphaTest(this._depthOnlySubMeshes);
  23301. engine.setColorWrite(true);
  23302. }
  23303. // Opaque
  23304. if (this._opaqueSubMeshes.length !== 0) {
  23305. this._renderOpaque(this._opaqueSubMeshes);
  23306. }
  23307. // Alpha test
  23308. if (this._alphaTestSubMeshes.length !== 0) {
  23309. this._renderAlphaTest(this._alphaTestSubMeshes);
  23310. }
  23311. var stencilState = engine.getStencilBuffer();
  23312. engine.setStencilBuffer(false);
  23313. // Sprites
  23314. if (renderSprites) {
  23315. this._renderSprites();
  23316. }
  23317. // Particles
  23318. if (renderParticles) {
  23319. this._renderParticles(activeMeshes);
  23320. }
  23321. if (this.onBeforeTransparentRendering) {
  23322. this.onBeforeTransparentRendering();
  23323. }
  23324. // Transparent
  23325. if (this._transparentSubMeshes.length !== 0) {
  23326. this._renderTransparent(this._transparentSubMeshes);
  23327. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23328. }
  23329. // Set back stencil to false in case it changes before the edge renderer.
  23330. engine.setStencilBuffer(false);
  23331. // Edges
  23332. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23333. this._edgesRenderers.data[edgesRendererIndex].render();
  23334. }
  23335. // Restore Stencil state.
  23336. engine.setStencilBuffer(stencilState);
  23337. };
  23338. /**
  23339. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23340. * @param subMeshes The submeshes to render
  23341. */
  23342. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23343. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23344. };
  23345. /**
  23346. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23347. * @param subMeshes The submeshes to render
  23348. */
  23349. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23350. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23351. };
  23352. /**
  23353. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23354. * @param subMeshes The submeshes to render
  23355. */
  23356. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23357. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23358. };
  23359. /**
  23360. * Renders the submeshes in a specified order.
  23361. * @param subMeshes The submeshes to sort before render
  23362. * @param sortCompareFn The comparison function use to sort
  23363. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23364. * @param transparent Specifies to activate blending if true
  23365. */
  23366. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23367. var subIndex = 0;
  23368. var subMesh;
  23369. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23370. for (; subIndex < subMeshes.length; subIndex++) {
  23371. subMesh = subMeshes.data[subIndex];
  23372. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23373. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23374. }
  23375. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23376. if (sortCompareFn) {
  23377. sortedArray.sort(sortCompareFn);
  23378. }
  23379. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23380. subMesh = sortedArray[subIndex];
  23381. if (transparent) {
  23382. var material = subMesh.getMaterial();
  23383. if (material && material.needDepthPrePass) {
  23384. var engine = material.getScene().getEngine();
  23385. engine.setColorWrite(false);
  23386. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23387. subMesh.render(false);
  23388. engine.setColorWrite(true);
  23389. }
  23390. }
  23391. subMesh.render(transparent);
  23392. }
  23393. };
  23394. /**
  23395. * Renders the submeshes in the order they were dispatched (no sort applied).
  23396. * @param subMeshes The submeshes to render
  23397. */
  23398. RenderingGroup.renderUnsorted = function (subMeshes) {
  23399. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23400. var submesh = subMeshes.data[subIndex];
  23401. submesh.render(false);
  23402. }
  23403. };
  23404. /**
  23405. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23406. * are rendered back to front if in the same alpha index.
  23407. *
  23408. * @param a The first submesh
  23409. * @param b The second submesh
  23410. * @returns The result of the comparison
  23411. */
  23412. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23413. // Alpha index first
  23414. if (a._alphaIndex > b._alphaIndex) {
  23415. return 1;
  23416. }
  23417. if (a._alphaIndex < b._alphaIndex) {
  23418. return -1;
  23419. }
  23420. // Then distance to camera
  23421. return RenderingGroup.backToFrontSortCompare(a, b);
  23422. };
  23423. /**
  23424. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23425. * are rendered back to front.
  23426. *
  23427. * @param a The first submesh
  23428. * @param b The second submesh
  23429. * @returns The result of the comparison
  23430. */
  23431. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23432. // Then distance to camera
  23433. if (a._distanceToCamera < b._distanceToCamera) {
  23434. return 1;
  23435. }
  23436. if (a._distanceToCamera > b._distanceToCamera) {
  23437. return -1;
  23438. }
  23439. return 0;
  23440. };
  23441. /**
  23442. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23443. * are rendered front to back (prevent overdraw).
  23444. *
  23445. * @param a The first submesh
  23446. * @param b The second submesh
  23447. * @returns The result of the comparison
  23448. */
  23449. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23450. // Then distance to camera
  23451. if (a._distanceToCamera < b._distanceToCamera) {
  23452. return -1;
  23453. }
  23454. if (a._distanceToCamera > b._distanceToCamera) {
  23455. return 1;
  23456. }
  23457. return 0;
  23458. };
  23459. /**
  23460. * Resets the different lists of submeshes to prepare a new frame.
  23461. */
  23462. RenderingGroup.prototype.prepare = function () {
  23463. this._opaqueSubMeshes.reset();
  23464. this._transparentSubMeshes.reset();
  23465. this._alphaTestSubMeshes.reset();
  23466. this._depthOnlySubMeshes.reset();
  23467. this._particleSystems.reset();
  23468. this._spriteManagers.reset();
  23469. this._edgesRenderers.reset();
  23470. };
  23471. RenderingGroup.prototype.dispose = function () {
  23472. this._opaqueSubMeshes.dispose();
  23473. this._transparentSubMeshes.dispose();
  23474. this._alphaTestSubMeshes.dispose();
  23475. this._depthOnlySubMeshes.dispose();
  23476. this._particleSystems.dispose();
  23477. this._spriteManagers.dispose();
  23478. this._edgesRenderers.dispose();
  23479. };
  23480. /**
  23481. * Inserts the submesh in its correct queue depending on its material.
  23482. * @param subMesh The submesh to dispatch
  23483. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23484. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23485. */
  23486. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23487. // Get mesh and materials if not provided
  23488. if (mesh === undefined) {
  23489. mesh = subMesh.getMesh();
  23490. }
  23491. if (material === undefined) {
  23492. material = subMesh.getMaterial();
  23493. }
  23494. if (material === null || material === undefined) {
  23495. return;
  23496. }
  23497. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23498. this._transparentSubMeshes.push(subMesh);
  23499. }
  23500. else if (material.needAlphaTesting()) { // Alpha test
  23501. if (material.needDepthPrePass) {
  23502. this._depthOnlySubMeshes.push(subMesh);
  23503. }
  23504. this._alphaTestSubMeshes.push(subMesh);
  23505. }
  23506. else {
  23507. if (material.needDepthPrePass) {
  23508. this._depthOnlySubMeshes.push(subMesh);
  23509. }
  23510. this._opaqueSubMeshes.push(subMesh); // Opaque
  23511. }
  23512. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23513. this._edgesRenderers.push(mesh._edgesRenderer);
  23514. }
  23515. };
  23516. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23517. this._spriteManagers.push(spriteManager);
  23518. };
  23519. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23520. this._particleSystems.push(particleSystem);
  23521. };
  23522. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23523. if (this._particleSystems.length === 0) {
  23524. return;
  23525. }
  23526. // Particles
  23527. var activeCamera = this._scene.activeCamera;
  23528. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23529. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23530. var particleSystem = this._particleSystems.data[particleIndex];
  23531. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23532. continue;
  23533. }
  23534. var emitter = particleSystem.emitter;
  23535. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23536. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23537. }
  23538. }
  23539. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23540. };
  23541. RenderingGroup.prototype._renderSprites = function () {
  23542. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23543. return;
  23544. }
  23545. // Sprites
  23546. var activeCamera = this._scene.activeCamera;
  23547. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23548. for (var id = 0; id < this._spriteManagers.length; id++) {
  23549. var spriteManager = this._spriteManagers.data[id];
  23550. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23551. spriteManager.render();
  23552. }
  23553. }
  23554. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23555. };
  23556. return RenderingGroup;
  23557. }());
  23558. BABYLON.RenderingGroup = RenderingGroup;
  23559. })(BABYLON || (BABYLON = {}));
  23560. //# sourceMappingURL=babylon.renderingGroup.js.map
  23561. var BABYLON;
  23562. (function (BABYLON) {
  23563. /** @hidden */
  23564. var ClickInfo = /** @class */ (function () {
  23565. function ClickInfo() {
  23566. this._singleClick = false;
  23567. this._doubleClick = false;
  23568. this._hasSwiped = false;
  23569. this._ignore = false;
  23570. }
  23571. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23572. get: function () {
  23573. return this._singleClick;
  23574. },
  23575. set: function (b) {
  23576. this._singleClick = b;
  23577. },
  23578. enumerable: true,
  23579. configurable: true
  23580. });
  23581. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23582. get: function () {
  23583. return this._doubleClick;
  23584. },
  23585. set: function (b) {
  23586. this._doubleClick = b;
  23587. },
  23588. enumerable: true,
  23589. configurable: true
  23590. });
  23591. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23592. get: function () {
  23593. return this._hasSwiped;
  23594. },
  23595. set: function (b) {
  23596. this._hasSwiped = b;
  23597. },
  23598. enumerable: true,
  23599. configurable: true
  23600. });
  23601. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23602. get: function () {
  23603. return this._ignore;
  23604. },
  23605. set: function (b) {
  23606. this._ignore = b;
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. return ClickInfo;
  23612. }());
  23613. /**
  23614. * This class is used by the onRenderingGroupObservable
  23615. */
  23616. var RenderingGroupInfo = /** @class */ (function () {
  23617. function RenderingGroupInfo() {
  23618. }
  23619. /**
  23620. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23621. * This stage will be fired no matter what
  23622. */
  23623. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23624. /**
  23625. * Called before opaque object are rendered.
  23626. * This stage will be fired only if there's 3D Opaque content to render
  23627. */
  23628. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23629. /**
  23630. * Called after the opaque objects are rendered and before the transparent ones
  23631. * This stage will be fired only if there's 3D transparent content to render
  23632. */
  23633. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23634. /**
  23635. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23636. * This stage will be fired no matter what
  23637. */
  23638. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23639. return RenderingGroupInfo;
  23640. }());
  23641. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23642. /**
  23643. * Represents a scene to be rendered by the engine.
  23644. * @see http://doc.babylonjs.com/features/scene
  23645. */
  23646. var Scene = /** @class */ (function () {
  23647. /**
  23648. * Creates a new Scene
  23649. * @param engine defines the engine to use to render this scene
  23650. */
  23651. function Scene(engine) {
  23652. // Members
  23653. /**
  23654. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23655. */
  23656. this.autoClear = true;
  23657. /**
  23658. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23659. */
  23660. this.autoClearDepthAndStencil = true;
  23661. /**
  23662. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23663. */
  23664. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23665. /**
  23666. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23667. */
  23668. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23669. this._forceWireframe = false;
  23670. this._forcePointsCloud = false;
  23671. /**
  23672. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23673. */
  23674. this.forceShowBoundingBoxes = false;
  23675. /**
  23676. * Gets or sets a boolean indicating if animations are enabled
  23677. */
  23678. this.animationsEnabled = true;
  23679. this._animationPropertiesOverride = null;
  23680. /**
  23681. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23682. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23683. */
  23684. this.useConstantAnimationDeltaTime = false;
  23685. /**
  23686. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23687. * Please note that it requires to run a ray cast through the scene on every frame
  23688. */
  23689. this.constantlyUpdateMeshUnderPointer = false;
  23690. /**
  23691. * Defines the HTML cursor to use when hovering over interactive elements
  23692. */
  23693. this.hoverCursor = "pointer";
  23694. /**
  23695. * Defines the HTML default cursor to use (empty by default)
  23696. */
  23697. this.defaultCursor = "";
  23698. /**
  23699. * This is used to call preventDefault() on pointer down
  23700. * in order to block unwanted artifacts like system double clicks
  23701. */
  23702. this.preventDefaultOnPointerDown = true;
  23703. // Metadata
  23704. /**
  23705. * Gets or sets user defined metadata
  23706. */
  23707. this.metadata = null;
  23708. /**
  23709. * Use this array to add regular expressions used to disable offline support for specific urls
  23710. */
  23711. this.disableOfflineSupportExceptionRules = new Array();
  23712. /**
  23713. * An event triggered when the scene is disposed.
  23714. */
  23715. this.onDisposeObservable = new BABYLON.Observable();
  23716. this._onDisposeObserver = null;
  23717. /**
  23718. * An event triggered before rendering the scene (right after animations and physics)
  23719. */
  23720. this.onBeforeRenderObservable = new BABYLON.Observable();
  23721. this._onBeforeRenderObserver = null;
  23722. /**
  23723. * An event triggered after rendering the scene
  23724. */
  23725. this.onAfterRenderObservable = new BABYLON.Observable();
  23726. this._onAfterRenderObserver = null;
  23727. /**
  23728. * An event triggered before animating the scene
  23729. */
  23730. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23731. /**
  23732. * An event triggered after animations processing
  23733. */
  23734. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23735. /**
  23736. * An event triggered before draw calls are ready to be sent
  23737. */
  23738. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23739. /**
  23740. * An event triggered after draw calls have been sent
  23741. */
  23742. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23743. /**
  23744. * An event triggered when physic simulation is about to be run
  23745. */
  23746. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23747. /**
  23748. * An event triggered when physic simulation has been done
  23749. */
  23750. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23751. /**
  23752. * An event triggered when the scene is ready
  23753. */
  23754. this.onReadyObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered before rendering a camera
  23757. */
  23758. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23759. this._onBeforeCameraRenderObserver = null;
  23760. /**
  23761. * An event triggered after rendering a camera
  23762. */
  23763. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23764. this._onAfterCameraRenderObserver = null;
  23765. /**
  23766. * An event triggered when active meshes evaluation is about to start
  23767. */
  23768. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23769. /**
  23770. * An event triggered when active meshes evaluation is done
  23771. */
  23772. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23773. /**
  23774. * An event triggered when particles rendering is about to start
  23775. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23776. */
  23777. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered when particles rendering is done
  23780. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23781. */
  23782. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23783. /**
  23784. * An event triggered when sprites rendering is about to start
  23785. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23786. */
  23787. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when sprites rendering is done
  23790. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23791. */
  23792. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23793. /**
  23794. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23795. */
  23796. this.onDataLoadedObservable = new BABYLON.Observable();
  23797. /**
  23798. * An event triggered when a camera is created
  23799. */
  23800. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23801. /**
  23802. * An event triggered when a camera is removed
  23803. */
  23804. this.onCameraRemovedObservable = new BABYLON.Observable();
  23805. /**
  23806. * An event triggered when a light is created
  23807. */
  23808. this.onNewLightAddedObservable = new BABYLON.Observable();
  23809. /**
  23810. * An event triggered when a light is removed
  23811. */
  23812. this.onLightRemovedObservable = new BABYLON.Observable();
  23813. /**
  23814. * An event triggered when a geometry is created
  23815. */
  23816. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23817. /**
  23818. * An event triggered when a geometry is removed
  23819. */
  23820. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23821. /**
  23822. * An event triggered when a transform node is created
  23823. */
  23824. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23825. /**
  23826. * An event triggered when a transform node is removed
  23827. */
  23828. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23829. /**
  23830. * An event triggered when a mesh is created
  23831. */
  23832. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23833. /**
  23834. * An event triggered when a mesh is removed
  23835. */
  23836. this.onMeshRemovedObservable = new BABYLON.Observable();
  23837. /**
  23838. * An event triggered when render targets are about to be rendered
  23839. * Can happen multiple times per frame.
  23840. */
  23841. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered when render targets were rendered.
  23844. * Can happen multiple times per frame.
  23845. */
  23846. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23847. /**
  23848. * An event triggered before calculating deterministic simulation step
  23849. */
  23850. this.onBeforeStepObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered after calculating deterministic simulation step
  23853. */
  23854. this.onAfterStepObservable = new BABYLON.Observable();
  23855. /**
  23856. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23857. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23858. * 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)
  23859. */
  23860. this.onRenderingGroupObservable = new BABYLON.Observable();
  23861. // Animations
  23862. /**
  23863. * Gets a list of Animations associated with the scene
  23864. */
  23865. this.animations = [];
  23866. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23867. /**
  23868. * 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).
  23869. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23870. */
  23871. this.onPrePointerObservable = new BABYLON.Observable();
  23872. /**
  23873. * Observable event triggered each time an input event is received from the rendering canvas
  23874. */
  23875. this.onPointerObservable = new BABYLON.Observable();
  23876. this._meshPickProceed = false;
  23877. this._currentPickResult = null;
  23878. this._previousPickResult = null;
  23879. this._totalPointersPressed = 0;
  23880. this._doubleClickOccured = false;
  23881. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23882. this.cameraToUseForPointers = null;
  23883. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23884. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23885. this._startingPointerTime = 0;
  23886. this._previousStartingPointerTime = 0;
  23887. this._pointerCaptures = {};
  23888. // Deterministic lockstep
  23889. this._timeAccumulator = 0;
  23890. this._currentStepId = 0;
  23891. this._currentInternalStep = 0;
  23892. // Keyboard
  23893. /**
  23894. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23895. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23896. */
  23897. this.onPreKeyboardObservable = new BABYLON.Observable();
  23898. /**
  23899. * Observable event triggered each time an keyboard event is received from the hosting window
  23900. */
  23901. this.onKeyboardObservable = new BABYLON.Observable();
  23902. // Coordinates system
  23903. this._useRightHandedSystem = false;
  23904. // Fog
  23905. this._fogEnabled = true;
  23906. this._fogMode = Scene.FOGMODE_NONE;
  23907. /**
  23908. * Gets or sets the fog color to use
  23909. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23910. */
  23911. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23912. /**
  23913. * Gets or sets the fog density to use
  23914. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23915. */
  23916. this.fogDensity = 0.1;
  23917. /**
  23918. * Gets or sets the fog start distance to use
  23919. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23920. */
  23921. this.fogStart = 0;
  23922. /**
  23923. * Gets or sets the fog end distance to use
  23924. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23925. */
  23926. this.fogEnd = 1000.0;
  23927. // Lights
  23928. this._shadowsEnabled = true;
  23929. this._lightsEnabled = true;
  23930. /**
  23931. * All of the lights added to this scene
  23932. * @see http://doc.babylonjs.com/babylon101/lights
  23933. */
  23934. this.lights = new Array();
  23935. // Cameras
  23936. /** All of the cameras added to this scene.
  23937. * @see http://doc.babylonjs.com/babylon101/cameras
  23938. */
  23939. this.cameras = new Array();
  23940. /** All of the active cameras added to this scene. */
  23941. this.activeCameras = new Array();
  23942. // Meshes
  23943. /**
  23944. * All of the tranform nodes added to this scene
  23945. * @see http://doc.babylonjs.com/how_to/transformnode
  23946. */
  23947. this.transformNodes = new Array();
  23948. /**
  23949. * All of the (abstract) meshes added to this scene
  23950. */
  23951. this.meshes = new Array();
  23952. /**
  23953. * All of the animation groups added to this scene
  23954. * @see http://doc.babylonjs.com/how_to/group
  23955. */
  23956. this.animationGroups = new Array();
  23957. // Geometries
  23958. this._geometries = new Array();
  23959. /**
  23960. * All of the materials added to this scene
  23961. * @see http://doc.babylonjs.com/babylon101/materials
  23962. */
  23963. this.materials = new Array();
  23964. /**
  23965. * All of the multi-materials added to this scene
  23966. * @see http://doc.babylonjs.com/how_to/multi_materials
  23967. */
  23968. this.multiMaterials = new Array();
  23969. // Textures
  23970. this._texturesEnabled = true;
  23971. /**
  23972. * All of the textures added to this scene
  23973. */
  23974. this.textures = new Array();
  23975. // Particles
  23976. /**
  23977. * Gets or sets a boolean indicating if particles are enabled on this scene
  23978. */
  23979. this.particlesEnabled = true;
  23980. /**
  23981. * All of the particle systems added to this scene
  23982. * @see http://doc.babylonjs.com/babylon101/particles
  23983. */
  23984. this.particleSystems = new Array();
  23985. // Sprites
  23986. /**
  23987. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23988. */
  23989. this.spritesEnabled = true;
  23990. /**
  23991. * All of the sprite managers added to this scene
  23992. * @see http://doc.babylonjs.com/babylon101/sprites
  23993. */
  23994. this.spriteManagers = new Array();
  23995. /**
  23996. * The list of layers (background and foreground) of the scene
  23997. */
  23998. this.layers = new Array();
  23999. /**
  24000. * The list of effect layers (highlights/glow) added to the scene
  24001. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24002. * @see http://doc.babylonjs.com/how_to/glow_layer
  24003. */
  24004. this.effectLayers = new Array();
  24005. // Skeletons
  24006. this._skeletonsEnabled = true;
  24007. /**
  24008. * The list of skeletons added to the scene
  24009. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24010. */
  24011. this.skeletons = new Array();
  24012. // Morph targets
  24013. /**
  24014. * The list of morph target managers added to the scene
  24015. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24016. */
  24017. this.morphTargetManagers = new Array();
  24018. // Lens flares
  24019. /**
  24020. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24021. */
  24022. this.lensFlaresEnabled = true;
  24023. /**
  24024. * The list of lens flare system added to the scene
  24025. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24026. */
  24027. this.lensFlareSystems = new Array();
  24028. // Collisions
  24029. /**
  24030. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24031. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24032. */
  24033. this.collisionsEnabled = true;
  24034. /**
  24035. * Defines the gravity applied to this scene (used only for collisions)
  24036. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24037. */
  24038. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24039. // Postprocesses
  24040. /**
  24041. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24042. */
  24043. this.postProcessesEnabled = true;
  24044. /**
  24045. * The list of postprocesses added to the scene
  24046. */
  24047. this.postProcesses = new Array();
  24048. // Customs render targets
  24049. /**
  24050. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24051. */
  24052. this.renderTargetsEnabled = true;
  24053. /**
  24054. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24055. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24056. */
  24057. this.dumpNextRenderTargets = false;
  24058. /**
  24059. * The list of user defined render targets added to the scene
  24060. */
  24061. this.customRenderTargets = new Array();
  24062. /**
  24063. * Gets the list of meshes imported to the scene through SceneLoader
  24064. */
  24065. this.importedMeshesFiles = new Array();
  24066. // Probes
  24067. /**
  24068. * Gets or sets a boolean indicating if probes are enabled on this scene
  24069. */
  24070. this.probesEnabled = true;
  24071. /**
  24072. * The list of reflection probes added to the scene
  24073. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24074. */
  24075. this.reflectionProbes = new Array();
  24076. /** @hidden */
  24077. this._actionManagers = new Array();
  24078. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24079. // Procedural textures
  24080. /**
  24081. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24082. */
  24083. this.proceduralTexturesEnabled = true;
  24084. /**
  24085. * The list of procedural textures added to the scene
  24086. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24087. */
  24088. this.proceduralTextures = new Array();
  24089. /**
  24090. * The list of sound tracks added to the scene
  24091. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24092. */
  24093. this.soundTracks = new Array();
  24094. this._audioEnabled = true;
  24095. this._headphone = false;
  24096. // Performance counters
  24097. this._totalVertices = new BABYLON.PerfCounter();
  24098. /** @hidden */
  24099. this._activeIndices = new BABYLON.PerfCounter();
  24100. /** @hidden */
  24101. this._activeParticles = new BABYLON.PerfCounter();
  24102. /** @hidden */
  24103. this._activeBones = new BABYLON.PerfCounter();
  24104. this._animationTime = 0;
  24105. /**
  24106. * Gets or sets a general scale for animation speed
  24107. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24108. */
  24109. this.animationTimeScale = 1;
  24110. this._renderId = 0;
  24111. this._executeWhenReadyTimeoutId = -1;
  24112. this._intermediateRendering = false;
  24113. this._viewUpdateFlag = -1;
  24114. this._projectionUpdateFlag = -1;
  24115. this._alternateViewUpdateFlag = -1;
  24116. this._alternateProjectionUpdateFlag = -1;
  24117. /** @hidden */
  24118. this._toBeDisposed = new BABYLON.SmartArray(256);
  24119. this._activeRequests = new Array();
  24120. this._pendingData = new Array();
  24121. this._isDisposed = false;
  24122. /**
  24123. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24124. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24125. */
  24126. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24127. this._activeMeshes = new BABYLON.SmartArray(256);
  24128. this._processedMaterials = new BABYLON.SmartArray(256);
  24129. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24130. /** @hidden */
  24131. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24132. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24133. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24134. /** @hidden */
  24135. this._activeAnimatables = new Array();
  24136. this._transformMatrix = BABYLON.Matrix.Zero();
  24137. this._useAlternateCameraConfiguration = false;
  24138. this._alternateRendering = false;
  24139. /**
  24140. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24141. * This is useful if there are more lights that the maximum simulteanous authorized
  24142. */
  24143. this.requireLightSorting = false;
  24144. this._depthRenderer = {};
  24145. this._activeMeshesFrozen = false;
  24146. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24147. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24148. this._engine.scenes.push(this);
  24149. this._uid = null;
  24150. this._renderingManager = new BABYLON.RenderingManager(this);
  24151. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24152. if (BABYLON.OutlineRenderer) {
  24153. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24154. }
  24155. if (BABYLON.Tools.IsWindowObjectExist()) {
  24156. this.attachControl();
  24157. }
  24158. //simplification queue
  24159. if (BABYLON.SimplificationQueue) {
  24160. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24161. }
  24162. //collision coordinator initialization. For now legacy per default.
  24163. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24164. // Uniform Buffer
  24165. this._createUbo();
  24166. // Default Image processing definition.
  24167. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24168. }
  24169. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24170. /** The fog is deactivated */
  24171. get: function () {
  24172. return Scene._FOGMODE_NONE;
  24173. },
  24174. enumerable: true,
  24175. configurable: true
  24176. });
  24177. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24178. /** The fog density is following an exponential function */
  24179. get: function () {
  24180. return Scene._FOGMODE_EXP;
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24186. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24187. get: function () {
  24188. return Scene._FOGMODE_EXP2;
  24189. },
  24190. enumerable: true,
  24191. configurable: true
  24192. });
  24193. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24194. /** The fog density is following a linear function. */
  24195. get: function () {
  24196. return Scene._FOGMODE_LINEAR;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24202. /**
  24203. * Texture used in all pbr material as the reflection texture.
  24204. * As in the majority of the scene they are the same (exception for multi room and so on),
  24205. * this is easier to reference from here than from all the materials.
  24206. */
  24207. get: function () {
  24208. return this._environmentTexture;
  24209. },
  24210. /**
  24211. * Texture used in all pbr material as the reflection texture.
  24212. * As in the majority of the scene they are the same (exception for multi room and so on),
  24213. * this is easier to set here than in all the materials.
  24214. */
  24215. set: function (value) {
  24216. if (this._environmentTexture === value) {
  24217. return;
  24218. }
  24219. this._environmentTexture = value;
  24220. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24226. /**
  24227. * Default image processing configuration used either in the rendering
  24228. * Forward main pass or through the imageProcessingPostProcess if present.
  24229. * As in the majority of the scene they are the same (exception for multi camera),
  24230. * this is easier to reference from here than from all the materials and post process.
  24231. *
  24232. * No setter as we it is a shared configuration, you can set the values instead.
  24233. */
  24234. get: function () {
  24235. return this._imageProcessingConfiguration;
  24236. },
  24237. enumerable: true,
  24238. configurable: true
  24239. });
  24240. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24241. get: function () {
  24242. return this._forceWireframe;
  24243. },
  24244. /**
  24245. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24246. */
  24247. set: function (value) {
  24248. if (this._forceWireframe === value) {
  24249. return;
  24250. }
  24251. this._forceWireframe = value;
  24252. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24258. get: function () {
  24259. return this._forcePointsCloud;
  24260. },
  24261. /**
  24262. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24263. */
  24264. set: function (value) {
  24265. if (this._forcePointsCloud === value) {
  24266. return;
  24267. }
  24268. this._forcePointsCloud = value;
  24269. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24275. /**
  24276. * Gets or sets the animation properties override
  24277. */
  24278. get: function () {
  24279. return this._animationPropertiesOverride;
  24280. },
  24281. set: function (value) {
  24282. this._animationPropertiesOverride = value;
  24283. },
  24284. enumerable: true,
  24285. configurable: true
  24286. });
  24287. Object.defineProperty(Scene.prototype, "onDispose", {
  24288. /** Sets a function to be executed when this scene is disposed. */
  24289. set: function (callback) {
  24290. if (this._onDisposeObserver) {
  24291. this.onDisposeObservable.remove(this._onDisposeObserver);
  24292. }
  24293. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24294. },
  24295. enumerable: true,
  24296. configurable: true
  24297. });
  24298. Object.defineProperty(Scene.prototype, "beforeRender", {
  24299. /** Sets a function to be executed before rendering this scene */
  24300. set: function (callback) {
  24301. if (this._onBeforeRenderObserver) {
  24302. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24303. }
  24304. if (callback) {
  24305. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24306. }
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. Object.defineProperty(Scene.prototype, "afterRender", {
  24312. /** Sets a function to be executed after rendering this scene */
  24313. set: function (callback) {
  24314. if (this._onAfterRenderObserver) {
  24315. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24316. }
  24317. if (callback) {
  24318. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24319. }
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24325. /** Sets a function to be executed before rendering a camera*/
  24326. set: function (callback) {
  24327. if (this._onBeforeCameraRenderObserver) {
  24328. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24329. }
  24330. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24331. },
  24332. enumerable: true,
  24333. configurable: true
  24334. });
  24335. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24336. /** Sets a function to be executed after rendering a camera*/
  24337. set: function (callback) {
  24338. if (this._onAfterCameraRenderObserver) {
  24339. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24340. }
  24341. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24347. /**
  24348. * Gets the gamepad manager associated with the scene
  24349. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24350. */
  24351. get: function () {
  24352. if (!this._gamepadManager) {
  24353. this._gamepadManager = new BABYLON.GamepadManager(this);
  24354. }
  24355. return this._gamepadManager;
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24361. /**
  24362. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24363. */
  24364. get: function () {
  24365. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24366. },
  24367. enumerable: true,
  24368. configurable: true
  24369. });
  24370. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24371. get: function () {
  24372. return this._useRightHandedSystem;
  24373. },
  24374. /**
  24375. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24376. */
  24377. set: function (value) {
  24378. if (this._useRightHandedSystem === value) {
  24379. return;
  24380. }
  24381. this._useRightHandedSystem = value;
  24382. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. /**
  24388. * Sets the step Id used by deterministic lock step
  24389. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24390. * @param newStepId defines the step Id
  24391. */
  24392. Scene.prototype.setStepId = function (newStepId) {
  24393. this._currentStepId = newStepId;
  24394. };
  24395. ;
  24396. /**
  24397. * Gets the step Id used by deterministic lock step
  24398. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24399. * @returns the step Id
  24400. */
  24401. Scene.prototype.getStepId = function () {
  24402. return this._currentStepId;
  24403. };
  24404. ;
  24405. /**
  24406. * Gets the internal step used by deterministic lock step
  24407. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24408. * @returns the internal step
  24409. */
  24410. Scene.prototype.getInternalStep = function () {
  24411. return this._currentInternalStep;
  24412. };
  24413. ;
  24414. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24415. get: function () {
  24416. return this._fogEnabled;
  24417. },
  24418. /**
  24419. * Gets or sets a boolean indicating if fog is enabled on this scene
  24420. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24421. */
  24422. set: function (value) {
  24423. if (this._fogEnabled === value) {
  24424. return;
  24425. }
  24426. this._fogEnabled = value;
  24427. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Object.defineProperty(Scene.prototype, "fogMode", {
  24433. get: function () {
  24434. return this._fogMode;
  24435. },
  24436. /**
  24437. * Gets or sets the fog mode to use
  24438. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24439. */
  24440. set: function (value) {
  24441. if (this._fogMode === value) {
  24442. return;
  24443. }
  24444. this._fogMode = value;
  24445. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24451. get: function () {
  24452. return this._shadowsEnabled;
  24453. },
  24454. /**
  24455. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24456. */
  24457. set: function (value) {
  24458. if (this._shadowsEnabled === value) {
  24459. return;
  24460. }
  24461. this._shadowsEnabled = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24468. get: function () {
  24469. return this._lightsEnabled;
  24470. },
  24471. /**
  24472. * Gets or sets a boolean indicating if lights are enabled on this scene
  24473. */
  24474. set: function (value) {
  24475. if (this._lightsEnabled === value) {
  24476. return;
  24477. }
  24478. this._lightsEnabled = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24485. /** The default material used on meshes when no material is affected */
  24486. get: function () {
  24487. if (!this._defaultMaterial) {
  24488. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24489. }
  24490. return this._defaultMaterial;
  24491. },
  24492. /** The default material used on meshes when no material is affected */
  24493. set: function (value) {
  24494. this._defaultMaterial = value;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24500. get: function () {
  24501. return this._texturesEnabled;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if textures are enabled on this scene
  24505. */
  24506. set: function (value) {
  24507. if (this._texturesEnabled === value) {
  24508. return;
  24509. }
  24510. this._texturesEnabled = value;
  24511. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24517. get: function () {
  24518. return this._skeletonsEnabled;
  24519. },
  24520. /**
  24521. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24522. */
  24523. set: function (value) {
  24524. if (this._skeletonsEnabled === value) {
  24525. return;
  24526. }
  24527. this._skeletonsEnabled = value;
  24528. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24534. /**
  24535. * Gets the postprocess render pipeline manager
  24536. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24537. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24538. */
  24539. get: function () {
  24540. if (!this._postProcessRenderPipelineManager) {
  24541. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24542. }
  24543. return this._postProcessRenderPipelineManager;
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24549. /**
  24550. * Gets the main soundtrack associated with the scene
  24551. */
  24552. get: function () {
  24553. if (!this._mainSoundTrack) {
  24554. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24555. }
  24556. return this._mainSoundTrack;
  24557. },
  24558. enumerable: true,
  24559. configurable: true
  24560. });
  24561. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24562. /** @hidden */
  24563. get: function () {
  24564. return this._alternateRendering;
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24570. /**
  24571. * Gets the list of frustum planes (built from the active camera)
  24572. */
  24573. get: function () {
  24574. return this._frustumPlanes;
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24580. /**
  24581. * Gets the current geometry buffer associated to the scene.
  24582. */
  24583. get: function () {
  24584. return this._geometryBufferRenderer;
  24585. },
  24586. /**
  24587. * Sets the current geometry buffer for the scene.
  24588. */
  24589. set: function (geometryBufferRenderer) {
  24590. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24591. this._geometryBufferRenderer = geometryBufferRenderer;
  24592. }
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. Object.defineProperty(Scene.prototype, "debugLayer", {
  24598. /**
  24599. * Gets the debug layer associated with the scene
  24600. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24601. */
  24602. get: function () {
  24603. if (!this._debugLayer) {
  24604. this._debugLayer = new BABYLON.DebugLayer(this);
  24605. }
  24606. return this._debugLayer;
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24612. /**
  24613. * Gets a boolean indicating if collisions are processed on a web worker
  24614. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24615. */
  24616. get: function () {
  24617. return this._workerCollisions;
  24618. },
  24619. set: function (enabled) {
  24620. if (!BABYLON.CollisionCoordinatorLegacy) {
  24621. return;
  24622. }
  24623. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24624. this._workerCollisions = enabled;
  24625. if (this.collisionCoordinator) {
  24626. this.collisionCoordinator.destroy();
  24627. }
  24628. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24629. this.collisionCoordinator.init(this);
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24635. /**
  24636. * Gets the octree used to boost mesh selection (picking)
  24637. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24638. */
  24639. get: function () {
  24640. return this._selectionOctree;
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24646. /**
  24647. * Gets the mesh that is currently under the pointer
  24648. */
  24649. get: function () {
  24650. return this._pointerOverMesh;
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(Scene.prototype, "pointerX", {
  24656. /**
  24657. * Gets the current on-screen X position of the pointer
  24658. */
  24659. get: function () {
  24660. return this._pointerX;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. Object.defineProperty(Scene.prototype, "pointerY", {
  24666. /**
  24667. * Gets the current on-screen Y position of the pointer
  24668. */
  24669. get: function () {
  24670. return this._pointerY;
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. /**
  24676. * Gets the cached material (ie. the latest rendered one)
  24677. * @returns the cached material
  24678. */
  24679. Scene.prototype.getCachedMaterial = function () {
  24680. return this._cachedMaterial;
  24681. };
  24682. /**
  24683. * Gets the cached effect (ie. the latest rendered one)
  24684. * @returns the cached effect
  24685. */
  24686. Scene.prototype.getCachedEffect = function () {
  24687. return this._cachedEffect;
  24688. };
  24689. /**
  24690. * Gets the cached visibility state (ie. the latest rendered one)
  24691. * @returns the cached visibility state
  24692. */
  24693. Scene.prototype.getCachedVisibility = function () {
  24694. return this._cachedVisibility;
  24695. };
  24696. /**
  24697. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24698. * @param material defines the current material
  24699. * @param effect defines the current effect
  24700. * @param visibility defines the current visibility state
  24701. * @returns true if one parameter is not cached
  24702. */
  24703. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24704. if (visibility === void 0) { visibility = 1; }
  24705. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24706. };
  24707. /**
  24708. * Gets the bounding box renderer associated with the scene
  24709. * @returns a BoundingBoxRenderer
  24710. */
  24711. Scene.prototype.getBoundingBoxRenderer = function () {
  24712. if (!this._boundingBoxRenderer) {
  24713. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24714. }
  24715. return this._boundingBoxRenderer;
  24716. };
  24717. /**
  24718. * Gets the outline renderer associated with the scene
  24719. * @returns a OutlineRenderer
  24720. */
  24721. Scene.prototype.getOutlineRenderer = function () {
  24722. return this._outlineRenderer;
  24723. };
  24724. /**
  24725. * Gets the engine associated with the scene
  24726. * @returns an Engine
  24727. */
  24728. Scene.prototype.getEngine = function () {
  24729. return this._engine;
  24730. };
  24731. /**
  24732. * Gets the total number of vertices rendered per frame
  24733. * @returns the total number of vertices rendered per frame
  24734. */
  24735. Scene.prototype.getTotalVertices = function () {
  24736. return this._totalVertices.current;
  24737. };
  24738. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24739. /**
  24740. * Gets the performance counter for total vertices
  24741. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24742. */
  24743. get: function () {
  24744. return this._totalVertices;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. /**
  24750. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24751. * @returns the total number of active indices rendered per frame
  24752. */
  24753. Scene.prototype.getActiveIndices = function () {
  24754. return this._activeIndices.current;
  24755. };
  24756. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24757. /**
  24758. * Gets the performance counter for active indices
  24759. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24760. */
  24761. get: function () {
  24762. return this._activeIndices;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. /**
  24768. * Gets the total number of active particles rendered per frame
  24769. * @returns the total number of active particles rendered per frame
  24770. */
  24771. Scene.prototype.getActiveParticles = function () {
  24772. return this._activeParticles.current;
  24773. };
  24774. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24775. /**
  24776. * Gets the performance counter for active particles
  24777. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24778. */
  24779. get: function () {
  24780. return this._activeParticles;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. /**
  24786. * Gets the total number of active bones rendered per frame
  24787. * @returns the total number of active bones rendered per frame
  24788. */
  24789. Scene.prototype.getActiveBones = function () {
  24790. return this._activeBones.current;
  24791. };
  24792. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24793. /**
  24794. * Gets the performance counter for active bones
  24795. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24796. */
  24797. get: function () {
  24798. return this._activeBones;
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. /** @hidden */
  24804. Scene.prototype.getInterFramePerfCounter = function () {
  24805. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24806. return 0;
  24807. };
  24808. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24809. /** @hidden */
  24810. get: function () {
  24811. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24812. return null;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. /** @hidden */
  24818. Scene.prototype.getLastFrameDuration = function () {
  24819. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24820. return 0;
  24821. };
  24822. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24823. /** @hidden */
  24824. get: function () {
  24825. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24826. return null;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. /** @hidden */
  24832. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24833. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24834. return 0;
  24835. };
  24836. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24837. /** @hidden */
  24838. get: function () {
  24839. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24840. return null;
  24841. },
  24842. enumerable: true,
  24843. configurable: true
  24844. });
  24845. /**
  24846. * Gets the array of active meshes
  24847. * @returns an array of AbstractMesh
  24848. */
  24849. Scene.prototype.getActiveMeshes = function () {
  24850. return this._activeMeshes;
  24851. };
  24852. /** @hidden */
  24853. Scene.prototype.getRenderTargetsDuration = function () {
  24854. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24855. return 0;
  24856. };
  24857. /** @hidden */
  24858. Scene.prototype.getRenderDuration = function () {
  24859. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24860. return 0;
  24861. };
  24862. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24863. /** @hidden */
  24864. get: function () {
  24865. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24866. return null;
  24867. },
  24868. enumerable: true,
  24869. configurable: true
  24870. });
  24871. /** @hidden */
  24872. Scene.prototype.getParticlesDuration = function () {
  24873. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24874. return 0;
  24875. };
  24876. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24877. /** @hidden */
  24878. get: function () {
  24879. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24880. return null;
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. /** @hidden */
  24886. Scene.prototype.getSpritesDuration = function () {
  24887. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24888. return 0;
  24889. };
  24890. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24891. /** @hidden */
  24892. get: function () {
  24893. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24894. return null;
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. /**
  24900. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24901. * @returns a number
  24902. */
  24903. Scene.prototype.getAnimationRatio = function () {
  24904. return this._animationRatio;
  24905. };
  24906. /**
  24907. * Gets an unique Id for the current frame
  24908. * @returns a number
  24909. */
  24910. Scene.prototype.getRenderId = function () {
  24911. return this._renderId;
  24912. };
  24913. /** Call this function if you want to manually increment the render Id*/
  24914. Scene.prototype.incrementRenderId = function () {
  24915. this._renderId++;
  24916. };
  24917. Scene.prototype._updatePointerPosition = function (evt) {
  24918. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24919. if (!canvasRect) {
  24920. return;
  24921. }
  24922. this._pointerX = evt.clientX - canvasRect.left;
  24923. this._pointerY = evt.clientY - canvasRect.top;
  24924. this._unTranslatedPointerX = this._pointerX;
  24925. this._unTranslatedPointerY = this._pointerY;
  24926. };
  24927. Scene.prototype._createUbo = function () {
  24928. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24929. this._sceneUbo.addUniform("viewProjection", 16);
  24930. this._sceneUbo.addUniform("view", 16);
  24931. };
  24932. Scene.prototype._createAlternateUbo = function () {
  24933. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24934. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24935. this._alternateSceneUbo.addUniform("view", 16);
  24936. };
  24937. // Pointers handling
  24938. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24939. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24940. if (result) {
  24941. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24942. }
  24943. return result;
  24944. };
  24945. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24946. if (pointerInfo.pickInfo) {
  24947. if (!pointerInfo.pickInfo.ray) {
  24948. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24949. }
  24950. }
  24951. };
  24952. /**
  24953. * Use this method to simulate a pointer move on a mesh
  24954. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24955. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24956. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24957. * @returns the current scene
  24958. */
  24959. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24960. var evt = new PointerEvent("pointermove", pointerEventInit);
  24961. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24962. return this;
  24963. }
  24964. return this._processPointerMove(pickResult, evt);
  24965. };
  24966. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24967. var canvas = this._engine.getRenderingCanvas();
  24968. if (!canvas) {
  24969. return this;
  24970. }
  24971. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24972. this.setPointerOverSprite(null);
  24973. this.setPointerOverMesh(pickResult.pickedMesh);
  24974. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24975. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24976. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24977. }
  24978. else {
  24979. canvas.style.cursor = this.hoverCursor;
  24980. }
  24981. }
  24982. else {
  24983. canvas.style.cursor = this.defaultCursor;
  24984. }
  24985. }
  24986. else {
  24987. this.setPointerOverMesh(null);
  24988. // Sprites
  24989. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24990. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24991. this.setPointerOverSprite(pickResult.pickedSprite);
  24992. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24993. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24994. }
  24995. else {
  24996. canvas.style.cursor = this.hoverCursor;
  24997. }
  24998. }
  24999. else {
  25000. this.setPointerOverSprite(null);
  25001. // Restore pointer
  25002. canvas.style.cursor = this.defaultCursor;
  25003. }
  25004. }
  25005. if (pickResult) {
  25006. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25007. if (this.onPointerMove) {
  25008. this.onPointerMove(evt, pickResult, type);
  25009. }
  25010. if (this.onPointerObservable.hasObservers()) {
  25011. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25012. this._setRayOnPointerInfo(pi);
  25013. this.onPointerObservable.notifyObservers(pi, type);
  25014. }
  25015. }
  25016. return this;
  25017. };
  25018. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25019. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25020. if (pickResult) {
  25021. pi.ray = pickResult.ray;
  25022. }
  25023. this.onPrePointerObservable.notifyObservers(pi, type);
  25024. if (pi.skipOnPointerObservable) {
  25025. return true;
  25026. }
  25027. else {
  25028. return false;
  25029. }
  25030. };
  25031. /**
  25032. * Use this method to simulate a pointer down on a mesh
  25033. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25034. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25035. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25036. * @returns the current scene
  25037. */
  25038. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25039. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25040. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25041. return this;
  25042. }
  25043. return this._processPointerDown(pickResult, evt);
  25044. };
  25045. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25046. var _this = this;
  25047. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25048. this._pickedDownMesh = pickResult.pickedMesh;
  25049. var actionManager = pickResult.pickedMesh.actionManager;
  25050. if (actionManager) {
  25051. if (actionManager.hasPickTriggers) {
  25052. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25053. switch (evt.button) {
  25054. case 0:
  25055. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25056. break;
  25057. case 1:
  25058. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25059. break;
  25060. case 2:
  25061. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25062. break;
  25063. }
  25064. }
  25065. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25066. window.setTimeout(function () {
  25067. 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);
  25068. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25069. if (_this._totalPointersPressed !== 0 &&
  25070. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25071. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25072. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25073. _this._startingPointerTime = 0;
  25074. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25075. }
  25076. }
  25077. }, Scene.LongPressDelay);
  25078. }
  25079. }
  25080. }
  25081. if (pickResult) {
  25082. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25083. if (this.onPointerDown) {
  25084. this.onPointerDown(evt, pickResult, type);
  25085. }
  25086. if (this.onPointerObservable.hasObservers()) {
  25087. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25088. this._setRayOnPointerInfo(pi);
  25089. this.onPointerObservable.notifyObservers(pi, type);
  25090. }
  25091. }
  25092. return this;
  25093. };
  25094. /**
  25095. * Use this method to simulate a pointer up on a mesh
  25096. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25097. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25098. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25099. * @returns the current scene
  25100. */
  25101. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25102. var evt = new PointerEvent("pointerup", pointerEventInit);
  25103. var clickInfo = new ClickInfo();
  25104. clickInfo.singleClick = true;
  25105. clickInfo.ignore = true;
  25106. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25107. return this;
  25108. }
  25109. return this._processPointerUp(pickResult, evt, clickInfo);
  25110. };
  25111. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25112. if (pickResult && pickResult && pickResult.pickedMesh) {
  25113. this._pickedUpMesh = pickResult.pickedMesh;
  25114. if (this._pickedDownMesh === this._pickedUpMesh) {
  25115. if (this.onPointerPick) {
  25116. this.onPointerPick(evt, pickResult);
  25117. }
  25118. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25119. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25120. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25121. this._setRayOnPointerInfo(pi);
  25122. this.onPointerObservable.notifyObservers(pi, type_1);
  25123. }
  25124. }
  25125. if (pickResult.pickedMesh.actionManager) {
  25126. if (clickInfo.ignore) {
  25127. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25128. }
  25129. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25130. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25131. }
  25132. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25133. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25134. }
  25135. }
  25136. }
  25137. if (this._pickedDownMesh &&
  25138. this._pickedDownMesh.actionManager &&
  25139. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25140. this._pickedDownMesh !== this._pickedUpMesh) {
  25141. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25142. }
  25143. var type = BABYLON.PointerEventTypes.POINTERUP;
  25144. if (this.onPointerObservable.hasObservers()) {
  25145. if (!clickInfo.ignore) {
  25146. if (!clickInfo.hasSwiped) {
  25147. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25148. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25149. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25150. this._setRayOnPointerInfo(pi);
  25151. this.onPointerObservable.notifyObservers(pi, type_2);
  25152. }
  25153. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25154. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25155. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25156. this._setRayOnPointerInfo(pi);
  25157. this.onPointerObservable.notifyObservers(pi, type_3);
  25158. }
  25159. }
  25160. }
  25161. else {
  25162. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25163. this._setRayOnPointerInfo(pi);
  25164. this.onPointerObservable.notifyObservers(pi, type);
  25165. }
  25166. }
  25167. if (this.onPointerUp) {
  25168. this.onPointerUp(evt, pickResult, type);
  25169. }
  25170. return this;
  25171. };
  25172. /**
  25173. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25174. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25175. * @returns true if the pointer was captured
  25176. */
  25177. Scene.prototype.isPointerCaptured = function (pointerId) {
  25178. if (pointerId === void 0) { pointerId = 0; }
  25179. return this._pointerCaptures[pointerId];
  25180. };
  25181. /**
  25182. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25183. * @param attachUp defines if you want to attach events to pointerup
  25184. * @param attachDown defines if you want to attach events to pointerdown
  25185. * @param attachMove defines if you want to attach events to pointermove
  25186. */
  25187. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25188. var _this = this;
  25189. if (attachUp === void 0) { attachUp = true; }
  25190. if (attachDown === void 0) { attachDown = true; }
  25191. if (attachMove === void 0) { attachMove = true; }
  25192. this._initActionManager = function (act, clickInfo) {
  25193. if (!_this._meshPickProceed) {
  25194. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25195. _this._currentPickResult = pickResult;
  25196. if (pickResult) {
  25197. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25198. }
  25199. _this._meshPickProceed = true;
  25200. }
  25201. return act;
  25202. };
  25203. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25204. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25205. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25206. btn !== _this._previousButtonPressed) {
  25207. _this._doubleClickOccured = false;
  25208. clickInfo.singleClick = true;
  25209. clickInfo.ignore = false;
  25210. cb(clickInfo, _this._currentPickResult);
  25211. }
  25212. };
  25213. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25214. var clickInfo = new ClickInfo();
  25215. _this._currentPickResult = null;
  25216. var act = null;
  25217. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25218. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25219. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25220. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25221. act = _this._initActionManager(act, clickInfo);
  25222. if (act)
  25223. checkPicking = act.hasPickTriggers;
  25224. }
  25225. if (checkPicking) {
  25226. var btn = evt.button;
  25227. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25228. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25229. if (!clickInfo.hasSwiped) {
  25230. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25231. if (!checkSingleClickImmediately) {
  25232. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25233. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25234. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25235. act = _this._initActionManager(act, clickInfo);
  25236. if (act)
  25237. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25238. }
  25239. }
  25240. if (checkSingleClickImmediately) {
  25241. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25242. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25243. btn !== _this._previousButtonPressed) {
  25244. clickInfo.singleClick = true;
  25245. cb(clickInfo, _this._currentPickResult);
  25246. }
  25247. }
  25248. // at least one double click is required to be check and exclusive double click is enabled
  25249. else {
  25250. // wait that no double click has been raised during the double click delay
  25251. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25252. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25253. }
  25254. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25255. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25256. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25257. act = _this._initActionManager(act, clickInfo);
  25258. if (act)
  25259. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25260. }
  25261. if (checkDoubleClick) {
  25262. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25263. if (btn === _this._previousButtonPressed &&
  25264. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25265. !_this._doubleClickOccured) {
  25266. // pointer has not moved for 2 clicks, it's a double click
  25267. if (!clickInfo.hasSwiped &&
  25268. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25269. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25270. _this._previousStartingPointerTime = 0;
  25271. _this._doubleClickOccured = true;
  25272. clickInfo.doubleClick = true;
  25273. clickInfo.ignore = false;
  25274. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25275. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25276. }
  25277. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25278. cb(clickInfo, _this._currentPickResult);
  25279. }
  25280. // if the two successive clicks are too far, it's just two simple clicks
  25281. else {
  25282. _this._doubleClickOccured = false;
  25283. _this._previousStartingPointerTime = _this._startingPointerTime;
  25284. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25285. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25286. _this._previousButtonPressed = btn;
  25287. if (Scene.ExclusiveDoubleClickMode) {
  25288. if (_this._previousDelayedSimpleClickTimeout) {
  25289. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25290. }
  25291. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25292. cb(clickInfo, _this._previousPickResult);
  25293. }
  25294. else {
  25295. cb(clickInfo, _this._currentPickResult);
  25296. }
  25297. }
  25298. }
  25299. // just the first click of the double has been raised
  25300. else {
  25301. _this._doubleClickOccured = false;
  25302. _this._previousStartingPointerTime = _this._startingPointerTime;
  25303. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25304. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25305. _this._previousButtonPressed = btn;
  25306. }
  25307. }
  25308. }
  25309. }
  25310. clickInfo.ignore = true;
  25311. cb(clickInfo, _this._currentPickResult);
  25312. };
  25313. this._spritePredicate = function (sprite) {
  25314. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25315. };
  25316. this._onPointerMove = function (evt) {
  25317. _this._updatePointerPosition(evt);
  25318. // PreObservable support
  25319. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25320. return;
  25321. }
  25322. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25323. return;
  25324. }
  25325. if (!_this.pointerMovePredicate) {
  25326. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25327. }
  25328. // Meshes
  25329. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25330. _this._processPointerMove(pickResult, evt);
  25331. };
  25332. this._onPointerDown = function (evt) {
  25333. _this._totalPointersPressed++;
  25334. _this._pickedDownMesh = null;
  25335. _this._meshPickProceed = false;
  25336. _this._updatePointerPosition(evt);
  25337. if (_this.preventDefaultOnPointerDown && canvas) {
  25338. evt.preventDefault();
  25339. canvas.focus();
  25340. }
  25341. // PreObservable support
  25342. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25343. return;
  25344. }
  25345. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25346. return;
  25347. }
  25348. _this._pointerCaptures[evt.pointerId] = true;
  25349. _this._startingPointerPosition.x = _this._pointerX;
  25350. _this._startingPointerPosition.y = _this._pointerY;
  25351. _this._startingPointerTime = Date.now();
  25352. if (!_this.pointerDownPredicate) {
  25353. _this.pointerDownPredicate = function (mesh) {
  25354. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25355. };
  25356. }
  25357. // Meshes
  25358. _this._pickedDownMesh = null;
  25359. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25360. _this._processPointerDown(pickResult, evt);
  25361. // Sprites
  25362. _this._pickedDownSprite = null;
  25363. if (_this.spriteManagers.length > 0) {
  25364. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25365. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25366. if (pickResult.pickedSprite.actionManager) {
  25367. _this._pickedDownSprite = pickResult.pickedSprite;
  25368. switch (evt.button) {
  25369. case 0:
  25370. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25371. break;
  25372. case 1:
  25373. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25374. break;
  25375. case 2:
  25376. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25377. break;
  25378. }
  25379. if (pickResult.pickedSprite.actionManager) {
  25380. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25381. }
  25382. }
  25383. }
  25384. }
  25385. };
  25386. this._onPointerUp = function (evt) {
  25387. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25388. return; // So we need to test it the pointer down was pressed before.
  25389. }
  25390. _this._totalPointersPressed--;
  25391. _this._pickedUpMesh = null;
  25392. _this._meshPickProceed = false;
  25393. _this._updatePointerPosition(evt);
  25394. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25395. // PreObservable support
  25396. if (_this.onPrePointerObservable.hasObservers()) {
  25397. if (!clickInfo.ignore) {
  25398. if (!clickInfo.hasSwiped) {
  25399. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25400. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25401. return;
  25402. }
  25403. }
  25404. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25405. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25406. return;
  25407. }
  25408. }
  25409. }
  25410. }
  25411. else {
  25412. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25413. return;
  25414. }
  25415. }
  25416. }
  25417. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25418. return;
  25419. }
  25420. _this._pointerCaptures[evt.pointerId] = false;
  25421. if (!_this.pointerUpPredicate) {
  25422. _this.pointerUpPredicate = function (mesh) {
  25423. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25424. };
  25425. }
  25426. // Meshes
  25427. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25428. _this._initActionManager(null, clickInfo);
  25429. }
  25430. if (!pickResult) {
  25431. pickResult = _this._currentPickResult;
  25432. }
  25433. _this._processPointerUp(pickResult, evt, clickInfo);
  25434. // Sprites
  25435. if (!clickInfo.ignore) {
  25436. if (_this.spriteManagers.length > 0) {
  25437. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25438. if (spritePickResult) {
  25439. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25440. if (spritePickResult.pickedSprite.actionManager) {
  25441. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25442. if (spritePickResult.pickedSprite.actionManager) {
  25443. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25444. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25445. }
  25446. }
  25447. }
  25448. }
  25449. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25450. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25451. }
  25452. }
  25453. }
  25454. }
  25455. _this._previousPickResult = _this._currentPickResult;
  25456. });
  25457. };
  25458. this._onKeyDown = function (evt) {
  25459. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25460. if (_this.onPreKeyboardObservable.hasObservers()) {
  25461. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25462. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25463. if (pi.skipOnPointerObservable) {
  25464. return;
  25465. }
  25466. }
  25467. if (_this.onKeyboardObservable.hasObservers()) {
  25468. var pi = new BABYLON.KeyboardInfo(type, evt);
  25469. _this.onKeyboardObservable.notifyObservers(pi, type);
  25470. }
  25471. if (_this.actionManager) {
  25472. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25473. }
  25474. };
  25475. this._onKeyUp = function (evt) {
  25476. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25477. if (_this.onPreKeyboardObservable.hasObservers()) {
  25478. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25479. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25480. if (pi.skipOnPointerObservable) {
  25481. return;
  25482. }
  25483. }
  25484. if (_this.onKeyboardObservable.hasObservers()) {
  25485. var pi = new BABYLON.KeyboardInfo(type, evt);
  25486. _this.onKeyboardObservable.notifyObservers(pi, type);
  25487. }
  25488. if (_this.actionManager) {
  25489. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25490. }
  25491. };
  25492. var engine = this.getEngine();
  25493. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25494. if (!canvas) {
  25495. return;
  25496. }
  25497. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25498. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25499. });
  25500. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25501. if (!canvas) {
  25502. return;
  25503. }
  25504. canvas.removeEventListener("keydown", _this._onKeyDown);
  25505. canvas.removeEventListener("keyup", _this._onKeyUp);
  25506. });
  25507. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25508. var canvas = this._engine.getRenderingCanvas();
  25509. if (!canvas) {
  25510. return;
  25511. }
  25512. if (attachMove) {
  25513. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25514. // Wheel
  25515. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25516. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25517. }
  25518. if (attachDown) {
  25519. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25520. }
  25521. if (attachUp) {
  25522. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25523. }
  25524. canvas.tabIndex = 1;
  25525. };
  25526. /** Detaches all event handlers*/
  25527. Scene.prototype.detachControl = function () {
  25528. var engine = this.getEngine();
  25529. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25530. var canvas = engine.getRenderingCanvas();
  25531. if (!canvas) {
  25532. return;
  25533. }
  25534. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25535. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25536. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25537. if (this._onCanvasBlurObserver) {
  25538. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25539. }
  25540. if (this._onCanvasFocusObserver) {
  25541. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25542. }
  25543. // Wheel
  25544. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25545. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25546. // Keyboard
  25547. canvas.removeEventListener("keydown", this._onKeyDown);
  25548. canvas.removeEventListener("keyup", this._onKeyUp);
  25549. // Observables
  25550. this.onKeyboardObservable.clear();
  25551. this.onPreKeyboardObservable.clear();
  25552. this.onPointerObservable.clear();
  25553. this.onPrePointerObservable.clear();
  25554. };
  25555. /**
  25556. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25557. * Delay loaded resources are not taking in account
  25558. * @return true if all required resources are ready
  25559. */
  25560. Scene.prototype.isReady = function () {
  25561. if (this._isDisposed) {
  25562. return false;
  25563. }
  25564. if (this._pendingData.length > 0) {
  25565. return false;
  25566. }
  25567. var index;
  25568. var engine = this.getEngine();
  25569. // Geometries
  25570. for (index = 0; index < this._geometries.length; index++) {
  25571. var geometry = this._geometries[index];
  25572. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25573. return false;
  25574. }
  25575. }
  25576. // Meshes
  25577. for (index = 0; index < this.meshes.length; index++) {
  25578. var mesh = this.meshes[index];
  25579. if (!mesh.isEnabled()) {
  25580. continue;
  25581. }
  25582. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25583. continue;
  25584. }
  25585. if (!mesh.isReady(true)) {
  25586. return false;
  25587. }
  25588. // Effect layers
  25589. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25590. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25591. var layer = _a[_i];
  25592. if (!layer.hasMesh(mesh)) {
  25593. continue;
  25594. }
  25595. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25596. var subMesh = _c[_b];
  25597. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25598. return false;
  25599. }
  25600. }
  25601. }
  25602. }
  25603. // Post-processes
  25604. if (this.activeCameras && this.activeCameras.length > 0) {
  25605. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25606. var camera = _e[_d];
  25607. if (!camera.isReady(true)) {
  25608. return false;
  25609. }
  25610. }
  25611. }
  25612. else if (this.activeCamera) {
  25613. if (!this.activeCamera.isReady(true)) {
  25614. return false;
  25615. }
  25616. }
  25617. // Particles
  25618. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25619. var particleSystem = _g[_f];
  25620. if (!particleSystem.isReady()) {
  25621. return false;
  25622. }
  25623. }
  25624. return true;
  25625. };
  25626. /** Resets all cached information relative to material (including effect and visibility) */
  25627. Scene.prototype.resetCachedMaterial = function () {
  25628. this._cachedMaterial = null;
  25629. this._cachedEffect = null;
  25630. this._cachedVisibility = null;
  25631. };
  25632. /**
  25633. * Registers a function to be called before every frame render
  25634. * @param func defines the function to register
  25635. */
  25636. Scene.prototype.registerBeforeRender = function (func) {
  25637. this.onBeforeRenderObservable.add(func);
  25638. };
  25639. /**
  25640. * Unregisters a function called before every frame render
  25641. * @param func defines the function to unregister
  25642. */
  25643. Scene.prototype.unregisterBeforeRender = function (func) {
  25644. this.onBeforeRenderObservable.removeCallback(func);
  25645. };
  25646. /**
  25647. * Registers a function to be called after every frame render
  25648. * @param func defines the function to register
  25649. */
  25650. Scene.prototype.registerAfterRender = function (func) {
  25651. this.onAfterRenderObservable.add(func);
  25652. };
  25653. /**
  25654. * Unregisters a function called after every frame render
  25655. * @param func defines the function to unregister
  25656. */
  25657. Scene.prototype.unregisterAfterRender = function (func) {
  25658. this.onAfterRenderObservable.removeCallback(func);
  25659. };
  25660. Scene.prototype._executeOnceBeforeRender = function (func) {
  25661. var _this = this;
  25662. var execFunc = function () {
  25663. func();
  25664. setTimeout(function () {
  25665. _this.unregisterBeforeRender(execFunc);
  25666. });
  25667. };
  25668. this.registerBeforeRender(execFunc);
  25669. };
  25670. /**
  25671. * The provided function will run before render once and will be disposed afterwards.
  25672. * A timeout delay can be provided so that the function will be executed in N ms.
  25673. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25674. * @param func The function to be executed.
  25675. * @param timeout optional delay in ms
  25676. */
  25677. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25678. var _this = this;
  25679. if (timeout !== undefined) {
  25680. setTimeout(function () {
  25681. _this._executeOnceBeforeRender(func);
  25682. }, timeout);
  25683. }
  25684. else {
  25685. this._executeOnceBeforeRender(func);
  25686. }
  25687. };
  25688. /** @hidden */
  25689. Scene.prototype._addPendingData = function (data) {
  25690. this._pendingData.push(data);
  25691. };
  25692. /** @hidden */
  25693. Scene.prototype._removePendingData = function (data) {
  25694. var wasLoading = this.isLoading;
  25695. var index = this._pendingData.indexOf(data);
  25696. if (index !== -1) {
  25697. this._pendingData.splice(index, 1);
  25698. }
  25699. if (wasLoading && !this.isLoading) {
  25700. this.onDataLoadedObservable.notifyObservers(this);
  25701. }
  25702. };
  25703. /**
  25704. * Returns the number of items waiting to be loaded
  25705. * @returns the number of items waiting to be loaded
  25706. */
  25707. Scene.prototype.getWaitingItemsCount = function () {
  25708. return this._pendingData.length;
  25709. };
  25710. Object.defineProperty(Scene.prototype, "isLoading", {
  25711. /**
  25712. * Returns a boolean indicating if the scene is still loading data
  25713. */
  25714. get: function () {
  25715. return this._pendingData.length > 0;
  25716. },
  25717. enumerable: true,
  25718. configurable: true
  25719. });
  25720. /**
  25721. * Registers a function to be executed when the scene is ready
  25722. * @param {Function} func - the function to be executed
  25723. */
  25724. Scene.prototype.executeWhenReady = function (func) {
  25725. var _this = this;
  25726. this.onReadyObservable.add(func);
  25727. if (this._executeWhenReadyTimeoutId !== -1) {
  25728. return;
  25729. }
  25730. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25731. _this._checkIsReady();
  25732. }, 150);
  25733. };
  25734. /**
  25735. * Returns a promise that resolves when the scene is ready
  25736. * @returns A promise that resolves when the scene is ready
  25737. */
  25738. Scene.prototype.whenReadyAsync = function () {
  25739. var _this = this;
  25740. return new Promise(function (resolve) {
  25741. _this.executeWhenReady(function () {
  25742. resolve();
  25743. });
  25744. });
  25745. };
  25746. /** @hidden */
  25747. Scene.prototype._checkIsReady = function () {
  25748. var _this = this;
  25749. if (this.isReady()) {
  25750. this.onReadyObservable.notifyObservers(this);
  25751. this.onReadyObservable.clear();
  25752. this._executeWhenReadyTimeoutId = -1;
  25753. return;
  25754. }
  25755. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25756. _this._checkIsReady();
  25757. }, 150);
  25758. };
  25759. // Animations
  25760. /**
  25761. * Will start the animation sequence of a given target
  25762. * @param target defines the target
  25763. * @param from defines from which frame should animation start
  25764. * @param to defines until which frame should animation run.
  25765. * @param weight defines the weight to apply to the animation (1.0 by default)
  25766. * @param loop defines if the animation loops
  25767. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25768. * @param onAnimationEnd defines the function to be executed when the animation ends
  25769. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25770. * @returns the animatable object created for this animation
  25771. */
  25772. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25773. if (weight === void 0) { weight = 1.0; }
  25774. if (speedRatio === void 0) { speedRatio = 1.0; }
  25775. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25776. returnedAnimatable.weight = weight;
  25777. return returnedAnimatable;
  25778. };
  25779. /**
  25780. * Will start the animation sequence of a given target
  25781. * @param target defines the target
  25782. * @param from defines from which frame should animation start
  25783. * @param to defines until which frame should animation run.
  25784. * @param loop defines if the animation loops
  25785. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25786. * @param onAnimationEnd defines the function to be executed when the animation ends
  25787. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25788. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25789. * @returns the animatable object created for this animation
  25790. */
  25791. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25792. if (speedRatio === void 0) { speedRatio = 1.0; }
  25793. if (stopCurrent === void 0) { stopCurrent = true; }
  25794. if (from > to && speedRatio > 0) {
  25795. speedRatio *= -1;
  25796. }
  25797. if (stopCurrent) {
  25798. this.stopAnimation(target);
  25799. }
  25800. if (!animatable) {
  25801. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25802. }
  25803. // Local animations
  25804. if (target.animations) {
  25805. animatable.appendAnimations(target, target.animations);
  25806. }
  25807. // Children animations
  25808. if (target.getAnimatables) {
  25809. var animatables = target.getAnimatables();
  25810. for (var index = 0; index < animatables.length; index++) {
  25811. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25812. }
  25813. }
  25814. animatable.reset();
  25815. return animatable;
  25816. };
  25817. /**
  25818. * Begin a new animation on a given node
  25819. * @param target defines the target where the animation will take place
  25820. * @param animations defines the list of animations to start
  25821. * @param from defines the initial value
  25822. * @param to defines the final value
  25823. * @param loop defines if you want animation to loop (off by default)
  25824. * @param speedRatio defines the speed ratio to apply to all animations
  25825. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25826. * @returns the list of created animatables
  25827. */
  25828. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25829. if (speedRatio === undefined) {
  25830. speedRatio = 1.0;
  25831. }
  25832. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25833. return animatable;
  25834. };
  25835. /**
  25836. * Begin a new animation on a given node and its hierarchy
  25837. * @param target defines the root node where the animation will take place
  25838. * @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.
  25839. * @param animations defines the list of animations to start
  25840. * @param from defines the initial value
  25841. * @param to defines the final value
  25842. * @param loop defines if you want animation to loop (off by default)
  25843. * @param speedRatio defines the speed ratio to apply to all animations
  25844. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25845. * @returns the list of animatables created for all nodes
  25846. */
  25847. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25848. var children = target.getDescendants(directDescendantsOnly);
  25849. var result = [];
  25850. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25851. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25852. var child = children_1[_i];
  25853. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25854. }
  25855. return result;
  25856. };
  25857. /**
  25858. * Gets the animatable associated with a specific target
  25859. * @param target defines the target of the animatable
  25860. * @returns the required animatable if found
  25861. */
  25862. Scene.prototype.getAnimatableByTarget = function (target) {
  25863. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25864. if (this._activeAnimatables[index].target === target) {
  25865. return this._activeAnimatables[index];
  25866. }
  25867. }
  25868. return null;
  25869. };
  25870. /**
  25871. * Gets all animatables associated with a given target
  25872. * @param target defines the target to look animatables for
  25873. * @returns an array of Animatables
  25874. */
  25875. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25876. var result = [];
  25877. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25878. if (this._activeAnimatables[index].target === target) {
  25879. result.push(this._activeAnimatables[index]);
  25880. }
  25881. }
  25882. return result;
  25883. };
  25884. Object.defineProperty(Scene.prototype, "animatables", {
  25885. /**
  25886. * Gets all animatable attached to the scene
  25887. */
  25888. get: function () {
  25889. return this._activeAnimatables;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. /**
  25895. * Will stop the animation of the given target
  25896. * @param target - the target
  25897. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25898. */
  25899. Scene.prototype.stopAnimation = function (target, animationName) {
  25900. var animatables = this.getAllAnimatablesByTarget(target);
  25901. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25902. var animatable = animatables_1[_i];
  25903. animatable.stop(animationName);
  25904. }
  25905. };
  25906. /**
  25907. * Stops and removes all animations that have been applied to the scene
  25908. */
  25909. Scene.prototype.stopAllAnimations = function () {
  25910. if (this._activeAnimatables) {
  25911. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25912. this._activeAnimatables[i].stop();
  25913. }
  25914. this._activeAnimatables = [];
  25915. }
  25916. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25917. var group = _a[_i];
  25918. group.stop();
  25919. }
  25920. };
  25921. Scene.prototype._animate = function () {
  25922. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25923. return;
  25924. }
  25925. // Getting time
  25926. var now = BABYLON.Tools.Now;
  25927. if (!this._animationTimeLast) {
  25928. if (this._pendingData.length > 0) {
  25929. return;
  25930. }
  25931. this._animationTimeLast = now;
  25932. }
  25933. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25934. this._animationTime += deltaTime;
  25935. this._animationTimeLast = now;
  25936. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25937. this._activeAnimatables[index]._animate(this._animationTime);
  25938. }
  25939. // Late animation bindings
  25940. this._processLateAnimationBindings();
  25941. };
  25942. /** @hidden */
  25943. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25944. var target = runtimeAnimation.target;
  25945. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25946. if (!target._lateAnimationHolders) {
  25947. target._lateAnimationHolders = {};
  25948. }
  25949. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25950. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25951. totalWeight: 0,
  25952. animations: [],
  25953. originalValue: originalValue
  25954. };
  25955. }
  25956. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25957. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25958. };
  25959. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25960. var normalizer = 1.0;
  25961. var finalPosition = BABYLON.Tmp.Vector3[0];
  25962. var finalScaling = BABYLON.Tmp.Vector3[1];
  25963. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25964. var startIndex = 0;
  25965. var originalAnimation = holder.animations[0];
  25966. var originalValue = holder.originalValue;
  25967. var scale = 1;
  25968. if (holder.totalWeight < 1.0) {
  25969. // We need to mix the original value in
  25970. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25971. scale = 1.0 - holder.totalWeight;
  25972. }
  25973. else {
  25974. startIndex = 1;
  25975. // We need to normalize the weights
  25976. normalizer = holder.totalWeight;
  25977. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25978. scale = originalAnimation.weight / normalizer;
  25979. if (scale == 1) {
  25980. return originalAnimation.currentValue;
  25981. }
  25982. }
  25983. finalScaling.scaleInPlace(scale);
  25984. finalPosition.scaleInPlace(scale);
  25985. finalQuaternion.scaleInPlace(scale);
  25986. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25987. var runtimeAnimation = holder.animations[animIndex];
  25988. var scale = runtimeAnimation.weight / normalizer;
  25989. var currentPosition = BABYLON.Tmp.Vector3[2];
  25990. var currentScaling = BABYLON.Tmp.Vector3[3];
  25991. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25992. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25993. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25994. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25995. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25996. }
  25997. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25998. return originalAnimation._workValue;
  25999. };
  26000. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26001. var originalAnimation = holder.animations[0];
  26002. var originalValue = holder.originalValue;
  26003. if (holder.animations.length === 1) {
  26004. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26005. }
  26006. var normalizer = 1.0;
  26007. var quaternions;
  26008. var weights;
  26009. if (holder.totalWeight < 1.0) {
  26010. var scale = 1.0 - holder.totalWeight;
  26011. quaternions = [];
  26012. weights = [];
  26013. quaternions.push(originalValue);
  26014. weights.push(scale);
  26015. }
  26016. else {
  26017. if (holder.animations.length === 2) { // Slerp as soon as we can
  26018. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26019. }
  26020. quaternions = [];
  26021. weights = [];
  26022. normalizer = holder.totalWeight;
  26023. }
  26024. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26025. var runtimeAnimation = holder.animations[animIndex];
  26026. quaternions.push(runtimeAnimation.currentValue);
  26027. weights.push(runtimeAnimation.weight / normalizer);
  26028. }
  26029. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26030. var cumulativeAmount = 0;
  26031. var cumulativeQuaternion = null;
  26032. for (var index = 0; index < quaternions.length;) {
  26033. if (!cumulativeQuaternion) {
  26034. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26035. cumulativeAmount = weights[index] + weights[index + 1];
  26036. index += 2;
  26037. continue;
  26038. }
  26039. cumulativeAmount += weights[index];
  26040. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26041. index++;
  26042. }
  26043. return cumulativeQuaternion;
  26044. };
  26045. Scene.prototype._processLateAnimationBindings = function () {
  26046. if (!this._registeredForLateAnimationBindings.length) {
  26047. return;
  26048. }
  26049. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26050. var target = this._registeredForLateAnimationBindings.data[index];
  26051. for (var path in target._lateAnimationHolders) {
  26052. var holder = target._lateAnimationHolders[path];
  26053. var originalAnimation = holder.animations[0];
  26054. var originalValue = holder.originalValue;
  26055. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26056. var finalValue = void 0;
  26057. if (matrixDecomposeMode) {
  26058. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26059. }
  26060. else {
  26061. var quaternionMode = originalValue.w !== undefined;
  26062. if (quaternionMode) {
  26063. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26064. }
  26065. else {
  26066. var startIndex = 0;
  26067. var normalizer = 1.0;
  26068. if (holder.totalWeight < 1.0) {
  26069. // We need to mix the original value in
  26070. if (originalValue.scale) {
  26071. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26072. }
  26073. else {
  26074. finalValue = originalValue * (1.0 - holder.totalWeight);
  26075. }
  26076. }
  26077. else {
  26078. // We need to normalize the weights
  26079. normalizer = holder.totalWeight;
  26080. var scale_1 = originalAnimation.weight / normalizer;
  26081. if (scale_1 !== 1) {
  26082. if (originalAnimation.currentValue.scale) {
  26083. finalValue = originalAnimation.currentValue.scale(scale_1);
  26084. }
  26085. else {
  26086. finalValue = originalAnimation.currentValue * scale_1;
  26087. }
  26088. }
  26089. else {
  26090. finalValue = originalAnimation.currentValue;
  26091. }
  26092. startIndex = 1;
  26093. }
  26094. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26095. var runtimeAnimation = holder.animations[animIndex];
  26096. var scale = runtimeAnimation.weight / normalizer;
  26097. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26098. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26099. }
  26100. else {
  26101. finalValue += runtimeAnimation.currentValue * scale;
  26102. }
  26103. }
  26104. }
  26105. }
  26106. target[path] = finalValue;
  26107. }
  26108. target._lateAnimationHolders = {};
  26109. }
  26110. this._registeredForLateAnimationBindings.reset();
  26111. };
  26112. // Matrix
  26113. /** @hidden */
  26114. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26115. this._useAlternateCameraConfiguration = active;
  26116. };
  26117. /**
  26118. * Gets the current view matrix
  26119. * @returns a Matrix
  26120. */
  26121. Scene.prototype.getViewMatrix = function () {
  26122. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26123. };
  26124. /**
  26125. * Gets the current projection matrix
  26126. * @returns a Matrix
  26127. */
  26128. Scene.prototype.getProjectionMatrix = function () {
  26129. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26130. };
  26131. /**
  26132. * Gets the current transform matrix
  26133. * @returns a Matrix made of View * Projection
  26134. */
  26135. Scene.prototype.getTransformMatrix = function () {
  26136. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26137. };
  26138. /**
  26139. * Sets the current transform matrix
  26140. * @param view defines the View matrix to use
  26141. * @param projection defines the Projection matrix to use
  26142. */
  26143. Scene.prototype.setTransformMatrix = function (view, projection) {
  26144. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26145. return;
  26146. }
  26147. this._viewUpdateFlag = view.updateFlag;
  26148. this._projectionUpdateFlag = projection.updateFlag;
  26149. this._viewMatrix = view;
  26150. this._projectionMatrix = projection;
  26151. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26152. // Update frustum
  26153. if (!this._frustumPlanes) {
  26154. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26155. }
  26156. else {
  26157. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26158. }
  26159. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26160. var otherCamera = this.activeCamera._alternateCamera;
  26161. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26162. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26163. }
  26164. if (this._sceneUbo.useUbo) {
  26165. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26166. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26167. this._sceneUbo.update();
  26168. }
  26169. };
  26170. /** @hidden */
  26171. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26172. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26173. return;
  26174. }
  26175. this._alternateViewUpdateFlag = view.updateFlag;
  26176. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26177. this._alternateViewMatrix = view;
  26178. this._alternateProjectionMatrix = projection;
  26179. if (!this._alternateTransformMatrix) {
  26180. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26181. }
  26182. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26183. if (!this._alternateSceneUbo) {
  26184. this._createAlternateUbo();
  26185. }
  26186. if (this._alternateSceneUbo.useUbo) {
  26187. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26188. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26189. this._alternateSceneUbo.update();
  26190. }
  26191. };
  26192. /**
  26193. * Gets the uniform buffer used to store scene data
  26194. * @returns a UniformBuffer
  26195. */
  26196. Scene.prototype.getSceneUniformBuffer = function () {
  26197. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26198. };
  26199. /**
  26200. * Gets an unique (relatively to the current scene) Id
  26201. * @returns an unique number for the scene
  26202. */
  26203. Scene.prototype.getUniqueId = function () {
  26204. var result = Scene._uniqueIdCounter;
  26205. Scene._uniqueIdCounter++;
  26206. return result;
  26207. };
  26208. /**
  26209. * Add a mesh to the list of scene's meshes
  26210. * @param newMesh defines the mesh to add
  26211. * @param recursive if all child meshes should also be added to the scene
  26212. */
  26213. Scene.prototype.addMesh = function (newMesh, recursive) {
  26214. var _this = this;
  26215. if (recursive === void 0) { recursive = false; }
  26216. this.meshes.push(newMesh);
  26217. //notify the collision coordinator
  26218. if (this.collisionCoordinator) {
  26219. this.collisionCoordinator.onMeshAdded(newMesh);
  26220. }
  26221. newMesh._resyncLightSources();
  26222. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26223. if (recursive) {
  26224. newMesh.getChildMeshes().forEach(function (m) {
  26225. _this.addMesh(m);
  26226. });
  26227. }
  26228. };
  26229. /**
  26230. * Remove a mesh for the list of scene's meshes
  26231. * @param toRemove defines the mesh to remove
  26232. * @param recursive if all child meshes should also be removed from the scene
  26233. * @returns the index where the mesh was in the mesh list
  26234. */
  26235. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26236. var _this = this;
  26237. if (recursive === void 0) { recursive = false; }
  26238. var index = this.meshes.indexOf(toRemove);
  26239. if (index !== -1) {
  26240. // Remove from the scene if mesh found
  26241. this.meshes.splice(index, 1);
  26242. }
  26243. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26244. if (recursive) {
  26245. toRemove.getChildMeshes().forEach(function (m) {
  26246. _this.removeMesh(m);
  26247. });
  26248. }
  26249. return index;
  26250. };
  26251. /**
  26252. * Add a transform node to the list of scene's transform nodes
  26253. * @param newTransformNode defines the transform node to add
  26254. */
  26255. Scene.prototype.addTransformNode = function (newTransformNode) {
  26256. this.transformNodes.push(newTransformNode);
  26257. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26258. };
  26259. /**
  26260. * Remove a transform node for the list of scene's transform nodes
  26261. * @param toRemove defines the transform node to remove
  26262. * @returns the index where the transform node was in the transform node list
  26263. */
  26264. Scene.prototype.removeTransformNode = function (toRemove) {
  26265. var index = this.transformNodes.indexOf(toRemove);
  26266. if (index !== -1) {
  26267. // Remove from the scene if found
  26268. this.transformNodes.splice(index, 1);
  26269. }
  26270. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26271. return index;
  26272. };
  26273. /**
  26274. * Remove a skeleton for the list of scene's skeletons
  26275. * @param toRemove defines the skeleton to remove
  26276. * @returns the index where the skeleton was in the skeleton list
  26277. */
  26278. Scene.prototype.removeSkeleton = function (toRemove) {
  26279. var index = this.skeletons.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. // Remove from the scene if found
  26282. this.skeletons.splice(index, 1);
  26283. }
  26284. return index;
  26285. };
  26286. /**
  26287. * Remove a morph target for the list of scene's morph targets
  26288. * @param toRemove defines the morph target to remove
  26289. * @returns the index where the morph target was in the morph target list
  26290. */
  26291. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26292. var index = this.morphTargetManagers.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. // Remove from the scene if found
  26295. this.morphTargetManagers.splice(index, 1);
  26296. }
  26297. return index;
  26298. };
  26299. /**
  26300. * Remove a light for the list of scene's lights
  26301. * @param toRemove defines the light to remove
  26302. * @returns the index where the light was in the light list
  26303. */
  26304. Scene.prototype.removeLight = function (toRemove) {
  26305. var index = this.lights.indexOf(toRemove);
  26306. if (index !== -1) {
  26307. // Remove from meshes
  26308. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26309. var mesh = _a[_i];
  26310. mesh._removeLightSource(toRemove);
  26311. }
  26312. // Remove from the scene if mesh found
  26313. this.lights.splice(index, 1);
  26314. this.sortLightsByPriority();
  26315. }
  26316. this.onLightRemovedObservable.notifyObservers(toRemove);
  26317. return index;
  26318. };
  26319. /**
  26320. * Remove a camera for the list of scene's cameras
  26321. * @param toRemove defines the camera to remove
  26322. * @returns the index where the camera was in the camera list
  26323. */
  26324. Scene.prototype.removeCamera = function (toRemove) {
  26325. var index = this.cameras.indexOf(toRemove);
  26326. if (index !== -1) {
  26327. // Remove from the scene if mesh found
  26328. this.cameras.splice(index, 1);
  26329. }
  26330. // Remove from activeCameras
  26331. var index2 = this.activeCameras.indexOf(toRemove);
  26332. if (index2 !== -1) {
  26333. // Remove from the scene if mesh found
  26334. this.activeCameras.splice(index2, 1);
  26335. }
  26336. // Reset the activeCamera
  26337. if (this.activeCamera === toRemove) {
  26338. if (this.cameras.length > 0) {
  26339. this.activeCamera = this.cameras[0];
  26340. }
  26341. else {
  26342. this.activeCamera = null;
  26343. }
  26344. }
  26345. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26346. return index;
  26347. };
  26348. /**
  26349. * Remove a particle system for the list of scene's particle systems
  26350. * @param toRemove defines the particle system to remove
  26351. * @returns the index where the particle system was in the particle system list
  26352. */
  26353. Scene.prototype.removeParticleSystem = function (toRemove) {
  26354. var index = this.particleSystems.indexOf(toRemove);
  26355. if (index !== -1) {
  26356. this.particleSystems.splice(index, 1);
  26357. }
  26358. return index;
  26359. };
  26360. /**
  26361. * Remove a animation for the list of scene's animations
  26362. * @param toRemove defines the animation to remove
  26363. * @returns the index where the animation was in the animation list
  26364. */
  26365. Scene.prototype.removeAnimation = function (toRemove) {
  26366. var index = this.animations.indexOf(toRemove);
  26367. if (index !== -1) {
  26368. this.animations.splice(index, 1);
  26369. }
  26370. return index;
  26371. };
  26372. /**
  26373. * Removes the given animation group from this scene.
  26374. * @param toRemove The animation group to remove
  26375. * @returns The index of the removed animation group
  26376. */
  26377. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26378. var index = this.animationGroups.indexOf(toRemove);
  26379. if (index !== -1) {
  26380. this.animationGroups.splice(index, 1);
  26381. }
  26382. return index;
  26383. };
  26384. /**
  26385. * Removes the given multi-material from this scene.
  26386. * @param toRemove The multi-material to remove
  26387. * @returns The index of the removed multi-material
  26388. */
  26389. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26390. var index = this.multiMaterials.indexOf(toRemove);
  26391. if (index !== -1) {
  26392. this.multiMaterials.splice(index, 1);
  26393. }
  26394. return index;
  26395. };
  26396. /**
  26397. * Removes the given material from this scene.
  26398. * @param toRemove The material to remove
  26399. * @returns The index of the removed material
  26400. */
  26401. Scene.prototype.removeMaterial = function (toRemove) {
  26402. var index = this.materials.indexOf(toRemove);
  26403. if (index !== -1) {
  26404. this.materials.splice(index, 1);
  26405. }
  26406. return index;
  26407. };
  26408. /**
  26409. * Removes the given lens flare system from this scene.
  26410. * @param toRemove The lens flare system to remove
  26411. * @returns The index of the removed lens flare system
  26412. */
  26413. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26414. var index = this.lensFlareSystems.indexOf(toRemove);
  26415. if (index !== -1) {
  26416. this.lensFlareSystems.splice(index, 1);
  26417. }
  26418. return index;
  26419. };
  26420. /**
  26421. * Removes the given action manager from this scene.
  26422. * @param toRemove The action manager to remove
  26423. * @returns The index of the removed action manager
  26424. */
  26425. Scene.prototype.removeActionManager = function (toRemove) {
  26426. var index = this._actionManagers.indexOf(toRemove);
  26427. if (index !== -1) {
  26428. this._actionManagers.splice(index, 1);
  26429. }
  26430. return index;
  26431. };
  26432. /**
  26433. * Removes the given effect layer from this scene.
  26434. * @param toRemove defines the effect layer to remove
  26435. * @returns the index of the removed effect layer
  26436. */
  26437. Scene.prototype.removeEffectLayer = function (toRemove) {
  26438. var index = this.effectLayers.indexOf(toRemove);
  26439. if (index !== -1) {
  26440. this.effectLayers.splice(index, 1);
  26441. }
  26442. return index;
  26443. };
  26444. /**
  26445. * Removes the given texture from this scene.
  26446. * @param toRemove The texture to remove
  26447. * @returns The index of the removed texture
  26448. */
  26449. Scene.prototype.removeTexture = function (toRemove) {
  26450. var index = this.textures.indexOf(toRemove);
  26451. if (index !== -1) {
  26452. this.textures.splice(index, 1);
  26453. }
  26454. return index;
  26455. };
  26456. /**
  26457. * Adds the given light to this scene
  26458. * @param newLight The light to add
  26459. */
  26460. Scene.prototype.addLight = function (newLight) {
  26461. this.lights.push(newLight);
  26462. this.sortLightsByPriority();
  26463. // Add light to all meshes (To support if the light is removed and then readded)
  26464. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26465. var mesh = _a[_i];
  26466. if (mesh._lightSources.indexOf(newLight) === -1) {
  26467. mesh._lightSources.push(newLight);
  26468. mesh._resyncLightSources();
  26469. }
  26470. }
  26471. this.onNewLightAddedObservable.notifyObservers(newLight);
  26472. };
  26473. /**
  26474. * Sorts the list list based on light priorities
  26475. */
  26476. Scene.prototype.sortLightsByPriority = function () {
  26477. if (this.requireLightSorting) {
  26478. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26479. }
  26480. };
  26481. /**
  26482. * Adds the given camera to this scene
  26483. * @param newCamera The camera to add
  26484. */
  26485. Scene.prototype.addCamera = function (newCamera) {
  26486. this.cameras.push(newCamera);
  26487. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26488. };
  26489. /**
  26490. * Adds the given skeleton to this scene
  26491. * @param newSkeleton The skeleton to add
  26492. */
  26493. Scene.prototype.addSkeleton = function (newSkeleton) {
  26494. this.skeletons.push(newSkeleton);
  26495. };
  26496. /**
  26497. * Adds the given particle system to this scene
  26498. * @param newParticleSystem The particle system to add
  26499. */
  26500. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26501. this.particleSystems.push(newParticleSystem);
  26502. };
  26503. /**
  26504. * Adds the given animation to this scene
  26505. * @param newAnimation The animation to add
  26506. */
  26507. Scene.prototype.addAnimation = function (newAnimation) {
  26508. this.animations.push(newAnimation);
  26509. };
  26510. /**
  26511. * Adds the given animation group to this scene.
  26512. * @param newAnimationGroup The animation group to add
  26513. */
  26514. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26515. this.animationGroups.push(newAnimationGroup);
  26516. };
  26517. /**
  26518. * Adds the given multi-material to this scene
  26519. * @param newMultiMaterial The multi-material to add
  26520. */
  26521. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26522. this.multiMaterials.push(newMultiMaterial);
  26523. };
  26524. /**
  26525. * Adds the given material to this scene
  26526. * @param newMaterial The material to add
  26527. */
  26528. Scene.prototype.addMaterial = function (newMaterial) {
  26529. this.materials.push(newMaterial);
  26530. };
  26531. /**
  26532. * Adds the given morph target to this scene
  26533. * @param newMorphTargetManager The morph target to add
  26534. */
  26535. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26536. this.morphTargetManagers.push(newMorphTargetManager);
  26537. };
  26538. /**
  26539. * Adds the given geometry to this scene
  26540. * @param newGeometry The geometry to add
  26541. */
  26542. Scene.prototype.addGeometry = function (newGeometry) {
  26543. this._geometries.push(newGeometry);
  26544. };
  26545. /**
  26546. * Adds the given lens flare system to this scene
  26547. * @param newLensFlareSystem The lens flare system to add
  26548. */
  26549. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26550. this.lensFlareSystems.push(newLensFlareSystem);
  26551. };
  26552. /**
  26553. * Adds the given effect layer to this scene
  26554. * @param newEffectLayer defines the effect layer to add
  26555. */
  26556. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26557. this.effectLayers.push(newEffectLayer);
  26558. };
  26559. /**
  26560. * Adds the given action manager to this scene
  26561. * @param newActionManager The action manager to add
  26562. */
  26563. Scene.prototype.addActionManager = function (newActionManager) {
  26564. this._actionManagers.push(newActionManager);
  26565. };
  26566. /**
  26567. * Adds the given texture to this scene.
  26568. * @param newTexture The texture to add
  26569. */
  26570. Scene.prototype.addTexture = function (newTexture) {
  26571. this.textures.push(newTexture);
  26572. };
  26573. /**
  26574. * Switch active camera
  26575. * @param newCamera defines the new active camera
  26576. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26577. */
  26578. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26579. if (attachControl === void 0) { attachControl = true; }
  26580. var canvas = this._engine.getRenderingCanvas();
  26581. if (!canvas) {
  26582. return;
  26583. }
  26584. if (this.activeCamera) {
  26585. this.activeCamera.detachControl(canvas);
  26586. }
  26587. this.activeCamera = newCamera;
  26588. if (attachControl) {
  26589. newCamera.attachControl(canvas);
  26590. }
  26591. };
  26592. /**
  26593. * sets the active camera of the scene using its ID
  26594. * @param id defines the camera's ID
  26595. * @return the new active camera or null if none found.
  26596. */
  26597. Scene.prototype.setActiveCameraByID = function (id) {
  26598. var camera = this.getCameraByID(id);
  26599. if (camera) {
  26600. this.activeCamera = camera;
  26601. return camera;
  26602. }
  26603. return null;
  26604. };
  26605. /**
  26606. * sets the active camera of the scene using its name
  26607. * @param name defines the camera's name
  26608. * @returns the new active camera or null if none found.
  26609. */
  26610. Scene.prototype.setActiveCameraByName = function (name) {
  26611. var camera = this.getCameraByName(name);
  26612. if (camera) {
  26613. this.activeCamera = camera;
  26614. return camera;
  26615. }
  26616. return null;
  26617. };
  26618. /**
  26619. * get an animation group using its name
  26620. * @param name defines the material's name
  26621. * @return the animation group or null if none found.
  26622. */
  26623. Scene.prototype.getAnimationGroupByName = function (name) {
  26624. for (var index = 0; index < this.animationGroups.length; index++) {
  26625. if (this.animationGroups[index].name === name) {
  26626. return this.animationGroups[index];
  26627. }
  26628. }
  26629. return null;
  26630. };
  26631. /**
  26632. * get a material using its id
  26633. * @param id defines the material's ID
  26634. * @return the material or null if none found.
  26635. */
  26636. Scene.prototype.getMaterialByID = function (id) {
  26637. for (var index = 0; index < this.materials.length; index++) {
  26638. if (this.materials[index].id === id) {
  26639. return this.materials[index];
  26640. }
  26641. }
  26642. return null;
  26643. };
  26644. /**
  26645. * Gets a material using its name
  26646. * @param name defines the material's name
  26647. * @return the material or null if none found.
  26648. */
  26649. Scene.prototype.getMaterialByName = function (name) {
  26650. for (var index = 0; index < this.materials.length; index++) {
  26651. if (this.materials[index].name === name) {
  26652. return this.materials[index];
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. /**
  26658. * Gets a lens flare system using its name
  26659. * @param name defines the name to look for
  26660. * @returns the lens flare system or null if not found
  26661. */
  26662. Scene.prototype.getLensFlareSystemByName = function (name) {
  26663. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26664. if (this.lensFlareSystems[index].name === name) {
  26665. return this.lensFlareSystems[index];
  26666. }
  26667. }
  26668. return null;
  26669. };
  26670. /**
  26671. * Gets a lens flare system using its id
  26672. * @param id defines the id to look for
  26673. * @returns the lens flare system or null if not found
  26674. */
  26675. Scene.prototype.getLensFlareSystemByID = function (id) {
  26676. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26677. if (this.lensFlareSystems[index].id === id) {
  26678. return this.lensFlareSystems[index];
  26679. }
  26680. }
  26681. return null;
  26682. };
  26683. /**
  26684. * Gets a camera using its id
  26685. * @param id defines the id to look for
  26686. * @returns the camera or null if not found
  26687. */
  26688. Scene.prototype.getCameraByID = function (id) {
  26689. for (var index = 0; index < this.cameras.length; index++) {
  26690. if (this.cameras[index].id === id) {
  26691. return this.cameras[index];
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a camera using its unique id
  26698. * @param uniqueId defines the unique id to look for
  26699. * @returns the camera or null if not found
  26700. */
  26701. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26702. for (var index = 0; index < this.cameras.length; index++) {
  26703. if (this.cameras[index].uniqueId === uniqueId) {
  26704. return this.cameras[index];
  26705. }
  26706. }
  26707. return null;
  26708. };
  26709. /**
  26710. * Gets a camera using its name
  26711. * @param name defines the camera's name
  26712. * @return the camera or null if none found.
  26713. */
  26714. Scene.prototype.getCameraByName = function (name) {
  26715. for (var index = 0; index < this.cameras.length; index++) {
  26716. if (this.cameras[index].name === name) {
  26717. return this.cameras[index];
  26718. }
  26719. }
  26720. return null;
  26721. };
  26722. /**
  26723. * Gets a bone using its id
  26724. * @param id defines the bone's id
  26725. * @return the bone or null if not found
  26726. */
  26727. Scene.prototype.getBoneByID = function (id) {
  26728. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26729. var skeleton = this.skeletons[skeletonIndex];
  26730. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26731. if (skeleton.bones[boneIndex].id === id) {
  26732. return skeleton.bones[boneIndex];
  26733. }
  26734. }
  26735. }
  26736. return null;
  26737. };
  26738. /**
  26739. * Gets a bone using its id
  26740. * @param name defines the bone's name
  26741. * @return the bone or null if not found
  26742. */
  26743. Scene.prototype.getBoneByName = function (name) {
  26744. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26745. var skeleton = this.skeletons[skeletonIndex];
  26746. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26747. if (skeleton.bones[boneIndex].name === name) {
  26748. return skeleton.bones[boneIndex];
  26749. }
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a light node using its name
  26756. * @param name defines the the light's name
  26757. * @return the light or null if none found.
  26758. */
  26759. Scene.prototype.getLightByName = function (name) {
  26760. for (var index = 0; index < this.lights.length; index++) {
  26761. if (this.lights[index].name === name) {
  26762. return this.lights[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a light node using its id
  26769. * @param id defines the light's id
  26770. * @return the light or null if none found.
  26771. */
  26772. Scene.prototype.getLightByID = function (id) {
  26773. for (var index = 0; index < this.lights.length; index++) {
  26774. if (this.lights[index].id === id) {
  26775. return this.lights[index];
  26776. }
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * Gets a light node using its scene-generated unique ID
  26782. * @param uniqueId defines the light's unique id
  26783. * @return the light or null if none found.
  26784. */
  26785. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26786. for (var index = 0; index < this.lights.length; index++) {
  26787. if (this.lights[index].uniqueId === uniqueId) {
  26788. return this.lights[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * Gets a particle system by id
  26795. * @param id defines the particle system id
  26796. * @return the corresponding system or null if none found
  26797. */
  26798. Scene.prototype.getParticleSystemByID = function (id) {
  26799. for (var index = 0; index < this.particleSystems.length; index++) {
  26800. if (this.particleSystems[index].id === id) {
  26801. return this.particleSystems[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * Gets a geometry using its ID
  26808. * @param id defines the geometry's id
  26809. * @return the geometry or null if none found.
  26810. */
  26811. Scene.prototype.getGeometryByID = function (id) {
  26812. for (var index = 0; index < this._geometries.length; index++) {
  26813. if (this._geometries[index].id === id) {
  26814. return this._geometries[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * Add a new geometry to this scene
  26821. * @param geometry defines the geometry to be added to the scene.
  26822. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26823. * @return a boolean defining if the geometry was added or not
  26824. */
  26825. Scene.prototype.pushGeometry = function (geometry, force) {
  26826. if (!force && this.getGeometryByID(geometry.id)) {
  26827. return false;
  26828. }
  26829. this._geometries.push(geometry);
  26830. //notify the collision coordinator
  26831. if (this.collisionCoordinator) {
  26832. this.collisionCoordinator.onGeometryAdded(geometry);
  26833. }
  26834. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26835. return true;
  26836. };
  26837. /**
  26838. * Removes an existing geometry
  26839. * @param geometry defines the geometry to be removed from the scene
  26840. * @return a boolean defining if the geometry was removed or not
  26841. */
  26842. Scene.prototype.removeGeometry = function (geometry) {
  26843. var index = this._geometries.indexOf(geometry);
  26844. if (index > -1) {
  26845. this._geometries.splice(index, 1);
  26846. //notify the collision coordinator
  26847. if (this.collisionCoordinator) {
  26848. this.collisionCoordinator.onGeometryDeleted(geometry);
  26849. }
  26850. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26851. return true;
  26852. }
  26853. return false;
  26854. };
  26855. /**
  26856. * Gets the list of geometries attached to the scene
  26857. * @returns an array of Geometry
  26858. */
  26859. Scene.prototype.getGeometries = function () {
  26860. return this._geometries;
  26861. };
  26862. /**
  26863. * Gets the first added mesh found of a given ID
  26864. * @param id defines the id to search for
  26865. * @return the mesh found or null if not found at all
  26866. */
  26867. Scene.prototype.getMeshByID = function (id) {
  26868. for (var index = 0; index < this.meshes.length; index++) {
  26869. if (this.meshes[index].id === id) {
  26870. return this.meshes[index];
  26871. }
  26872. }
  26873. return null;
  26874. };
  26875. /**
  26876. * Gets a list of meshes using their id
  26877. * @param id defines the id to search for
  26878. * @returns a list of meshes
  26879. */
  26880. Scene.prototype.getMeshesByID = function (id) {
  26881. return this.meshes.filter(function (m) {
  26882. return m.id === id;
  26883. });
  26884. };
  26885. /**
  26886. * Gets the first added transform node found of a given ID
  26887. * @param id defines the id to search for
  26888. * @return the found transform node or null if not found at all.
  26889. */
  26890. Scene.prototype.getTransformNodeByID = function (id) {
  26891. for (var index = 0; index < this.transformNodes.length; index++) {
  26892. if (this.transformNodes[index].id === id) {
  26893. return this.transformNodes[index];
  26894. }
  26895. }
  26896. return null;
  26897. };
  26898. /**
  26899. * Gets a list of transform nodes using their id
  26900. * @param id defines the id to search for
  26901. * @returns a list of transform nodes
  26902. */
  26903. Scene.prototype.getTransformNodesByID = function (id) {
  26904. return this.transformNodes.filter(function (m) {
  26905. return m.id === id;
  26906. });
  26907. };
  26908. /**
  26909. * Gets a mesh with its auto-generated unique id
  26910. * @param uniqueId defines the unique id to search for
  26911. * @return the found mesh or null if not found at all.
  26912. */
  26913. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26914. for (var index = 0; index < this.meshes.length; index++) {
  26915. if (this.meshes[index].uniqueId === uniqueId) {
  26916. return this.meshes[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a the last added mesh using a given id
  26923. * @param id defines the id to search for
  26924. * @return the found mesh or null if not found at all.
  26925. */
  26926. Scene.prototype.getLastMeshByID = function (id) {
  26927. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26928. if (this.meshes[index].id === id) {
  26929. return this.meshes[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26936. * @param id defines the id to search for
  26937. * @return the found node or null if not found at all
  26938. */
  26939. Scene.prototype.getLastEntryByID = function (id) {
  26940. var index;
  26941. for (index = this.meshes.length - 1; index >= 0; index--) {
  26942. if (this.meshes[index].id === id) {
  26943. return this.meshes[index];
  26944. }
  26945. }
  26946. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26947. if (this.transformNodes[index].id === id) {
  26948. return this.transformNodes[index];
  26949. }
  26950. }
  26951. for (index = this.cameras.length - 1; index >= 0; index--) {
  26952. if (this.cameras[index].id === id) {
  26953. return this.cameras[index];
  26954. }
  26955. }
  26956. for (index = this.lights.length - 1; index >= 0; index--) {
  26957. if (this.lights[index].id === id) {
  26958. return this.lights[index];
  26959. }
  26960. }
  26961. return null;
  26962. };
  26963. /**
  26964. * Gets a node (Mesh, Camera, Light) using a given id
  26965. * @param id defines the id to search for
  26966. * @return the found node or null if not found at all
  26967. */
  26968. Scene.prototype.getNodeByID = function (id) {
  26969. var mesh = this.getMeshByID(id);
  26970. if (mesh) {
  26971. return mesh;
  26972. }
  26973. var light = this.getLightByID(id);
  26974. if (light) {
  26975. return light;
  26976. }
  26977. var camera = this.getCameraByID(id);
  26978. if (camera) {
  26979. return camera;
  26980. }
  26981. var bone = this.getBoneByID(id);
  26982. return bone;
  26983. };
  26984. /**
  26985. * Gets a node (Mesh, Camera, Light) using a given name
  26986. * @param name defines the name to search for
  26987. * @return the found node or null if not found at all.
  26988. */
  26989. Scene.prototype.getNodeByName = function (name) {
  26990. var mesh = this.getMeshByName(name);
  26991. if (mesh) {
  26992. return mesh;
  26993. }
  26994. var light = this.getLightByName(name);
  26995. if (light) {
  26996. return light;
  26997. }
  26998. var camera = this.getCameraByName(name);
  26999. if (camera) {
  27000. return camera;
  27001. }
  27002. var bone = this.getBoneByName(name);
  27003. return bone;
  27004. };
  27005. /**
  27006. * Gets a mesh using a given name
  27007. * @param name defines the name to search for
  27008. * @return the found mesh or null if not found at all.
  27009. */
  27010. Scene.prototype.getMeshByName = function (name) {
  27011. for (var index = 0; index < this.meshes.length; index++) {
  27012. if (this.meshes[index].name === name) {
  27013. return this.meshes[index];
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a transform node using a given name
  27020. * @param name defines the name to search for
  27021. * @return the found transform node or null if not found at all.
  27022. */
  27023. Scene.prototype.getTransformNodeByName = function (name) {
  27024. for (var index = 0; index < this.transformNodes.length; index++) {
  27025. if (this.transformNodes[index].name === name) {
  27026. return this.transformNodes[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Gets a sound using a given name
  27033. * @param name defines the name to search for
  27034. * @return the found sound or null if not found at all.
  27035. */
  27036. Scene.prototype.getSoundByName = function (name) {
  27037. var index;
  27038. if (BABYLON.AudioEngine) {
  27039. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27040. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27041. return this.mainSoundTrack.soundCollection[index];
  27042. }
  27043. }
  27044. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27045. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27046. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27047. return this.soundTracks[sdIndex].soundCollection[index];
  27048. }
  27049. }
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27056. * @param id defines the id to search for
  27057. * @return the found skeleton or null if not found at all.
  27058. */
  27059. Scene.prototype.getLastSkeletonByID = function (id) {
  27060. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27061. if (this.skeletons[index].id === id) {
  27062. return this.skeletons[index];
  27063. }
  27064. }
  27065. return null;
  27066. };
  27067. /**
  27068. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27069. * @param id defines the id to search for
  27070. * @return the found skeleton or null if not found at all.
  27071. */
  27072. Scene.prototype.getSkeletonById = function (id) {
  27073. for (var index = 0; index < this.skeletons.length; index++) {
  27074. if (this.skeletons[index].id === id) {
  27075. return this.skeletons[index];
  27076. }
  27077. }
  27078. return null;
  27079. };
  27080. /**
  27081. * Gets a skeleton using a given name
  27082. * @param name defines the name to search for
  27083. * @return the found skeleton or null if not found at all.
  27084. */
  27085. Scene.prototype.getSkeletonByName = function (name) {
  27086. for (var index = 0; index < this.skeletons.length; index++) {
  27087. if (this.skeletons[index].name === name) {
  27088. return this.skeletons[index];
  27089. }
  27090. }
  27091. return null;
  27092. };
  27093. /**
  27094. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27095. * @param id defines the id to search for
  27096. * @return the found morph target manager or null if not found at all.
  27097. */
  27098. Scene.prototype.getMorphTargetManagerById = function (id) {
  27099. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27100. if (this.morphTargetManagers[index].uniqueId === id) {
  27101. return this.morphTargetManagers[index];
  27102. }
  27103. }
  27104. return null;
  27105. };
  27106. /**
  27107. * Gets a boolean indicating if the given mesh is active
  27108. * @param mesh defines the mesh to look for
  27109. * @returns true if the mesh is in the active list
  27110. */
  27111. Scene.prototype.isActiveMesh = function (mesh) {
  27112. return (this._activeMeshes.indexOf(mesh) !== -1);
  27113. };
  27114. /**
  27115. * Return a the first highlight layer of the scene with a given name.
  27116. * @param name The name of the highlight layer to look for.
  27117. * @return The highlight layer if found otherwise null.
  27118. */
  27119. Scene.prototype.getHighlightLayerByName = function (name) {
  27120. for (var index = 0; index < this.effectLayers.length; index++) {
  27121. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27122. return this.effectLayers[index];
  27123. }
  27124. }
  27125. return null;
  27126. };
  27127. /**
  27128. * Return a the first highlight layer of the scene with a given name.
  27129. * @param name The name of the highlight layer to look for.
  27130. * @return The highlight layer if found otherwise null.
  27131. */
  27132. Scene.prototype.getGlowLayerByName = function (name) {
  27133. for (var index = 0; index < this.effectLayers.length; index++) {
  27134. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27135. return this.effectLayers[index];
  27136. }
  27137. }
  27138. return null;
  27139. };
  27140. Object.defineProperty(Scene.prototype, "uid", {
  27141. /**
  27142. * Return a unique id as a string which can serve as an identifier for the scene
  27143. */
  27144. get: function () {
  27145. if (!this._uid) {
  27146. this._uid = BABYLON.Tools.RandomId();
  27147. }
  27148. return this._uid;
  27149. },
  27150. enumerable: true,
  27151. configurable: true
  27152. });
  27153. /**
  27154. * Add an externaly attached data from its key.
  27155. * This method call will fail and return false, if such key already exists.
  27156. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27157. * @param key the unique key that identifies the data
  27158. * @param data the data object to associate to the key for this Engine instance
  27159. * @return true if no such key were already present and the data was added successfully, false otherwise
  27160. */
  27161. Scene.prototype.addExternalData = function (key, data) {
  27162. if (!this._externalData) {
  27163. this._externalData = new BABYLON.StringDictionary();
  27164. }
  27165. return this._externalData.add(key, data);
  27166. };
  27167. /**
  27168. * Get an externaly attached data from its key
  27169. * @param key the unique key that identifies the data
  27170. * @return the associated data, if present (can be null), or undefined if not present
  27171. */
  27172. Scene.prototype.getExternalData = function (key) {
  27173. if (!this._externalData) {
  27174. return null;
  27175. }
  27176. return this._externalData.get(key);
  27177. };
  27178. /**
  27179. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27180. * @param key the unique key that identifies the data
  27181. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27182. * @return the associated data, can be null if the factory returned null.
  27183. */
  27184. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27185. if (!this._externalData) {
  27186. this._externalData = new BABYLON.StringDictionary();
  27187. }
  27188. return this._externalData.getOrAddWithFactory(key, factory);
  27189. };
  27190. /**
  27191. * Remove an externaly attached data from the Engine instance
  27192. * @param key the unique key that identifies the data
  27193. * @return true if the data was successfully removed, false if it doesn't exist
  27194. */
  27195. Scene.prototype.removeExternalData = function (key) {
  27196. return this._externalData.remove(key);
  27197. };
  27198. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27199. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27200. if (mesh.showSubMeshesBoundingBox) {
  27201. var boundingInfo = subMesh.getBoundingInfo();
  27202. if (boundingInfo !== null && boundingInfo !== undefined) {
  27203. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27204. }
  27205. }
  27206. var material = subMesh.getMaterial();
  27207. if (material !== null && material !== undefined) {
  27208. // Render targets
  27209. if (material.getRenderTargetTextures !== undefined) {
  27210. if (this._processedMaterials.indexOf(material) === -1) {
  27211. this._processedMaterials.push(material);
  27212. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27213. }
  27214. }
  27215. // Dispatch
  27216. this._activeIndices.addCount(subMesh.indexCount, false);
  27217. this._renderingManager.dispatch(subMesh, mesh, material);
  27218. }
  27219. }
  27220. };
  27221. /**
  27222. * Clear the processed materials smart array preventing retention point in material dispose.
  27223. */
  27224. Scene.prototype.freeProcessedMaterials = function () {
  27225. this._processedMaterials.dispose();
  27226. };
  27227. /**
  27228. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27229. */
  27230. Scene.prototype.freeActiveMeshes = function () {
  27231. this._activeMeshes.dispose();
  27232. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27233. this.activeCamera._activeMeshes.dispose();
  27234. }
  27235. if (this.activeCameras) {
  27236. for (var i = 0; i < this.activeCameras.length; i++) {
  27237. var activeCamera = this.activeCameras[i];
  27238. if (activeCamera && activeCamera._activeMeshes) {
  27239. activeCamera._activeMeshes.dispose();
  27240. }
  27241. }
  27242. }
  27243. };
  27244. /**
  27245. * Clear the info related to rendering groups preventing retention points during dispose.
  27246. */
  27247. Scene.prototype.freeRenderingGroups = function () {
  27248. if (this._renderingManager) {
  27249. this._renderingManager.freeRenderingGroups();
  27250. }
  27251. if (this.textures) {
  27252. for (var i = 0; i < this.textures.length; i++) {
  27253. var texture = this.textures[i];
  27254. if (texture && texture.renderList) {
  27255. texture.freeRenderingGroups();
  27256. }
  27257. }
  27258. }
  27259. };
  27260. /** @hidden */
  27261. Scene.prototype._isInIntermediateRendering = function () {
  27262. return this._intermediateRendering;
  27263. };
  27264. /**
  27265. * Defines the current active mesh candidate provider
  27266. * @param provider defines the provider to use
  27267. */
  27268. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27269. this._activeMeshCandidateProvider = provider;
  27270. };
  27271. /**
  27272. * Gets the current active mesh candidate provider
  27273. * @returns the current active mesh candidate provider
  27274. */
  27275. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27276. return this._activeMeshCandidateProvider;
  27277. };
  27278. /**
  27279. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27280. * @returns the current scene
  27281. */
  27282. Scene.prototype.freezeActiveMeshes = function () {
  27283. if (!this.activeCamera) {
  27284. return this;
  27285. }
  27286. if (!this._frustumPlanes) {
  27287. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27288. }
  27289. this._evaluateActiveMeshes();
  27290. this._activeMeshesFrozen = true;
  27291. return this;
  27292. };
  27293. /**
  27294. * Use this function to restart evaluating active meshes on every frame
  27295. * @returns the current scene
  27296. */
  27297. Scene.prototype.unfreezeActiveMeshes = function () {
  27298. this._activeMeshesFrozen = false;
  27299. return this;
  27300. };
  27301. Scene.prototype._evaluateActiveMeshes = function () {
  27302. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27303. return;
  27304. }
  27305. if (!this.activeCamera) {
  27306. return;
  27307. }
  27308. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27309. this.activeCamera._activeMeshes.reset();
  27310. this._activeMeshes.reset();
  27311. this._renderingManager.reset();
  27312. this._processedMaterials.reset();
  27313. this._activeParticleSystems.reset();
  27314. this._activeSkeletons.reset();
  27315. this._softwareSkinnedMeshes.reset();
  27316. if (this._boundingBoxRenderer) {
  27317. this._boundingBoxRenderer.reset();
  27318. }
  27319. // Meshes
  27320. var meshes;
  27321. var len;
  27322. var checkIsEnabled = true;
  27323. // Determine mesh candidates
  27324. if (this._activeMeshCandidateProvider !== undefined) {
  27325. // Use _activeMeshCandidateProvider
  27326. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27327. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27328. if (meshes !== undefined) {
  27329. len = meshes.length;
  27330. }
  27331. else {
  27332. len = 0;
  27333. }
  27334. }
  27335. else if (this._selectionOctree !== undefined) {
  27336. // Octree
  27337. var selection = this._selectionOctree.select(this._frustumPlanes);
  27338. meshes = selection.data;
  27339. len = selection.length;
  27340. }
  27341. else {
  27342. // Full scene traversal
  27343. len = this.meshes.length;
  27344. meshes = this.meshes;
  27345. }
  27346. // Check each mesh
  27347. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27348. mesh = meshes[meshIndex];
  27349. if (mesh.isBlocked) {
  27350. continue;
  27351. }
  27352. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27353. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27354. continue;
  27355. }
  27356. mesh.computeWorldMatrix();
  27357. // Intersections
  27358. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27359. this._meshesForIntersections.pushNoDuplicate(mesh);
  27360. }
  27361. // Switch to current LOD
  27362. meshLOD = mesh.getLOD(this.activeCamera);
  27363. if (meshLOD === undefined || meshLOD === null) {
  27364. continue;
  27365. }
  27366. mesh._preActivate();
  27367. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27368. this._activeMeshes.push(mesh);
  27369. this.activeCamera._activeMeshes.push(mesh);
  27370. mesh._activate(this._renderId);
  27371. if (meshLOD !== mesh) {
  27372. meshLOD._activate(this._renderId);
  27373. }
  27374. this._activeMesh(mesh, meshLOD);
  27375. }
  27376. }
  27377. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27378. // Particle systems
  27379. if (this.particlesEnabled) {
  27380. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27381. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27382. var particleSystem = this.particleSystems[particleIndex];
  27383. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27384. continue;
  27385. }
  27386. var emitter = particleSystem.emitter;
  27387. if (!emitter.position || emitter.isEnabled()) {
  27388. this._activeParticleSystems.push(particleSystem);
  27389. particleSystem.animate();
  27390. this._renderingManager.dispatchParticles(particleSystem);
  27391. }
  27392. }
  27393. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27394. }
  27395. };
  27396. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27397. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27398. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27399. mesh.skeleton.prepare();
  27400. }
  27401. if (!mesh.computeBonesUsingShaders) {
  27402. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27403. }
  27404. }
  27405. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27406. var boundingInfo = sourceMesh.getBoundingInfo();
  27407. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27408. }
  27409. if (mesh !== undefined && mesh !== null
  27410. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27411. // Submeshes Octrees
  27412. var len;
  27413. var subMeshes;
  27414. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27415. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27416. len = intersections.length;
  27417. subMeshes = intersections.data;
  27418. }
  27419. else {
  27420. subMeshes = mesh.subMeshes;
  27421. len = subMeshes.length;
  27422. }
  27423. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27424. subMesh = subMeshes[subIndex];
  27425. this._evaluateSubMesh(subMesh, mesh);
  27426. }
  27427. }
  27428. };
  27429. /**
  27430. * Update the transform matrix to update from the current active camera
  27431. * @param force defines a boolean used to force the update even if cache is up to date
  27432. */
  27433. Scene.prototype.updateTransformMatrix = function (force) {
  27434. if (!this.activeCamera) {
  27435. return;
  27436. }
  27437. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27438. };
  27439. /**
  27440. * 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)
  27441. * @param alternateCamera defines the camera to use
  27442. */
  27443. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27444. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27445. };
  27446. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27447. if (camera && camera._skipRendering) {
  27448. return;
  27449. }
  27450. var engine = this._engine;
  27451. this.activeCamera = camera;
  27452. if (!this.activeCamera)
  27453. throw new Error("Active camera not set");
  27454. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27455. // Viewport
  27456. engine.setViewport(this.activeCamera.viewport);
  27457. // Camera
  27458. this.resetCachedMaterial();
  27459. this._renderId++;
  27460. this.updateTransformMatrix();
  27461. if (camera._alternateCamera) {
  27462. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27463. this._alternateRendering = true;
  27464. }
  27465. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27466. // Meshes
  27467. this._evaluateActiveMeshes();
  27468. // Software skinning
  27469. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27470. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27471. mesh.applySkeleton(mesh.skeleton);
  27472. }
  27473. // Render targets
  27474. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27475. var needsRestoreFrameBuffer = false;
  27476. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27477. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27478. }
  27479. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27480. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27481. }
  27482. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27483. this._intermediateRendering = true;
  27484. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27485. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27486. var renderTarget = this._renderTargets.data[renderIndex];
  27487. if (renderTarget._shouldRender()) {
  27488. this._renderId++;
  27489. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27490. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27491. }
  27492. }
  27493. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27494. this._intermediateRendering = false;
  27495. this._renderId++;
  27496. needsRestoreFrameBuffer = true; // Restore back buffer
  27497. }
  27498. // Render EffecttLayer Texture
  27499. var stencilState = this._engine.getStencilBuffer();
  27500. var renderEffects = false;
  27501. var needStencil = false;
  27502. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27503. this._intermediateRendering = true;
  27504. for (var i = 0; i < this.effectLayers.length; i++) {
  27505. var effectLayer = this.effectLayers[i];
  27506. if (effectLayer.shouldRender() &&
  27507. (!effectLayer.camera ||
  27508. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27509. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27510. renderEffects = true;
  27511. needStencil = needStencil || effectLayer.needStencil();
  27512. var renderTarget = effectLayer._mainTexture;
  27513. if (renderTarget._shouldRender()) {
  27514. this._renderId++;
  27515. renderTarget.render(false, false);
  27516. needsRestoreFrameBuffer = true;
  27517. }
  27518. }
  27519. }
  27520. this._intermediateRendering = false;
  27521. this._renderId++;
  27522. }
  27523. if (needsRestoreFrameBuffer) {
  27524. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27525. }
  27526. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27527. // Prepare Frame
  27528. this.postProcessManager._prepareFrame();
  27529. // Backgrounds
  27530. var layerIndex;
  27531. var layer;
  27532. if (this.layers.length) {
  27533. engine.setDepthBuffer(false);
  27534. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27535. layer = this.layers[layerIndex];
  27536. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27537. layer.render();
  27538. }
  27539. }
  27540. engine.setDepthBuffer(true);
  27541. }
  27542. // Activate effect Layer stencil
  27543. if (needStencil) {
  27544. this._engine.setStencilBuffer(true);
  27545. }
  27546. // Render
  27547. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27548. this._renderingManager.render(null, null, true, true);
  27549. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27550. // Restore effect Layer stencil
  27551. if (needStencil) {
  27552. this._engine.setStencilBuffer(stencilState);
  27553. }
  27554. // Bounding boxes
  27555. if (this._boundingBoxRenderer) {
  27556. this._boundingBoxRenderer.render();
  27557. }
  27558. // Lens flares
  27559. if (this.lensFlaresEnabled) {
  27560. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27561. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27562. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27563. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27564. lensFlareSystem.render();
  27565. }
  27566. }
  27567. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27568. }
  27569. // Effect Layer
  27570. if (renderEffects) {
  27571. engine.setDepthBuffer(false);
  27572. for (var i = 0; i < this.effectLayers.length; i++) {
  27573. if (this.effectLayers[i].shouldRender()) {
  27574. this.effectLayers[i].render();
  27575. }
  27576. }
  27577. engine.setDepthBuffer(true);
  27578. }
  27579. // Foregrounds
  27580. if (this.layers.length) {
  27581. engine.setDepthBuffer(false);
  27582. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27583. layer = this.layers[layerIndex];
  27584. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27585. layer.render();
  27586. }
  27587. }
  27588. engine.setDepthBuffer(true);
  27589. }
  27590. // Finalize frame
  27591. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27592. // Reset some special arrays
  27593. this._renderTargets.reset();
  27594. this._alternateRendering = false;
  27595. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27596. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27597. };
  27598. Scene.prototype._processSubCameras = function (camera) {
  27599. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27600. this._renderForCamera(camera);
  27601. return;
  27602. }
  27603. // rig cameras
  27604. for (var index = 0; index < camera._rigCameras.length; index++) {
  27605. this._renderForCamera(camera._rigCameras[index], camera);
  27606. }
  27607. this.activeCamera = camera;
  27608. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27609. };
  27610. Scene.prototype._checkIntersections = function () {
  27611. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27612. var sourceMesh = this._meshesForIntersections.data[index];
  27613. if (!sourceMesh.actionManager) {
  27614. continue;
  27615. }
  27616. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27617. var action = sourceMesh.actionManager.actions[actionIndex];
  27618. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27619. var parameters = action.getTriggerParameter();
  27620. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27621. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27622. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27623. if (areIntersecting && currentIntersectionInProgress === -1) {
  27624. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27625. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27626. sourceMesh._intersectionsInProgress.push(otherMesh);
  27627. }
  27628. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27629. sourceMesh._intersectionsInProgress.push(otherMesh);
  27630. }
  27631. }
  27632. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27633. //They intersected, and now they don't.
  27634. //is this trigger an exit trigger? execute an event.
  27635. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27636. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27637. }
  27638. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27639. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27640. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27641. return otherMesh === parameterMesh;
  27642. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27643. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27644. }
  27645. }
  27646. }
  27647. }
  27648. }
  27649. };
  27650. /**
  27651. * Render the scene
  27652. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27653. */
  27654. Scene.prototype.render = function (updateCameras) {
  27655. if (updateCameras === void 0) { updateCameras = true; }
  27656. if (this.isDisposed) {
  27657. return;
  27658. }
  27659. this._activeParticles.fetchNewFrame();
  27660. this._totalVertices.fetchNewFrame();
  27661. this._activeIndices.fetchNewFrame();
  27662. this._activeBones.fetchNewFrame();
  27663. this._meshesForIntersections.reset();
  27664. this.resetCachedMaterial();
  27665. this.onBeforeAnimationsObservable.notifyObservers(this);
  27666. // Actions
  27667. if (this.actionManager) {
  27668. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27669. }
  27670. //Simplification Queue
  27671. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27672. this.simplificationQueue.executeNext();
  27673. }
  27674. if (this._engine.isDeterministicLockStep()) {
  27675. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27676. var defaultFPS = (60.0 / 1000.0);
  27677. var defaultFrameTime = 1000 / 60; // frame time in MS
  27678. if (this._physicsEngine) {
  27679. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27680. }
  27681. var stepsTaken = 0;
  27682. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27683. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27684. internalSteps = Math.min(internalSteps, maxSubSteps);
  27685. do {
  27686. this.onBeforeStepObservable.notifyObservers(this);
  27687. // Animations
  27688. this._animationRatio = defaultFrameTime * defaultFPS;
  27689. this._animate();
  27690. this.onAfterAnimationsObservable.notifyObservers(this);
  27691. // Physics
  27692. if (this._physicsEngine) {
  27693. this.onBeforePhysicsObservable.notifyObservers(this);
  27694. this._physicsEngine._step(defaultFrameTime / 1000);
  27695. this.onAfterPhysicsObservable.notifyObservers(this);
  27696. }
  27697. this.onAfterStepObservable.notifyObservers(this);
  27698. this._currentStepId++;
  27699. stepsTaken++;
  27700. deltaTime -= defaultFrameTime;
  27701. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27702. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27703. }
  27704. else {
  27705. // Animations
  27706. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27707. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27708. this._animate();
  27709. this.onAfterAnimationsObservable.notifyObservers(this);
  27710. // Physics
  27711. if (this._physicsEngine) {
  27712. this.onBeforePhysicsObservable.notifyObservers(this);
  27713. this._physicsEngine._step(deltaTime / 1000.0);
  27714. this.onAfterPhysicsObservable.notifyObservers(this);
  27715. }
  27716. }
  27717. // update gamepad manager
  27718. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27719. this._gamepadManager._checkGamepadsStatus();
  27720. }
  27721. // Update Cameras
  27722. if (updateCameras) {
  27723. if (this.activeCameras.length > 0) {
  27724. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27725. var camera = this.activeCameras[cameraIndex];
  27726. camera.update();
  27727. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27728. // rig cameras
  27729. for (var index = 0; index < camera._rigCameras.length; index++) {
  27730. camera._rigCameras[index].update();
  27731. }
  27732. }
  27733. }
  27734. }
  27735. else if (this.activeCamera) {
  27736. this.activeCamera.update();
  27737. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27738. // rig cameras
  27739. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27740. this.activeCamera._rigCameras[index].update();
  27741. }
  27742. }
  27743. }
  27744. }
  27745. // Before render
  27746. this.onBeforeRenderObservable.notifyObservers(this);
  27747. // Customs render targets
  27748. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27749. var engine = this.getEngine();
  27750. var currentActiveCamera = this.activeCamera;
  27751. if (this.renderTargetsEnabled) {
  27752. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27753. this._intermediateRendering = true;
  27754. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27755. var renderTarget = this.customRenderTargets[customIndex];
  27756. if (renderTarget._shouldRender()) {
  27757. this._renderId++;
  27758. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27759. if (!this.activeCamera)
  27760. throw new Error("Active camera not set");
  27761. // Viewport
  27762. engine.setViewport(this.activeCamera.viewport);
  27763. // Camera
  27764. this.updateTransformMatrix();
  27765. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27766. }
  27767. }
  27768. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27769. this._intermediateRendering = false;
  27770. this._renderId++;
  27771. }
  27772. // Restore back buffer
  27773. if (this.customRenderTargets.length > 0) {
  27774. engine.restoreDefaultFramebuffer();
  27775. }
  27776. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27777. this.activeCamera = currentActiveCamera;
  27778. // Procedural textures
  27779. if (this.proceduralTexturesEnabled) {
  27780. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27781. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27782. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27783. if (proceduralTexture._shouldRender()) {
  27784. proceduralTexture.render();
  27785. }
  27786. }
  27787. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27788. }
  27789. // Clear
  27790. if (this.autoClearDepthAndStencil || this.autoClear) {
  27791. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27792. }
  27793. // Shadows
  27794. if (this.shadowsEnabled) {
  27795. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27796. var light = this.lights[lightIndex];
  27797. var shadowGenerator = light.getShadowGenerator();
  27798. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27799. var shadowMap = (shadowGenerator.getShadowMap());
  27800. if (this.textures.indexOf(shadowMap) !== -1) {
  27801. this._renderTargets.push(shadowMap);
  27802. }
  27803. }
  27804. }
  27805. }
  27806. // Depth renderer
  27807. for (var key in this._depthRenderer) {
  27808. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27809. }
  27810. // Geometry renderer
  27811. if (this._geometryBufferRenderer) {
  27812. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27813. }
  27814. // RenderPipeline
  27815. if (this._postProcessRenderPipelineManager) {
  27816. this._postProcessRenderPipelineManager.update();
  27817. }
  27818. // Multi-cameras?
  27819. if (this.activeCameras.length > 0) {
  27820. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27821. if (cameraIndex > 0) {
  27822. this._engine.clear(null, false, true, true);
  27823. }
  27824. this._processSubCameras(this.activeCameras[cameraIndex]);
  27825. }
  27826. }
  27827. else {
  27828. if (!this.activeCamera) {
  27829. throw new Error("No camera defined");
  27830. }
  27831. this._processSubCameras(this.activeCamera);
  27832. }
  27833. // Intersection checks
  27834. this._checkIntersections();
  27835. // Update the audio listener attached to the camera
  27836. if (BABYLON.AudioEngine) {
  27837. this._updateAudioParameters();
  27838. }
  27839. // After render
  27840. if (this.afterRender) {
  27841. this.afterRender();
  27842. }
  27843. this.onAfterRenderObservable.notifyObservers(this);
  27844. // Cleaning
  27845. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27846. var data = this._toBeDisposed.data[index];
  27847. if (data) {
  27848. data.dispose();
  27849. }
  27850. this._toBeDisposed[index] = null;
  27851. }
  27852. this._toBeDisposed.reset();
  27853. if (this.dumpNextRenderTargets) {
  27854. this.dumpNextRenderTargets = false;
  27855. }
  27856. this._activeBones.addCount(0, true);
  27857. this._activeIndices.addCount(0, true);
  27858. this._activeParticles.addCount(0, true);
  27859. };
  27860. Scene.prototype._updateAudioParameters = function () {
  27861. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27862. return;
  27863. }
  27864. var listeningCamera;
  27865. var audioEngine = BABYLON.Engine.audioEngine;
  27866. if (this.activeCameras.length > 0) {
  27867. listeningCamera = this.activeCameras[0];
  27868. }
  27869. else {
  27870. listeningCamera = this.activeCamera;
  27871. }
  27872. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27873. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27874. // for VR cameras
  27875. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27876. listeningCamera = listeningCamera.rigCameras[0];
  27877. }
  27878. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27879. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27880. cameraDirection.normalize();
  27881. // To avoid some errors on GearVR
  27882. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27884. }
  27885. var i;
  27886. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27887. var sound = this.mainSoundTrack.soundCollection[i];
  27888. if (sound.useCustomAttenuation) {
  27889. sound.updateDistanceFromListener();
  27890. }
  27891. }
  27892. for (i = 0; i < this.soundTracks.length; i++) {
  27893. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27894. sound = this.soundTracks[i].soundCollection[j];
  27895. if (sound.useCustomAttenuation) {
  27896. sound.updateDistanceFromListener();
  27897. }
  27898. }
  27899. }
  27900. }
  27901. };
  27902. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27903. // Audio
  27904. /**
  27905. * Gets or sets if audio support is enabled
  27906. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27907. */
  27908. get: function () {
  27909. return this._audioEnabled;
  27910. },
  27911. set: function (value) {
  27912. this._audioEnabled = value;
  27913. if (BABYLON.AudioEngine) {
  27914. if (this._audioEnabled) {
  27915. this._enableAudio();
  27916. }
  27917. else {
  27918. this._disableAudio();
  27919. }
  27920. }
  27921. },
  27922. enumerable: true,
  27923. configurable: true
  27924. });
  27925. Scene.prototype._disableAudio = function () {
  27926. var i;
  27927. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27928. this.mainSoundTrack.soundCollection[i].pause();
  27929. }
  27930. for (i = 0; i < this.soundTracks.length; i++) {
  27931. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27932. this.soundTracks[i].soundCollection[j].pause();
  27933. }
  27934. }
  27935. };
  27936. Scene.prototype._enableAudio = function () {
  27937. var i;
  27938. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27939. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27940. this.mainSoundTrack.soundCollection[i].play();
  27941. }
  27942. }
  27943. for (i = 0; i < this.soundTracks.length; i++) {
  27944. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27945. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27946. this.soundTracks[i].soundCollection[j].play();
  27947. }
  27948. }
  27949. }
  27950. };
  27951. Object.defineProperty(Scene.prototype, "headphone", {
  27952. /**
  27953. * Gets or sets if audio will be output to headphones
  27954. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27955. */
  27956. get: function () {
  27957. return this._headphone;
  27958. },
  27959. set: function (value) {
  27960. this._headphone = value;
  27961. if (BABYLON.AudioEngine) {
  27962. if (this._headphone) {
  27963. this._switchAudioModeForHeadphones();
  27964. }
  27965. else {
  27966. this._switchAudioModeForNormalSpeakers();
  27967. }
  27968. }
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. Scene.prototype._switchAudioModeForHeadphones = function () {
  27974. this.mainSoundTrack.switchPanningModelToHRTF();
  27975. for (var i = 0; i < this.soundTracks.length; i++) {
  27976. this.soundTracks[i].switchPanningModelToHRTF();
  27977. }
  27978. };
  27979. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27980. this.mainSoundTrack.switchPanningModelToEqualPower();
  27981. for (var i = 0; i < this.soundTracks.length; i++) {
  27982. this.soundTracks[i].switchPanningModelToEqualPower();
  27983. }
  27984. };
  27985. /**
  27986. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27987. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27988. * @returns the created depth renderer
  27989. */
  27990. Scene.prototype.enableDepthRenderer = function (camera) {
  27991. camera = camera || this.activeCamera;
  27992. if (!camera) {
  27993. throw "No camera available to enable depth renderer";
  27994. }
  27995. if (!this._depthRenderer[camera.id]) {
  27996. var textureType = 0;
  27997. if (this._engine.getCaps().textureHalfFloatRender) {
  27998. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27999. }
  28000. else if (this._engine.getCaps().textureFloatRender) {
  28001. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28002. }
  28003. else {
  28004. throw "Depth renderer does not support int texture type";
  28005. }
  28006. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28007. }
  28008. return this._depthRenderer[camera.id];
  28009. };
  28010. /**
  28011. * Disables a depth renderer for a given camera
  28012. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28013. */
  28014. Scene.prototype.disableDepthRenderer = function (camera) {
  28015. camera = camera || this.activeCamera;
  28016. if (!camera || !this._depthRenderer[camera.id]) {
  28017. return;
  28018. }
  28019. this._depthRenderer[camera.id].dispose();
  28020. delete this._depthRenderer[camera.id];
  28021. };
  28022. /**
  28023. * Enables a GeometryBufferRender and associates it with the scene
  28024. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28025. * @returns the GeometryBufferRenderer
  28026. */
  28027. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28028. if (ratio === void 0) { ratio = 1; }
  28029. if (this._geometryBufferRenderer) {
  28030. return this._geometryBufferRenderer;
  28031. }
  28032. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28033. if (!this._geometryBufferRenderer.isSupported) {
  28034. this._geometryBufferRenderer = null;
  28035. }
  28036. return this._geometryBufferRenderer;
  28037. };
  28038. /**
  28039. * Disables the GeometryBufferRender associated with the scene
  28040. */
  28041. Scene.prototype.disableGeometryBufferRenderer = function () {
  28042. if (!this._geometryBufferRenderer) {
  28043. return;
  28044. }
  28045. this._geometryBufferRenderer.dispose();
  28046. this._geometryBufferRenderer = null;
  28047. };
  28048. /**
  28049. * Freeze all materials
  28050. * A frozen material will not be updatable but should be faster to render
  28051. */
  28052. Scene.prototype.freezeMaterials = function () {
  28053. for (var i = 0; i < this.materials.length; i++) {
  28054. this.materials[i].freeze();
  28055. }
  28056. };
  28057. /**
  28058. * Unfreeze all materials
  28059. * A frozen material will not be updatable but should be faster to render
  28060. */
  28061. Scene.prototype.unfreezeMaterials = function () {
  28062. for (var i = 0; i < this.materials.length; i++) {
  28063. this.materials[i].unfreeze();
  28064. }
  28065. };
  28066. /**
  28067. * Releases all held ressources
  28068. */
  28069. Scene.prototype.dispose = function () {
  28070. this.beforeRender = null;
  28071. this.afterRender = null;
  28072. this.skeletons = [];
  28073. this.morphTargetManagers = [];
  28074. this.importedMeshesFiles = new Array();
  28075. this.stopAllAnimations();
  28076. this.resetCachedMaterial();
  28077. for (var key in this._depthRenderer) {
  28078. this._depthRenderer[key].dispose();
  28079. }
  28080. if (this._gamepadManager) {
  28081. this._gamepadManager.dispose();
  28082. this._gamepadManager = null;
  28083. }
  28084. // Smart arrays
  28085. if (this.activeCamera) {
  28086. this.activeCamera._activeMeshes.dispose();
  28087. this.activeCamera = null;
  28088. }
  28089. this._activeMeshes.dispose();
  28090. this._renderingManager.dispose();
  28091. this._processedMaterials.dispose();
  28092. this._activeParticleSystems.dispose();
  28093. this._activeSkeletons.dispose();
  28094. this._softwareSkinnedMeshes.dispose();
  28095. this._renderTargets.dispose();
  28096. this._registeredForLateAnimationBindings.dispose();
  28097. if (this._boundingBoxRenderer) {
  28098. this._boundingBoxRenderer.dispose();
  28099. }
  28100. this._meshesForIntersections.dispose();
  28101. this._toBeDisposed.dispose();
  28102. // Abort active requests
  28103. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28104. var request = _a[_i];
  28105. request.abort();
  28106. }
  28107. // Debug layer
  28108. if (this._debugLayer) {
  28109. this._debugLayer.hide();
  28110. }
  28111. // Events
  28112. this.onDisposeObservable.notifyObservers(this);
  28113. this.onDisposeObservable.clear();
  28114. this.onBeforeRenderObservable.clear();
  28115. this.onAfterRenderObservable.clear();
  28116. this.onBeforeRenderTargetsRenderObservable.clear();
  28117. this.onAfterRenderTargetsRenderObservable.clear();
  28118. this.onAfterStepObservable.clear();
  28119. this.onBeforeStepObservable.clear();
  28120. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28121. this.onAfterActiveMeshesEvaluationObservable.clear();
  28122. this.onBeforeParticlesRenderingObservable.clear();
  28123. this.onAfterParticlesRenderingObservable.clear();
  28124. this.onBeforeSpritesRenderingObservable.clear();
  28125. this.onAfterSpritesRenderingObservable.clear();
  28126. this.onBeforeDrawPhaseObservable.clear();
  28127. this.onAfterDrawPhaseObservable.clear();
  28128. this.onBeforePhysicsObservable.clear();
  28129. this.onAfterPhysicsObservable.clear();
  28130. this.onBeforeAnimationsObservable.clear();
  28131. this.onAfterAnimationsObservable.clear();
  28132. this.onDataLoadedObservable.clear();
  28133. this.detachControl();
  28134. // Release sounds & sounds tracks
  28135. if (BABYLON.AudioEngine) {
  28136. this.disposeSounds();
  28137. }
  28138. // VR Helper
  28139. if (this.VRHelper) {
  28140. this.VRHelper.dispose();
  28141. }
  28142. // Detach cameras
  28143. var canvas = this._engine.getRenderingCanvas();
  28144. if (canvas) {
  28145. var index;
  28146. for (index = 0; index < this.cameras.length; index++) {
  28147. this.cameras[index].detachControl(canvas);
  28148. }
  28149. }
  28150. // Release animation groups
  28151. while (this.animationGroups.length) {
  28152. this.animationGroups[0].dispose();
  28153. }
  28154. // Release lights
  28155. while (this.lights.length) {
  28156. this.lights[0].dispose();
  28157. }
  28158. // Release meshes
  28159. while (this.meshes.length) {
  28160. this.meshes[0].dispose(true);
  28161. }
  28162. while (this.transformNodes.length) {
  28163. this.removeTransformNode(this.transformNodes[0]);
  28164. }
  28165. // Release cameras
  28166. while (this.cameras.length) {
  28167. this.cameras[0].dispose();
  28168. }
  28169. // Release materials
  28170. if (this.defaultMaterial) {
  28171. this.defaultMaterial.dispose();
  28172. }
  28173. while (this.multiMaterials.length) {
  28174. this.multiMaterials[0].dispose();
  28175. }
  28176. while (this.materials.length) {
  28177. this.materials[0].dispose();
  28178. }
  28179. // Release particles
  28180. while (this.particleSystems.length) {
  28181. this.particleSystems[0].dispose();
  28182. }
  28183. // Release sprites
  28184. while (this.spriteManagers.length) {
  28185. this.spriteManagers[0].dispose();
  28186. }
  28187. // Release postProcesses
  28188. while (this.postProcesses.length) {
  28189. this.postProcesses[0].dispose();
  28190. }
  28191. // Release layers
  28192. while (this.layers.length) {
  28193. this.layers[0].dispose();
  28194. }
  28195. while (this.effectLayers.length) {
  28196. this.effectLayers[0].dispose();
  28197. }
  28198. // Release textures
  28199. while (this.textures.length) {
  28200. this.textures[0].dispose();
  28201. }
  28202. // Release UBO
  28203. this._sceneUbo.dispose();
  28204. if (this._alternateSceneUbo) {
  28205. this._alternateSceneUbo.dispose();
  28206. }
  28207. // Post-processes
  28208. this.postProcessManager.dispose();
  28209. if (this._postProcessRenderPipelineManager) {
  28210. this._postProcessRenderPipelineManager.dispose();
  28211. }
  28212. // Physics
  28213. if (this._physicsEngine) {
  28214. this.disablePhysicsEngine();
  28215. }
  28216. // Remove from engine
  28217. index = this._engine.scenes.indexOf(this);
  28218. if (index > -1) {
  28219. this._engine.scenes.splice(index, 1);
  28220. }
  28221. this._engine.wipeCaches(true);
  28222. this._isDisposed = true;
  28223. };
  28224. Object.defineProperty(Scene.prototype, "isDisposed", {
  28225. /**
  28226. * Gets if the scene is already disposed
  28227. */
  28228. get: function () {
  28229. return this._isDisposed;
  28230. },
  28231. enumerable: true,
  28232. configurable: true
  28233. });
  28234. /**
  28235. * Releases sounds & soundtracks
  28236. */
  28237. Scene.prototype.disposeSounds = function () {
  28238. if (!this._mainSoundTrack) {
  28239. return;
  28240. }
  28241. this.mainSoundTrack.dispose();
  28242. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28243. this.soundTracks[scIndex].dispose();
  28244. }
  28245. };
  28246. /**
  28247. * Call this function to reduce memory footprint of the scene.
  28248. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28249. */
  28250. Scene.prototype.clearCachedVertexData = function () {
  28251. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28252. var mesh = this.meshes[meshIndex];
  28253. var geometry = mesh.geometry;
  28254. if (geometry) {
  28255. geometry._indices = [];
  28256. for (var vbName in geometry._vertexBuffers) {
  28257. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28258. continue;
  28259. }
  28260. geometry._vertexBuffers[vbName]._buffer._data = null;
  28261. }
  28262. }
  28263. }
  28264. };
  28265. /**
  28266. * This function will remove the local cached buffer data from texture.
  28267. * It will save memory but will prevent the texture from being rebuilt
  28268. */
  28269. Scene.prototype.cleanCachedTextureBuffer = function () {
  28270. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28271. var baseTexture = _a[_i];
  28272. var buffer = baseTexture._buffer;
  28273. if (buffer) {
  28274. baseTexture._buffer = null;
  28275. }
  28276. }
  28277. };
  28278. // Octrees
  28279. /**
  28280. * Get the world extend vectors with an optional filter
  28281. *
  28282. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28283. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28284. */
  28285. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28286. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28287. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28288. filterPredicate = filterPredicate || (function () { return true; });
  28289. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28290. mesh.computeWorldMatrix(true);
  28291. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28292. return;
  28293. }
  28294. var boundingInfo = mesh.getBoundingInfo();
  28295. var minBox = boundingInfo.boundingBox.minimumWorld;
  28296. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28297. BABYLON.Tools.CheckExtends(minBox, min, max);
  28298. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28299. });
  28300. return {
  28301. min: min,
  28302. max: max
  28303. };
  28304. };
  28305. /**
  28306. * Creates or updates the octree used to boost selection (picking)
  28307. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28308. * @param maxCapacity defines the maximum capacity per leaf
  28309. * @param maxDepth defines the maximum depth of the octree
  28310. * @returns an octree of AbstractMesh
  28311. */
  28312. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28313. if (maxCapacity === void 0) { maxCapacity = 64; }
  28314. if (maxDepth === void 0) { maxDepth = 2; }
  28315. if (!this._selectionOctree) {
  28316. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28317. }
  28318. var worldExtends = this.getWorldExtends();
  28319. // Update octree
  28320. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28321. return this._selectionOctree;
  28322. };
  28323. // Picking
  28324. /**
  28325. * Creates a ray that can be used to pick in the scene
  28326. * @param x defines the x coordinate of the origin (on-screen)
  28327. * @param y defines the y coordinate of the origin (on-screen)
  28328. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28329. * @param camera defines the camera to use for the picking
  28330. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28331. * @returns a Ray
  28332. */
  28333. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28334. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28335. var result = BABYLON.Ray.Zero();
  28336. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28337. return result;
  28338. };
  28339. /**
  28340. * Creates a ray that can be used to pick in the scene
  28341. * @param x defines the x coordinate of the origin (on-screen)
  28342. * @param y defines the y coordinate of the origin (on-screen)
  28343. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28344. * @param result defines the ray where to store the picking ray
  28345. * @param camera defines the camera to use for the picking
  28346. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28347. * @returns the current scene
  28348. */
  28349. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28350. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28351. var engine = this._engine;
  28352. if (!camera) {
  28353. if (!this.activeCamera)
  28354. throw new Error("Active camera not set");
  28355. camera = this.activeCamera;
  28356. }
  28357. var cameraViewport = camera.viewport;
  28358. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28359. // Moving coordinates to local viewport world
  28360. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28361. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28362. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28363. return this;
  28364. };
  28365. /**
  28366. * Creates a ray that can be used to pick in the scene
  28367. * @param x defines the x coordinate of the origin (on-screen)
  28368. * @param y defines the y coordinate of the origin (on-screen)
  28369. * @param camera defines the camera to use for the picking
  28370. * @returns a Ray
  28371. */
  28372. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28373. var result = BABYLON.Ray.Zero();
  28374. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28375. return result;
  28376. };
  28377. /**
  28378. * Creates a ray that can be used to pick in the scene
  28379. * @param x defines the x coordinate of the origin (on-screen)
  28380. * @param y defines the y coordinate of the origin (on-screen)
  28381. * @param result defines the ray where to store the picking ray
  28382. * @param camera defines the camera to use for the picking
  28383. * @returns the current scene
  28384. */
  28385. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28386. if (!BABYLON.PickingInfo) {
  28387. return this;
  28388. }
  28389. var engine = this._engine;
  28390. if (!camera) {
  28391. if (!this.activeCamera)
  28392. throw new Error("Active camera not set");
  28393. camera = this.activeCamera;
  28394. }
  28395. var cameraViewport = camera.viewport;
  28396. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28397. var identity = BABYLON.Matrix.Identity();
  28398. // Moving coordinates to local viewport world
  28399. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28400. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28401. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28402. return this;
  28403. };
  28404. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28405. if (!BABYLON.PickingInfo) {
  28406. return null;
  28407. }
  28408. var pickingInfo = null;
  28409. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28410. var mesh = this.meshes[meshIndex];
  28411. if (predicate) {
  28412. if (!predicate(mesh)) {
  28413. continue;
  28414. }
  28415. }
  28416. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28417. continue;
  28418. }
  28419. var world = mesh.getWorldMatrix();
  28420. var ray = rayFunction(world);
  28421. var result = mesh.intersects(ray, fastCheck);
  28422. if (!result || !result.hit)
  28423. continue;
  28424. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28425. continue;
  28426. pickingInfo = result;
  28427. if (fastCheck) {
  28428. break;
  28429. }
  28430. }
  28431. return pickingInfo || new BABYLON.PickingInfo();
  28432. };
  28433. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28434. if (!BABYLON.PickingInfo) {
  28435. return null;
  28436. }
  28437. var pickingInfos = new Array();
  28438. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28439. var mesh = this.meshes[meshIndex];
  28440. if (predicate) {
  28441. if (!predicate(mesh)) {
  28442. continue;
  28443. }
  28444. }
  28445. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28446. continue;
  28447. }
  28448. var world = mesh.getWorldMatrix();
  28449. var ray = rayFunction(world);
  28450. var result = mesh.intersects(ray, false);
  28451. if (!result || !result.hit)
  28452. continue;
  28453. pickingInfos.push(result);
  28454. }
  28455. return pickingInfos;
  28456. };
  28457. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28458. if (!BABYLON.PickingInfo) {
  28459. return null;
  28460. }
  28461. var pickingInfo = null;
  28462. if (!camera) {
  28463. if (!this.activeCamera) {
  28464. return null;
  28465. }
  28466. camera = this.activeCamera;
  28467. }
  28468. if (this.spriteManagers.length > 0) {
  28469. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28470. var spriteManager = this.spriteManagers[spriteIndex];
  28471. if (!spriteManager.isPickable) {
  28472. continue;
  28473. }
  28474. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28475. if (!result || !result.hit)
  28476. continue;
  28477. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28478. continue;
  28479. pickingInfo = result;
  28480. if (fastCheck) {
  28481. break;
  28482. }
  28483. }
  28484. }
  28485. return pickingInfo || new BABYLON.PickingInfo();
  28486. };
  28487. /** Launch a ray to try to pick a mesh in the scene
  28488. * @param x position on screen
  28489. * @param y position on screen
  28490. * @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
  28491. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28492. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28493. * @returns a PickingInfo
  28494. */
  28495. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28496. var _this = this;
  28497. if (!BABYLON.PickingInfo) {
  28498. return null;
  28499. }
  28500. return this._internalPick(function (world) {
  28501. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28502. return _this._tempPickingRay;
  28503. }, predicate, fastCheck);
  28504. };
  28505. /** Launch a ray to try to pick a sprite in the scene
  28506. * @param x position on screen
  28507. * @param y position on screen
  28508. * @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
  28509. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28510. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28511. * @returns a PickingInfo
  28512. */
  28513. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28514. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28515. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28516. };
  28517. /** Use the given ray to pick a mesh in the scene
  28518. * @param ray The ray to use to pick meshes
  28519. * @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
  28520. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28521. * @returns a PickingInfo
  28522. */
  28523. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28524. var _this = this;
  28525. var result = this._internalPick(function (world) {
  28526. if (!_this._pickWithRayInverseMatrix) {
  28527. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28528. }
  28529. world.invertToRef(_this._pickWithRayInverseMatrix);
  28530. if (!_this._cachedRayForTransform) {
  28531. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28532. }
  28533. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28534. return _this._cachedRayForTransform;
  28535. }, predicate, fastCheck);
  28536. if (result) {
  28537. result.ray = ray;
  28538. }
  28539. return result;
  28540. };
  28541. /**
  28542. * Launch a ray to try to pick a mesh in the scene
  28543. * @param x X position on screen
  28544. * @param y Y position on screen
  28545. * @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
  28546. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28547. * @returns an array of PickingInfo
  28548. */
  28549. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28550. var _this = this;
  28551. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28552. };
  28553. /**
  28554. * Launch a ray to try to pick a mesh in the scene
  28555. * @param ray Ray to use
  28556. * @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
  28557. * @returns an array of PickingInfo
  28558. */
  28559. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28560. var _this = this;
  28561. return this._internalMultiPick(function (world) {
  28562. if (!_this._pickWithRayInverseMatrix) {
  28563. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28564. }
  28565. world.invertToRef(_this._pickWithRayInverseMatrix);
  28566. if (!_this._cachedRayForTransform) {
  28567. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28568. }
  28569. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28570. return _this._cachedRayForTransform;
  28571. }, predicate);
  28572. };
  28573. /**
  28574. * Force the value of meshUnderPointer
  28575. * @param mesh defines the mesh to use
  28576. */
  28577. Scene.prototype.setPointerOverMesh = function (mesh) {
  28578. if (this._pointerOverMesh === mesh) {
  28579. return;
  28580. }
  28581. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28582. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28583. }
  28584. this._pointerOverMesh = mesh;
  28585. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28586. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28587. }
  28588. };
  28589. /**
  28590. * Gets the mesh under the pointer
  28591. * @returns a Mesh or null if no mesh is under the pointer
  28592. */
  28593. Scene.prototype.getPointerOverMesh = function () {
  28594. return this._pointerOverMesh;
  28595. };
  28596. /**
  28597. * Force the sprite under the pointer
  28598. * @param sprite defines the sprite to use
  28599. */
  28600. Scene.prototype.setPointerOverSprite = function (sprite) {
  28601. if (this._pointerOverSprite === sprite) {
  28602. return;
  28603. }
  28604. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28605. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28606. }
  28607. this._pointerOverSprite = sprite;
  28608. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28609. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28610. }
  28611. };
  28612. /**
  28613. * Gets the sprite under the pointer
  28614. * @returns a Sprite or null if no sprite is under the pointer
  28615. */
  28616. Scene.prototype.getPointerOverSprite = function () {
  28617. return this._pointerOverSprite;
  28618. };
  28619. // Physics
  28620. /**
  28621. * Gets the current physics engine
  28622. * @returns a PhysicsEngine or null if none attached
  28623. */
  28624. Scene.prototype.getPhysicsEngine = function () {
  28625. return this._physicsEngine;
  28626. };
  28627. /**
  28628. * Enables physics to the current scene
  28629. * @param gravity defines the scene's gravity for the physics engine
  28630. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28631. * @return a boolean indicating if the physics engine was initialized
  28632. */
  28633. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28634. if (gravity === void 0) { gravity = null; }
  28635. if (this._physicsEngine) {
  28636. return true;
  28637. }
  28638. try {
  28639. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28640. return true;
  28641. }
  28642. catch (e) {
  28643. BABYLON.Tools.Error(e.message);
  28644. return false;
  28645. }
  28646. };
  28647. /**
  28648. * Disables and disposes the physics engine associated with the scene
  28649. */
  28650. Scene.prototype.disablePhysicsEngine = function () {
  28651. if (!this._physicsEngine) {
  28652. return;
  28653. }
  28654. this._physicsEngine.dispose();
  28655. this._physicsEngine = null;
  28656. };
  28657. /**
  28658. * Gets a boolean indicating if there is an active physics engine
  28659. * @returns a boolean indicating if there is an active physics engine
  28660. */
  28661. Scene.prototype.isPhysicsEnabled = function () {
  28662. return this._physicsEngine !== undefined;
  28663. };
  28664. /**
  28665. * Deletes a physics compound impostor
  28666. * @param compound defines the compound to delete
  28667. */
  28668. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28669. var mesh = compound.parts[0].mesh;
  28670. if (mesh.physicsImpostor) {
  28671. mesh.physicsImpostor.dispose( /*true*/);
  28672. mesh.physicsImpostor = null;
  28673. }
  28674. };
  28675. // Misc.
  28676. /** @hidden */
  28677. Scene.prototype._rebuildGeometries = function () {
  28678. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28679. var geometry = _a[_i];
  28680. geometry._rebuild();
  28681. }
  28682. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28683. var mesh = _c[_b];
  28684. mesh._rebuild();
  28685. }
  28686. if (this.postProcessManager) {
  28687. this.postProcessManager._rebuild();
  28688. }
  28689. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28690. var layer = _e[_d];
  28691. layer._rebuild();
  28692. }
  28693. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28694. var effectLayer = _g[_f];
  28695. effectLayer._rebuild();
  28696. }
  28697. if (this._boundingBoxRenderer) {
  28698. this._boundingBoxRenderer._rebuild();
  28699. }
  28700. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28701. var system = _j[_h];
  28702. system.rebuild();
  28703. }
  28704. if (this._postProcessRenderPipelineManager) {
  28705. this._postProcessRenderPipelineManager._rebuild();
  28706. }
  28707. };
  28708. /** @hidden */
  28709. Scene.prototype._rebuildTextures = function () {
  28710. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28711. var texture = _a[_i];
  28712. texture._rebuild();
  28713. }
  28714. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28715. };
  28716. /**
  28717. * Creates a default light for the scene.
  28718. * @param replace Whether to replace the existing lights in the scene.
  28719. */
  28720. Scene.prototype.createDefaultLight = function (replace) {
  28721. if (replace === void 0) { replace = false; }
  28722. // Dispose existing light in replace mode.
  28723. if (replace) {
  28724. if (this.lights) {
  28725. for (var i = 0; i < this.lights.length; i++) {
  28726. this.lights[i].dispose();
  28727. }
  28728. }
  28729. }
  28730. // Light
  28731. if (this.lights.length === 0) {
  28732. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28733. }
  28734. };
  28735. /**
  28736. * Creates a default camera for the scene.
  28737. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28738. * @param replace Whether to replace the existing active camera in the scene.
  28739. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28740. */
  28741. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28742. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28743. if (replace === void 0) { replace = false; }
  28744. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28745. // Dispose existing camera in replace mode.
  28746. if (replace) {
  28747. if (this.activeCamera) {
  28748. this.activeCamera.dispose();
  28749. this.activeCamera = null;
  28750. }
  28751. }
  28752. // Camera
  28753. if (!this.activeCamera) {
  28754. var worldExtends = this.getWorldExtends();
  28755. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28756. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28757. var camera;
  28758. var radius = worldSize.length() * 1.5;
  28759. // empty scene scenario!
  28760. if (!isFinite(radius)) {
  28761. radius = 1;
  28762. worldCenter.copyFromFloats(0, 0, 0);
  28763. }
  28764. if (createArcRotateCamera) {
  28765. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28766. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28767. arcRotateCamera.wheelPrecision = 100 / radius;
  28768. camera = arcRotateCamera;
  28769. }
  28770. else {
  28771. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28772. freeCamera.setTarget(worldCenter);
  28773. camera = freeCamera;
  28774. }
  28775. camera.minZ = radius * 0.01;
  28776. camera.maxZ = radius * 1000;
  28777. camera.speed = radius * 0.2;
  28778. this.activeCamera = camera;
  28779. var canvas = this.getEngine().getRenderingCanvas();
  28780. if (attachCameraControls && canvas) {
  28781. camera.attachControl(canvas);
  28782. }
  28783. }
  28784. };
  28785. /**
  28786. * Creates a default camera and a default light
  28787. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28788. * @param replace defines if the camera and/or light will replace the existing ones
  28789. * @param attachCameraControls defines if attachControl will be called on the new camera
  28790. */
  28791. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28792. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28793. if (replace === void 0) { replace = false; }
  28794. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28795. this.createDefaultLight(replace);
  28796. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28797. };
  28798. /**
  28799. * Creates a new sky box
  28800. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28801. * @param environmentTexture defines the texture to use as environment texture
  28802. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28803. * @param scale defines the overall scale of the skybox
  28804. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28805. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28806. * @returns a new mesh holding the sky box
  28807. */
  28808. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28809. if (pbr === void 0) { pbr = false; }
  28810. if (scale === void 0) { scale = 1000; }
  28811. if (blur === void 0) { blur = 0; }
  28812. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28813. if (!environmentTexture) {
  28814. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28815. return null;
  28816. }
  28817. if (setGlobalEnvTexture) {
  28818. if (environmentTexture) {
  28819. this.environmentTexture = environmentTexture;
  28820. }
  28821. }
  28822. // Skybox
  28823. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28824. if (pbr) {
  28825. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28826. hdrSkyboxMaterial.backFaceCulling = false;
  28827. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28828. if (hdrSkyboxMaterial.reflectionTexture) {
  28829. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28830. }
  28831. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28832. hdrSkyboxMaterial.disableLighting = true;
  28833. hdrSkyboxMaterial.twoSidedLighting = true;
  28834. hdrSkybox.infiniteDistance = true;
  28835. hdrSkybox.material = hdrSkyboxMaterial;
  28836. }
  28837. else {
  28838. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28839. skyboxMaterial.backFaceCulling = false;
  28840. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28841. if (skyboxMaterial.reflectionTexture) {
  28842. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28843. }
  28844. skyboxMaterial.disableLighting = true;
  28845. hdrSkybox.infiniteDistance = true;
  28846. hdrSkybox.material = skyboxMaterial;
  28847. }
  28848. return hdrSkybox;
  28849. };
  28850. /**
  28851. * Creates a new environment
  28852. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28853. * @param options defines the options you can use to configure the environment
  28854. * @returns the new EnvironmentHelper
  28855. */
  28856. Scene.prototype.createDefaultEnvironment = function (options) {
  28857. if (BABYLON.EnvironmentHelper) {
  28858. return new BABYLON.EnvironmentHelper(options, this);
  28859. }
  28860. return null;
  28861. };
  28862. /**
  28863. * Creates a new VREXperienceHelper
  28864. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28865. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28866. * @returns a new VREXperienceHelper
  28867. */
  28868. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28869. if (webVROptions === void 0) { webVROptions = {}; }
  28870. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28871. };
  28872. // Tags
  28873. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28874. if (tagsQuery === undefined) {
  28875. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28876. return list;
  28877. }
  28878. var listByTags = [];
  28879. forEach = forEach || (function (item) { return; });
  28880. for (var i in list) {
  28881. var item = list[i];
  28882. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28883. listByTags.push(item);
  28884. forEach(item);
  28885. }
  28886. }
  28887. return listByTags;
  28888. };
  28889. /**
  28890. * Get a list of meshes by tags
  28891. * @param tagsQuery defines the tags query to use
  28892. * @param forEach defines a predicate used to filter results
  28893. * @returns an array of Mesh
  28894. */
  28895. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28896. return this._getByTags(this.meshes, tagsQuery, forEach);
  28897. };
  28898. /**
  28899. * Get a list of cameras by tags
  28900. * @param tagsQuery defines the tags query to use
  28901. * @param forEach defines a predicate used to filter results
  28902. * @returns an array of Camera
  28903. */
  28904. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28905. return this._getByTags(this.cameras, tagsQuery, forEach);
  28906. };
  28907. /**
  28908. * Get a list of lights by tags
  28909. * @param tagsQuery defines the tags query to use
  28910. * @param forEach defines a predicate used to filter results
  28911. * @returns an array of Light
  28912. */
  28913. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28914. return this._getByTags(this.lights, tagsQuery, forEach);
  28915. };
  28916. /**
  28917. * Get a list of materials by tags
  28918. * @param tagsQuery defines the tags query to use
  28919. * @param forEach defines a predicate used to filter results
  28920. * @returns an array of Material
  28921. */
  28922. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28923. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28924. };
  28925. /**
  28926. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28927. * This allowed control for front to back rendering or reversly depending of the special needs.
  28928. *
  28929. * @param renderingGroupId The rendering group id corresponding to its index
  28930. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28931. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28932. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28933. */
  28934. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28935. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28936. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28937. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28938. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28939. };
  28940. /**
  28941. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28942. *
  28943. * @param renderingGroupId The rendering group id corresponding to its index
  28944. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28945. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28946. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28947. */
  28948. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28949. if (depth === void 0) { depth = true; }
  28950. if (stencil === void 0) { stencil = true; }
  28951. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28952. };
  28953. /**
  28954. * Will flag all materials as dirty to trigger new shader compilation
  28955. * @param flag defines the flag used to specify which material part must be marked as dirty
  28956. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28957. */
  28958. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28959. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28960. var material = _a[_i];
  28961. if (predicate && !predicate(material)) {
  28962. continue;
  28963. }
  28964. material.markAsDirty(flag);
  28965. }
  28966. };
  28967. /** @hidden */
  28968. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28969. var _this = this;
  28970. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28971. this._activeRequests.push(request);
  28972. request.onCompleteObservable.add(function (request) {
  28973. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28974. });
  28975. return request;
  28976. };
  28977. /** @hidden */
  28978. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28979. var _this = this;
  28980. return new Promise(function (resolve, reject) {
  28981. _this._loadFile(url, function (data) {
  28982. resolve(data);
  28983. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28984. reject(exception);
  28985. });
  28986. });
  28987. };
  28988. // Statics
  28989. Scene._FOGMODE_NONE = 0;
  28990. Scene._FOGMODE_EXP = 1;
  28991. Scene._FOGMODE_EXP2 = 2;
  28992. Scene._FOGMODE_LINEAR = 3;
  28993. Scene._uniqueIdCounter = 0;
  28994. /**
  28995. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28996. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28997. */
  28998. Scene.MinDeltaTime = 1.0;
  28999. /**
  29000. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29001. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29002. */
  29003. Scene.MaxDeltaTime = 1000.0;
  29004. /** The distance in pixel that you have to move to prevent some events */
  29005. Scene.DragMovementThreshold = 10; // in pixels
  29006. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29007. Scene.LongPressDelay = 500; // in milliseconds
  29008. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29009. Scene.DoubleClickDelay = 300; // in milliseconds
  29010. /** If you need to check double click without raising a single click at first click, enable this flag */
  29011. Scene.ExclusiveDoubleClickMode = false;
  29012. return Scene;
  29013. }());
  29014. BABYLON.Scene = Scene;
  29015. })(BABYLON || (BABYLON = {}));
  29016. //# sourceMappingURL=babylon.scene.js.map
  29017. var BABYLON;
  29018. (function (BABYLON) {
  29019. /**
  29020. * Set of assets to keep when moving a scene into an asset container.
  29021. */
  29022. var KeepAssets = /** @class */ (function () {
  29023. function KeepAssets() {
  29024. /**
  29025. * Cameras to keep.
  29026. */
  29027. this.cameras = new Array();
  29028. /**
  29029. * Lights to keep.
  29030. */
  29031. this.lights = new Array();
  29032. /**
  29033. * Meshes to keep.
  29034. */
  29035. this.meshes = new Array();
  29036. /**
  29037. * Skeletons to keep.
  29038. */
  29039. this.skeletons = new Array();
  29040. /**
  29041. * ParticleSystems to keep.
  29042. */
  29043. this.particleSystems = new Array();
  29044. /**
  29045. * Animations to keep.
  29046. */
  29047. this.animations = new Array();
  29048. /**
  29049. * AnimationGroups to keep.
  29050. */
  29051. this.animationGroups = new Array();
  29052. /**
  29053. * MultiMaterials to keep.
  29054. */
  29055. this.multiMaterials = new Array();
  29056. /**
  29057. * Materials to keep.
  29058. */
  29059. this.materials = new Array();
  29060. /**
  29061. * MorphTargetManagers to keep.
  29062. */
  29063. this.morphTargetManagers = new Array();
  29064. /**
  29065. * Geometries to keep.
  29066. */
  29067. this.geometries = new Array();
  29068. /**
  29069. * TransformNodes to keep.
  29070. */
  29071. this.transformNodes = new Array();
  29072. /**
  29073. * LensFlareSystems to keep.
  29074. */
  29075. this.lensFlareSystems = new Array();
  29076. /**
  29077. * ShadowGenerators to keep.
  29078. */
  29079. this.shadowGenerators = new Array();
  29080. /**
  29081. * ActionManagers to keep.
  29082. */
  29083. this.actionManagers = new Array();
  29084. /**
  29085. * Sounds to keep.
  29086. */
  29087. this.sounds = new Array();
  29088. /**
  29089. * Textures to keep.
  29090. */
  29091. this.textures = new Array();
  29092. /**
  29093. * Effect layers to keep.
  29094. */
  29095. this.effectLayers = new Array();
  29096. }
  29097. return KeepAssets;
  29098. }());
  29099. BABYLON.KeepAssets = KeepAssets;
  29100. /**
  29101. * Container with a set of assets that can be added or removed from a scene.
  29102. */
  29103. var AssetContainer = /** @class */ (function () {
  29104. /**
  29105. * Instantiates an AssetContainer.
  29106. * @param scene The scene the AssetContainer belongs to.
  29107. */
  29108. function AssetContainer(scene) {
  29109. // Objects
  29110. /**
  29111. * Cameras populated in the container.
  29112. */
  29113. this.cameras = new Array();
  29114. /**
  29115. * Lights populated in the container.
  29116. */
  29117. this.lights = new Array();
  29118. /**
  29119. * Meshes populated in the container.
  29120. */
  29121. this.meshes = new Array();
  29122. /**
  29123. * Skeletons populated in the container.
  29124. */
  29125. this.skeletons = new Array();
  29126. /**
  29127. * ParticleSystems populated in the container.
  29128. */
  29129. this.particleSystems = new Array();
  29130. /**
  29131. * Animations populated in the container.
  29132. */
  29133. this.animations = new Array();
  29134. /**
  29135. * AnimationGroups populated in the container.
  29136. */
  29137. this.animationGroups = new Array();
  29138. /**
  29139. * MultiMaterials populated in the container.
  29140. */
  29141. this.multiMaterials = new Array();
  29142. /**
  29143. * Materials populated in the container.
  29144. */
  29145. this.materials = new Array();
  29146. /**
  29147. * MorphTargetManagers populated in the container.
  29148. */
  29149. this.morphTargetManagers = new Array();
  29150. /**
  29151. * Geometries populated in the container.
  29152. */
  29153. this.geometries = new Array();
  29154. /**
  29155. * TransformNodes populated in the container.
  29156. */
  29157. this.transformNodes = new Array();
  29158. /**
  29159. * LensFlareSystems populated in the container.
  29160. */
  29161. this.lensFlareSystems = new Array();
  29162. /**
  29163. * ShadowGenerators populated in the container.
  29164. */
  29165. this.shadowGenerators = new Array();
  29166. /**
  29167. * ActionManagers populated in the container.
  29168. */
  29169. this.actionManagers = new Array();
  29170. /**
  29171. * Sounds populated in the container.
  29172. */
  29173. this.sounds = new Array();
  29174. /**
  29175. * Textures populated in the container.
  29176. */
  29177. this.textures = new Array();
  29178. /**
  29179. * Effect layers populated in the container.
  29180. */
  29181. this.effectLayers = new Array();
  29182. this.scene = scene;
  29183. }
  29184. /**
  29185. * Adds all the assets from the container to the scene.
  29186. */
  29187. AssetContainer.prototype.addAllToScene = function () {
  29188. var _this = this;
  29189. this.cameras.forEach(function (o) {
  29190. _this.scene.addCamera(o);
  29191. });
  29192. this.lights.forEach(function (o) {
  29193. _this.scene.addLight(o);
  29194. });
  29195. this.meshes.forEach(function (o) {
  29196. _this.scene.addMesh(o);
  29197. });
  29198. this.skeletons.forEach(function (o) {
  29199. _this.scene.addSkeleton(o);
  29200. });
  29201. this.particleSystems.forEach(function (o) {
  29202. _this.scene.addParticleSystem(o);
  29203. });
  29204. this.animations.forEach(function (o) {
  29205. _this.scene.addAnimation(o);
  29206. });
  29207. this.animationGroups.forEach(function (o) {
  29208. _this.scene.addAnimationGroup(o);
  29209. });
  29210. this.multiMaterials.forEach(function (o) {
  29211. _this.scene.addMultiMaterial(o);
  29212. });
  29213. this.materials.forEach(function (o) {
  29214. _this.scene.addMaterial(o);
  29215. });
  29216. this.morphTargetManagers.forEach(function (o) {
  29217. _this.scene.addMorphTargetManager(o);
  29218. });
  29219. this.geometries.forEach(function (o) {
  29220. _this.scene.addGeometry(o);
  29221. });
  29222. this.transformNodes.forEach(function (o) {
  29223. _this.scene.addTransformNode(o);
  29224. });
  29225. this.lensFlareSystems.forEach(function (o) {
  29226. _this.scene.addLensFlareSystem(o);
  29227. });
  29228. this.actionManagers.forEach(function (o) {
  29229. _this.scene.addActionManager(o);
  29230. });
  29231. this.sounds.forEach(function (o) {
  29232. o.play();
  29233. o.autoplay = true;
  29234. _this.scene.mainSoundTrack.AddSound(o);
  29235. });
  29236. this.textures.forEach(function (o) {
  29237. _this.scene.addTexture(o);
  29238. });
  29239. this.effectLayers.forEach(function (o) {
  29240. _this.scene.addEffectLayer(o);
  29241. });
  29242. };
  29243. /**
  29244. * Removes all the assets in the container from the scene
  29245. */
  29246. AssetContainer.prototype.removeAllFromScene = function () {
  29247. var _this = this;
  29248. this.cameras.forEach(function (o) {
  29249. _this.scene.removeCamera(o);
  29250. });
  29251. this.lights.forEach(function (o) {
  29252. _this.scene.removeLight(o);
  29253. });
  29254. this.meshes.forEach(function (o) {
  29255. _this.scene.removeMesh(o);
  29256. });
  29257. this.skeletons.forEach(function (o) {
  29258. _this.scene.removeSkeleton(o);
  29259. });
  29260. this.particleSystems.forEach(function (o) {
  29261. _this.scene.removeParticleSystem(o);
  29262. });
  29263. this.animations.forEach(function (o) {
  29264. _this.scene.removeAnimation(o);
  29265. });
  29266. this.animationGroups.forEach(function (o) {
  29267. _this.scene.removeAnimationGroup(o);
  29268. });
  29269. this.multiMaterials.forEach(function (o) {
  29270. _this.scene.removeMultiMaterial(o);
  29271. });
  29272. this.materials.forEach(function (o) {
  29273. _this.scene.removeMaterial(o);
  29274. });
  29275. this.morphTargetManagers.forEach(function (o) {
  29276. _this.scene.removeMorphTargetManager(o);
  29277. });
  29278. this.geometries.forEach(function (o) {
  29279. _this.scene.removeGeometry(o);
  29280. });
  29281. this.transformNodes.forEach(function (o) {
  29282. _this.scene.removeTransformNode(o);
  29283. });
  29284. this.lensFlareSystems.forEach(function (o) {
  29285. _this.scene.removeLensFlareSystem(o);
  29286. });
  29287. this.actionManagers.forEach(function (o) {
  29288. _this.scene.removeActionManager(o);
  29289. });
  29290. this.sounds.forEach(function (o) {
  29291. o.stop();
  29292. o.autoplay = false;
  29293. _this.scene.mainSoundTrack.RemoveSound(o);
  29294. });
  29295. this.textures.forEach(function (o) {
  29296. _this.scene.removeTexture(o);
  29297. });
  29298. this.effectLayers.forEach(function (o) {
  29299. _this.scene.removeEffectLayer(o);
  29300. });
  29301. };
  29302. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29303. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29304. var asset = sourceAssets_1[_i];
  29305. var move = true;
  29306. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29307. var keepAsset = keepAssets_1[_a];
  29308. if (asset === keepAsset) {
  29309. move = false;
  29310. break;
  29311. }
  29312. }
  29313. if (move) {
  29314. targetAssets.push(asset);
  29315. }
  29316. }
  29317. };
  29318. /**
  29319. * Removes all the assets contained in the scene and adds them to the container.
  29320. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29321. */
  29322. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29323. if (keepAssets === undefined) {
  29324. keepAssets = new KeepAssets();
  29325. }
  29326. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29327. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29328. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29329. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29330. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29331. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29332. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29333. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29334. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29335. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29336. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29337. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29338. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29339. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29340. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29341. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29342. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29343. this.removeAllFromScene();
  29344. };
  29345. /**
  29346. * 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.
  29347. * @returns the root mesh
  29348. */
  29349. AssetContainer.prototype.createRootMesh = function () {
  29350. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29351. this.meshes.forEach(function (m) {
  29352. if (!m.parent) {
  29353. rootMesh.addChild(m);
  29354. }
  29355. });
  29356. this.meshes.unshift(rootMesh);
  29357. return rootMesh;
  29358. };
  29359. return AssetContainer;
  29360. }());
  29361. BABYLON.AssetContainer = AssetContainer;
  29362. })(BABYLON || (BABYLON = {}));
  29363. //# sourceMappingURL=babylon.assetContainer.js.map
  29364. var BABYLON;
  29365. (function (BABYLON) {
  29366. var Buffer = /** @class */ (function () {
  29367. /**
  29368. * Constructor
  29369. * @param engine the engine
  29370. * @param data the data to use for this buffer
  29371. * @param updatable whether the data is updatable
  29372. * @param stride the stride (optional)
  29373. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29374. * @param instanced whether the buffer is instanced (optional)
  29375. * @param useBytes set to true if the stride in in bytes (optional)
  29376. */
  29377. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29378. if (stride === void 0) { stride = 0; }
  29379. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29380. if (instanced === void 0) { instanced = false; }
  29381. if (useBytes === void 0) { useBytes = false; }
  29382. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29383. this._engine = engine.getScene().getEngine();
  29384. }
  29385. else {
  29386. this._engine = engine;
  29387. }
  29388. this._updatable = updatable;
  29389. this._instanced = instanced;
  29390. this._data = data;
  29391. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29392. if (!postponeInternalCreation) { // by default
  29393. this.create();
  29394. }
  29395. }
  29396. /**
  29397. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29398. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29399. * @param offset defines offset in the buffer (0 by default)
  29400. * @param size defines the size in floats of attributes (position is 3 for instance)
  29401. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29402. * @param instanced defines if the vertex buffer contains indexed data
  29403. * @param useBytes defines if the offset and stride are in bytes
  29404. * @returns the new vertex buffer
  29405. */
  29406. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29407. if (useBytes === void 0) { useBytes = false; }
  29408. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29409. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29410. // a lot of these parameters are ignored as they are overriden by the buffer
  29411. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29412. };
  29413. // Properties
  29414. Buffer.prototype.isUpdatable = function () {
  29415. return this._updatable;
  29416. };
  29417. Buffer.prototype.getData = function () {
  29418. return this._data;
  29419. };
  29420. Buffer.prototype.getBuffer = function () {
  29421. return this._buffer;
  29422. };
  29423. /**
  29424. * Gets the stride in float32 units (i.e. byte stride / 4).
  29425. * May not be an integer if the byte stride is not divisible by 4.
  29426. * DEPRECATED. Use byteStride instead.
  29427. * @returns the stride in float32 units
  29428. */
  29429. Buffer.prototype.getStrideSize = function () {
  29430. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29431. };
  29432. // Methods
  29433. Buffer.prototype.create = function (data) {
  29434. if (data === void 0) { data = null; }
  29435. if (!data && this._buffer) {
  29436. return; // nothing to do
  29437. }
  29438. data = data || this._data;
  29439. if (!data) {
  29440. return;
  29441. }
  29442. if (!this._buffer) { // create buffer
  29443. if (this._updatable) {
  29444. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29445. this._data = data;
  29446. }
  29447. else {
  29448. this._buffer = this._engine.createVertexBuffer(data);
  29449. }
  29450. }
  29451. else if (this._updatable) { // update buffer
  29452. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29453. this._data = data;
  29454. }
  29455. };
  29456. Buffer.prototype._rebuild = function () {
  29457. this._buffer = null;
  29458. this.create(this._data);
  29459. };
  29460. Buffer.prototype.update = function (data) {
  29461. this.create(data);
  29462. };
  29463. /**
  29464. * Updates the data directly.
  29465. * @param data the new data
  29466. * @param offset the new offset
  29467. * @param vertexCount the vertex count (optional)
  29468. * @param useBytes set to true if the offset is in bytes
  29469. */
  29470. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29471. if (useBytes === void 0) { useBytes = false; }
  29472. if (!this._buffer) {
  29473. return;
  29474. }
  29475. if (this._updatable) { // update buffer
  29476. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29477. this._data = null;
  29478. }
  29479. };
  29480. Buffer.prototype.dispose = function () {
  29481. if (!this._buffer) {
  29482. return;
  29483. }
  29484. if (this._engine._releaseBuffer(this._buffer)) {
  29485. this._buffer = null;
  29486. }
  29487. };
  29488. return Buffer;
  29489. }());
  29490. BABYLON.Buffer = Buffer;
  29491. })(BABYLON || (BABYLON = {}));
  29492. //# sourceMappingURL=babylon.buffer.js.map
  29493. var BABYLON;
  29494. (function (BABYLON) {
  29495. var VertexBuffer = /** @class */ (function () {
  29496. /**
  29497. * Constructor
  29498. * @param engine the engine
  29499. * @param data the data to use for this vertex buffer
  29500. * @param kind the vertex buffer kind
  29501. * @param updatable whether the data is updatable
  29502. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29503. * @param stride the stride (optional)
  29504. * @param instanced whether the buffer is instanced (optional)
  29505. * @param offset the offset of the data (optional)
  29506. * @param size the number of components (optional)
  29507. * @param type the type of the component (optional)
  29508. * @param normalized whether the data contains normalized data (optional)
  29509. * @param useBytes set to true if stride and offset are in bytes (optional)
  29510. */
  29511. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29512. if (normalized === void 0) { normalized = false; }
  29513. if (useBytes === void 0) { useBytes = false; }
  29514. if (data instanceof BABYLON.Buffer) {
  29515. this._buffer = data;
  29516. this._ownsBuffer = false;
  29517. }
  29518. else {
  29519. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29520. this._ownsBuffer = true;
  29521. }
  29522. this._kind = kind;
  29523. if (type == undefined) {
  29524. var data_1 = this.getData();
  29525. this.type = VertexBuffer.FLOAT;
  29526. if (data_1 instanceof Int8Array)
  29527. this.type = VertexBuffer.BYTE;
  29528. else if (data_1 instanceof Uint8Array)
  29529. this.type = VertexBuffer.UNSIGNED_BYTE;
  29530. else if (data_1 instanceof Int16Array)
  29531. this.type = VertexBuffer.SHORT;
  29532. else if (data_1 instanceof Uint16Array)
  29533. this.type = VertexBuffer.UNSIGNED_SHORT;
  29534. else if (data_1 instanceof Int32Array)
  29535. this.type = VertexBuffer.INT;
  29536. else if (data_1 instanceof Uint32Array)
  29537. this.type = VertexBuffer.UNSIGNED_INT;
  29538. }
  29539. else {
  29540. this.type = type;
  29541. }
  29542. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29543. if (useBytes) {
  29544. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29545. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29546. this.byteOffset = offset || 0;
  29547. }
  29548. else {
  29549. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29550. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29551. this.byteOffset = (offset || 0) * typeByteLength;
  29552. }
  29553. this.normalized = normalized;
  29554. this._instanced = instanced !== undefined ? instanced : false;
  29555. this._instanceDivisor = instanced ? 1 : 0;
  29556. }
  29557. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29558. /**
  29559. * Gets or sets the instance divisor when in instanced mode
  29560. */
  29561. get: function () {
  29562. return this._instanceDivisor;
  29563. },
  29564. set: function (value) {
  29565. this._instanceDivisor = value;
  29566. if (value == 0) {
  29567. this._instanced = false;
  29568. }
  29569. else {
  29570. this._instanced = true;
  29571. }
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. VertexBuffer.prototype._rebuild = function () {
  29577. if (!this._buffer) {
  29578. return;
  29579. }
  29580. this._buffer._rebuild();
  29581. };
  29582. /**
  29583. * Returns the kind of the VertexBuffer (string).
  29584. */
  29585. VertexBuffer.prototype.getKind = function () {
  29586. return this._kind;
  29587. };
  29588. // Properties
  29589. /**
  29590. * Boolean : is the VertexBuffer updatable ?
  29591. */
  29592. VertexBuffer.prototype.isUpdatable = function () {
  29593. return this._buffer.isUpdatable();
  29594. };
  29595. /**
  29596. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29597. */
  29598. VertexBuffer.prototype.getData = function () {
  29599. return this._buffer.getData();
  29600. };
  29601. /**
  29602. * Returns the WebGLBuffer associated to the VertexBuffer.
  29603. */
  29604. VertexBuffer.prototype.getBuffer = function () {
  29605. return this._buffer.getBuffer();
  29606. };
  29607. /**
  29608. * Returns the stride as a multiple of the type byte length.
  29609. * DEPRECATED. Use byteStride instead.
  29610. */
  29611. VertexBuffer.prototype.getStrideSize = function () {
  29612. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29613. };
  29614. /**
  29615. * Returns the offset as a multiple of the type byte length.
  29616. * DEPRECATED. Use byteOffset instead.
  29617. */
  29618. VertexBuffer.prototype.getOffset = function () {
  29619. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29620. };
  29621. /**
  29622. * Returns the number of components per vertex attribute (integer).
  29623. */
  29624. VertexBuffer.prototype.getSize = function () {
  29625. return this._size;
  29626. };
  29627. /**
  29628. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29629. */
  29630. VertexBuffer.prototype.getIsInstanced = function () {
  29631. return this._instanced;
  29632. };
  29633. /**
  29634. * Returns the instancing divisor, zero for non-instanced (integer).
  29635. */
  29636. VertexBuffer.prototype.getInstanceDivisor = function () {
  29637. return this._instanceDivisor;
  29638. };
  29639. // Methods
  29640. /**
  29641. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29642. * Returns the created WebGLBuffer.
  29643. */
  29644. VertexBuffer.prototype.create = function (data) {
  29645. return this._buffer.create(data);
  29646. };
  29647. /**
  29648. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29649. * This function will create a new buffer if the current one is not updatable
  29650. * Returns the updated WebGLBuffer.
  29651. */
  29652. VertexBuffer.prototype.update = function (data) {
  29653. return this._buffer.update(data);
  29654. };
  29655. /**
  29656. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29657. * Returns the directly updated WebGLBuffer.
  29658. * @param data the new data
  29659. * @param offset the new offset
  29660. * @param useBytes set to true if the offset is in bytes
  29661. */
  29662. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29663. if (useBytes === void 0) { useBytes = false; }
  29664. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29665. };
  29666. /**
  29667. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29668. */
  29669. VertexBuffer.prototype.dispose = function () {
  29670. if (this._ownsBuffer) {
  29671. this._buffer.dispose();
  29672. }
  29673. };
  29674. /**
  29675. * Enumerates each value of this vertex buffer as numbers.
  29676. * @param count the number of values to enumerate
  29677. * @param callback the callback function called for each value
  29678. */
  29679. VertexBuffer.prototype.forEach = function (count, callback) {
  29680. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29681. };
  29682. Object.defineProperty(VertexBuffer, "PositionKind", {
  29683. get: function () {
  29684. return VertexBuffer._PositionKind;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. Object.defineProperty(VertexBuffer, "NormalKind", {
  29690. get: function () {
  29691. return VertexBuffer._NormalKind;
  29692. },
  29693. enumerable: true,
  29694. configurable: true
  29695. });
  29696. Object.defineProperty(VertexBuffer, "TangentKind", {
  29697. get: function () {
  29698. return VertexBuffer._TangentKind;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. Object.defineProperty(VertexBuffer, "UVKind", {
  29704. get: function () {
  29705. return VertexBuffer._UVKind;
  29706. },
  29707. enumerable: true,
  29708. configurable: true
  29709. });
  29710. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29711. get: function () {
  29712. return VertexBuffer._UV2Kind;
  29713. },
  29714. enumerable: true,
  29715. configurable: true
  29716. });
  29717. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29718. get: function () {
  29719. return VertexBuffer._UV3Kind;
  29720. },
  29721. enumerable: true,
  29722. configurable: true
  29723. });
  29724. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29725. get: function () {
  29726. return VertexBuffer._UV4Kind;
  29727. },
  29728. enumerable: true,
  29729. configurable: true
  29730. });
  29731. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29732. get: function () {
  29733. return VertexBuffer._UV5Kind;
  29734. },
  29735. enumerable: true,
  29736. configurable: true
  29737. });
  29738. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29739. get: function () {
  29740. return VertexBuffer._UV6Kind;
  29741. },
  29742. enumerable: true,
  29743. configurable: true
  29744. });
  29745. Object.defineProperty(VertexBuffer, "ColorKind", {
  29746. get: function () {
  29747. return VertexBuffer._ColorKind;
  29748. },
  29749. enumerable: true,
  29750. configurable: true
  29751. });
  29752. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29753. get: function () {
  29754. return VertexBuffer._MatricesIndicesKind;
  29755. },
  29756. enumerable: true,
  29757. configurable: true
  29758. });
  29759. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29760. get: function () {
  29761. return VertexBuffer._MatricesWeightsKind;
  29762. },
  29763. enumerable: true,
  29764. configurable: true
  29765. });
  29766. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29767. get: function () {
  29768. return VertexBuffer._MatricesIndicesExtraKind;
  29769. },
  29770. enumerable: true,
  29771. configurable: true
  29772. });
  29773. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29774. get: function () {
  29775. return VertexBuffer._MatricesWeightsExtraKind;
  29776. },
  29777. enumerable: true,
  29778. configurable: true
  29779. });
  29780. /**
  29781. * Deduces the stride given a kind.
  29782. * @param kind The kind string to deduce
  29783. * @returns The deduced stride
  29784. */
  29785. VertexBuffer.DeduceStride = function (kind) {
  29786. switch (kind) {
  29787. case VertexBuffer.UVKind:
  29788. case VertexBuffer.UV2Kind:
  29789. case VertexBuffer.UV3Kind:
  29790. case VertexBuffer.UV4Kind:
  29791. case VertexBuffer.UV5Kind:
  29792. case VertexBuffer.UV6Kind:
  29793. return 2;
  29794. case VertexBuffer.NormalKind:
  29795. case VertexBuffer.PositionKind:
  29796. return 3;
  29797. case VertexBuffer.ColorKind:
  29798. case VertexBuffer.MatricesIndicesKind:
  29799. case VertexBuffer.MatricesIndicesExtraKind:
  29800. case VertexBuffer.MatricesWeightsKind:
  29801. case VertexBuffer.MatricesWeightsExtraKind:
  29802. case VertexBuffer.TangentKind:
  29803. return 4;
  29804. default:
  29805. throw new Error("Invalid kind '" + kind + "'");
  29806. }
  29807. };
  29808. /**
  29809. * Gets the byte length of the given type.
  29810. * @param type the type
  29811. * @returns the number of bytes
  29812. */
  29813. VertexBuffer.GetTypeByteLength = function (type) {
  29814. switch (type) {
  29815. case VertexBuffer.BYTE:
  29816. case VertexBuffer.UNSIGNED_BYTE:
  29817. return 1;
  29818. case VertexBuffer.SHORT:
  29819. case VertexBuffer.UNSIGNED_SHORT:
  29820. return 2;
  29821. case VertexBuffer.INT:
  29822. case VertexBuffer.FLOAT:
  29823. return 4;
  29824. default:
  29825. throw new Error("Invalid type '" + type + "'");
  29826. }
  29827. };
  29828. /**
  29829. * Enumerates each value of the given parameters as numbers.
  29830. * @param data the data to enumerate
  29831. * @param byteOffset the byte offset of the data
  29832. * @param byteStride the byte stride of the data
  29833. * @param componentCount the number of components per element
  29834. * @param componentType the type of the component
  29835. * @param count the total number of components
  29836. * @param normalized whether the data is normalized
  29837. * @param callback the callback function called for each value
  29838. */
  29839. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29840. if (data instanceof Array) {
  29841. var offset = byteOffset / 4;
  29842. var stride = byteStride / 4;
  29843. for (var index = 0; index < count; index += componentCount) {
  29844. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29845. callback(data[offset + componentIndex], index + componentIndex);
  29846. }
  29847. offset += stride;
  29848. }
  29849. }
  29850. else {
  29851. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29852. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29853. for (var index = 0; index < count; index += componentCount) {
  29854. var componentByteOffset = byteOffset;
  29855. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29856. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29857. callback(value, index + componentIndex);
  29858. componentByteOffset += componentByteLength;
  29859. }
  29860. byteOffset += byteStride;
  29861. }
  29862. }
  29863. };
  29864. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29865. switch (type) {
  29866. case VertexBuffer.BYTE: {
  29867. var value = dataView.getInt8(byteOffset);
  29868. if (normalized) {
  29869. value = Math.max(value / 127, -1);
  29870. }
  29871. return value;
  29872. }
  29873. case VertexBuffer.UNSIGNED_BYTE: {
  29874. var value = dataView.getUint8(byteOffset);
  29875. if (normalized) {
  29876. value = value / 255;
  29877. }
  29878. return value;
  29879. }
  29880. case VertexBuffer.SHORT: {
  29881. var value = dataView.getInt16(byteOffset, true);
  29882. if (normalized) {
  29883. value = Math.max(value / 16383, -1);
  29884. }
  29885. return value;
  29886. }
  29887. case VertexBuffer.UNSIGNED_SHORT: {
  29888. var value = dataView.getUint16(byteOffset, true);
  29889. if (normalized) {
  29890. value = value / 65535;
  29891. }
  29892. return value;
  29893. }
  29894. case VertexBuffer.FLOAT: {
  29895. return dataView.getFloat32(byteOffset, true);
  29896. }
  29897. default: {
  29898. throw new Error("Invalid component type " + type);
  29899. }
  29900. }
  29901. };
  29902. /**
  29903. * The byte type.
  29904. */
  29905. VertexBuffer.BYTE = 5120;
  29906. /**
  29907. * The unsigned byte type.
  29908. */
  29909. VertexBuffer.UNSIGNED_BYTE = 5121;
  29910. /**
  29911. * The short type.
  29912. */
  29913. VertexBuffer.SHORT = 5122;
  29914. /**
  29915. * The unsigned short type.
  29916. */
  29917. VertexBuffer.UNSIGNED_SHORT = 5123;
  29918. /**
  29919. * The integer type.
  29920. */
  29921. VertexBuffer.INT = 5124;
  29922. /**
  29923. * The unsigned integer type.
  29924. */
  29925. VertexBuffer.UNSIGNED_INT = 5125;
  29926. /**
  29927. * The float type.
  29928. */
  29929. VertexBuffer.FLOAT = 5126;
  29930. // Enums
  29931. VertexBuffer._PositionKind = "position";
  29932. VertexBuffer._NormalKind = "normal";
  29933. VertexBuffer._TangentKind = "tangent";
  29934. VertexBuffer._UVKind = "uv";
  29935. VertexBuffer._UV2Kind = "uv2";
  29936. VertexBuffer._UV3Kind = "uv3";
  29937. VertexBuffer._UV4Kind = "uv4";
  29938. VertexBuffer._UV5Kind = "uv5";
  29939. VertexBuffer._UV6Kind = "uv6";
  29940. VertexBuffer._ColorKind = "color";
  29941. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29942. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29943. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29944. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29945. return VertexBuffer;
  29946. }());
  29947. BABYLON.VertexBuffer = VertexBuffer;
  29948. })(BABYLON || (BABYLON = {}));
  29949. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29950. var BABYLON;
  29951. (function (BABYLON) {
  29952. /**
  29953. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29954. */
  29955. var DummyInternalTextureTracker = /** @class */ (function () {
  29956. function DummyInternalTextureTracker() {
  29957. /**
  29958. * Gets or set the previous tracker in the list
  29959. */
  29960. this.previous = null;
  29961. /**
  29962. * Gets or set the next tracker in the list
  29963. */
  29964. this.next = null;
  29965. }
  29966. return DummyInternalTextureTracker;
  29967. }());
  29968. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29969. })(BABYLON || (BABYLON = {}));
  29970. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29971. var BABYLON;
  29972. (function (BABYLON) {
  29973. /**
  29974. * Class used to store data associated with WebGL texture data for the engine
  29975. * This class should not be used directly
  29976. */
  29977. var InternalTexture = /** @class */ (function () {
  29978. /**
  29979. * Creates a new InternalTexture
  29980. * @param engine defines the engine to use
  29981. * @param dataSource defines the type of data that will be used
  29982. */
  29983. function InternalTexture(engine, dataSource) {
  29984. /**
  29985. * Observable called when the texture is loaded
  29986. */
  29987. this.onLoadedObservable = new BABYLON.Observable();
  29988. /**
  29989. * Gets or set the previous tracker in the list
  29990. */
  29991. this.previous = null;
  29992. /**
  29993. * Gets or set the next tracker in the list
  29994. */
  29995. this.next = null;
  29996. // Private
  29997. /** @hidden */
  29998. this._initialSlot = -1;
  29999. /** @hidden */
  30000. this._designatedSlot = -1;
  30001. /** @hidden */
  30002. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30003. /** @hidden */
  30004. this._comparisonFunction = 0;
  30005. /** @hidden */
  30006. this._references = 1;
  30007. this._engine = engine;
  30008. this._dataSource = dataSource;
  30009. this._webGLTexture = engine._createTexture();
  30010. }
  30011. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30012. /**
  30013. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30014. */
  30015. get: function () {
  30016. return this._dataSource;
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. /**
  30022. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30023. */
  30024. InternalTexture.prototype.incrementReferences = function () {
  30025. this._references++;
  30026. };
  30027. /**
  30028. * Change the size of the texture (not the size of the content)
  30029. * @param width defines the new width
  30030. * @param height defines the new height
  30031. * @param depth defines the new depth (1 by default)
  30032. */
  30033. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30034. if (depth === void 0) { depth = 1; }
  30035. this.width = width;
  30036. this.height = height;
  30037. this.depth = depth;
  30038. this.baseWidth = width;
  30039. this.baseHeight = height;
  30040. this.baseDepth = depth;
  30041. this._size = width * height * depth;
  30042. };
  30043. /** @hidden */
  30044. InternalTexture.prototype._rebuild = function () {
  30045. var _this = this;
  30046. var proxy;
  30047. this.isReady = false;
  30048. this._cachedCoordinatesMode = null;
  30049. this._cachedWrapU = null;
  30050. this._cachedWrapV = null;
  30051. this._cachedAnisotropicFilteringLevel = null;
  30052. switch (this._dataSource) {
  30053. case InternalTexture.DATASOURCE_TEMP:
  30054. return;
  30055. case InternalTexture.DATASOURCE_URL:
  30056. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30057. _this.isReady = true;
  30058. }, null, this._buffer, undefined, this.format);
  30059. proxy._swapAndDie(this);
  30060. return;
  30061. case InternalTexture.DATASOURCE_RAW:
  30062. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30063. proxy._swapAndDie(this);
  30064. this.isReady = true;
  30065. return;
  30066. case InternalTexture.DATASOURCE_RAW3D:
  30067. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30068. proxy._swapAndDie(this);
  30069. this.isReady = true;
  30070. return;
  30071. case InternalTexture.DATASOURCE_DYNAMIC:
  30072. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30073. proxy._swapAndDie(this);
  30074. // The engine will make sure to update content so no need to flag it as isReady = true
  30075. return;
  30076. case InternalTexture.DATASOURCE_RENDERTARGET:
  30077. var options = new BABYLON.RenderTargetCreationOptions();
  30078. options.generateDepthBuffer = this._generateDepthBuffer;
  30079. options.generateMipMaps = this.generateMipMaps;
  30080. options.generateStencilBuffer = this._generateStencilBuffer;
  30081. options.samplingMode = this.samplingMode;
  30082. options.type = this.type;
  30083. if (this.isCube) {
  30084. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30085. }
  30086. else {
  30087. var size = {
  30088. width: this.width,
  30089. height: this.height
  30090. };
  30091. proxy = this._engine.createRenderTargetTexture(size, options);
  30092. }
  30093. proxy._swapAndDie(this);
  30094. this.isReady = true;
  30095. return;
  30096. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30097. var depthTextureOptions = {
  30098. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30099. comparisonFunction: this._comparisonFunction,
  30100. generateStencil: this._generateStencilBuffer,
  30101. isCube: this.isCube
  30102. };
  30103. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30104. proxy._swapAndDie(this);
  30105. this.isReady = true;
  30106. return;
  30107. case InternalTexture.DATASOURCE_CUBE:
  30108. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30109. _this.isReady = true;
  30110. }, null, this.format, this._extension);
  30111. proxy._swapAndDie(this);
  30112. return;
  30113. case InternalTexture.DATASOURCE_CUBERAW:
  30114. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30115. proxy._swapAndDie(this);
  30116. this.isReady = true;
  30117. return;
  30118. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30119. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30120. if (proxy) {
  30121. proxy._swapAndDie(_this);
  30122. }
  30123. _this.isReady = true;
  30124. }, null, this.format, this._extension);
  30125. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30126. return;
  30127. }
  30128. };
  30129. InternalTexture.prototype._swapAndDie = function (target) {
  30130. target._webGLTexture = this._webGLTexture;
  30131. if (this._framebuffer) {
  30132. target._framebuffer = this._framebuffer;
  30133. }
  30134. if (this._depthStencilBuffer) {
  30135. target._depthStencilBuffer = this._depthStencilBuffer;
  30136. }
  30137. if (this._lodTextureHigh) {
  30138. if (target._lodTextureHigh) {
  30139. target._lodTextureHigh.dispose();
  30140. }
  30141. target._lodTextureHigh = this._lodTextureHigh;
  30142. }
  30143. if (this._lodTextureMid) {
  30144. if (target._lodTextureMid) {
  30145. target._lodTextureMid.dispose();
  30146. }
  30147. target._lodTextureMid = this._lodTextureMid;
  30148. }
  30149. if (this._lodTextureLow) {
  30150. if (target._lodTextureLow) {
  30151. target._lodTextureLow.dispose();
  30152. }
  30153. target._lodTextureLow = this._lodTextureLow;
  30154. }
  30155. var cache = this._engine.getLoadedTexturesCache();
  30156. var index = cache.indexOf(this);
  30157. if (index !== -1) {
  30158. cache.splice(index, 1);
  30159. }
  30160. };
  30161. /**
  30162. * Dispose the current allocated resources
  30163. */
  30164. InternalTexture.prototype.dispose = function () {
  30165. if (!this._webGLTexture) {
  30166. return;
  30167. }
  30168. this._references--;
  30169. if (this._references === 0) {
  30170. this._engine._releaseTexture(this);
  30171. this._webGLTexture = null;
  30172. this.previous = null;
  30173. this.next = null;
  30174. }
  30175. };
  30176. /**
  30177. * The source of the texture data is unknown
  30178. */
  30179. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30180. /**
  30181. * Texture data comes from an URL
  30182. */
  30183. InternalTexture.DATASOURCE_URL = 1;
  30184. /**
  30185. * Texture data is only used for temporary storage
  30186. */
  30187. InternalTexture.DATASOURCE_TEMP = 2;
  30188. /**
  30189. * Texture data comes from raw data (ArrayBuffer)
  30190. */
  30191. InternalTexture.DATASOURCE_RAW = 3;
  30192. /**
  30193. * Texture content is dynamic (video or dynamic texture)
  30194. */
  30195. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30196. /**
  30197. * Texture content is generated by rendering to it
  30198. */
  30199. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30200. /**
  30201. * Texture content is part of a multi render target process
  30202. */
  30203. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30204. /**
  30205. * Texture data comes from a cube data file
  30206. */
  30207. InternalTexture.DATASOURCE_CUBE = 7;
  30208. /**
  30209. * Texture data comes from a raw cube data
  30210. */
  30211. InternalTexture.DATASOURCE_CUBERAW = 8;
  30212. /**
  30213. * Texture data come from a prefiltered cube data file
  30214. */
  30215. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30216. /**
  30217. * Texture content is raw 3D data
  30218. */
  30219. InternalTexture.DATASOURCE_RAW3D = 10;
  30220. /**
  30221. * Texture content is a depth texture
  30222. */
  30223. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30224. return InternalTexture;
  30225. }());
  30226. BABYLON.InternalTexture = InternalTexture;
  30227. })(BABYLON || (BABYLON = {}));
  30228. //# sourceMappingURL=babylon.internalTexture.js.map
  30229. var BABYLON;
  30230. (function (BABYLON) {
  30231. var BaseTexture = /** @class */ (function () {
  30232. function BaseTexture(scene) {
  30233. this._hasAlpha = false;
  30234. this.getAlphaFromRGB = false;
  30235. this.level = 1;
  30236. this.coordinatesIndex = 0;
  30237. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30238. /**
  30239. * | Value | Type | Description |
  30240. * | ----- | ------------------ | ----------- |
  30241. * | 0 | CLAMP_ADDRESSMODE | |
  30242. * | 1 | WRAP_ADDRESSMODE | |
  30243. * | 2 | MIRROR_ADDRESSMODE | |
  30244. */
  30245. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30246. /**
  30247. * | Value | Type | Description |
  30248. * | ----- | ------------------ | ----------- |
  30249. * | 0 | CLAMP_ADDRESSMODE | |
  30250. * | 1 | WRAP_ADDRESSMODE | |
  30251. * | 2 | MIRROR_ADDRESSMODE | |
  30252. */
  30253. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30254. /**
  30255. * | Value | Type | Description |
  30256. * | ----- | ------------------ | ----------- |
  30257. * | 0 | CLAMP_ADDRESSMODE | |
  30258. * | 1 | WRAP_ADDRESSMODE | |
  30259. * | 2 | MIRROR_ADDRESSMODE | |
  30260. */
  30261. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30262. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30263. this.isCube = false;
  30264. this.is3D = false;
  30265. this.gammaSpace = true;
  30266. this.invertZ = false;
  30267. this.lodLevelInAlpha = false;
  30268. this.lodGenerationOffset = 0.0;
  30269. this.lodGenerationScale = 0.8;
  30270. this.isRenderTarget = false;
  30271. this.animations = new Array();
  30272. /**
  30273. * An event triggered when the texture is disposed.
  30274. */
  30275. this.onDisposeObservable = new BABYLON.Observable();
  30276. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30277. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30278. if (this._scene) {
  30279. this._scene.textures.push(this);
  30280. }
  30281. this._uid = null;
  30282. }
  30283. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30284. get: function () {
  30285. return this._hasAlpha;
  30286. },
  30287. set: function (value) {
  30288. if (this._hasAlpha === value) {
  30289. return;
  30290. }
  30291. this._hasAlpha = value;
  30292. if (this._scene) {
  30293. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30294. }
  30295. },
  30296. enumerable: true,
  30297. configurable: true
  30298. });
  30299. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30300. get: function () {
  30301. return this._coordinatesMode;
  30302. },
  30303. /**
  30304. * How a texture is mapped.
  30305. *
  30306. * | Value | Type | Description |
  30307. * | ----- | ----------------------------------- | ----------- |
  30308. * | 0 | EXPLICIT_MODE | |
  30309. * | 1 | SPHERICAL_MODE | |
  30310. * | 2 | PLANAR_MODE | |
  30311. * | 3 | CUBIC_MODE | |
  30312. * | 4 | PROJECTION_MODE | |
  30313. * | 5 | SKYBOX_MODE | |
  30314. * | 6 | INVCUBIC_MODE | |
  30315. * | 7 | EQUIRECTANGULAR_MODE | |
  30316. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30317. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30318. */
  30319. set: function (value) {
  30320. if (this._coordinatesMode === value) {
  30321. return;
  30322. }
  30323. this._coordinatesMode = value;
  30324. if (this._scene) {
  30325. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30326. }
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(BaseTexture.prototype, "uid", {
  30332. get: function () {
  30333. if (!this._uid) {
  30334. this._uid = BABYLON.Tools.RandomId();
  30335. }
  30336. return this._uid;
  30337. },
  30338. enumerable: true,
  30339. configurable: true
  30340. });
  30341. BaseTexture.prototype.toString = function () {
  30342. return this.name;
  30343. };
  30344. BaseTexture.prototype.getClassName = function () {
  30345. return "BaseTexture";
  30346. };
  30347. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30348. set: function (callback) {
  30349. if (this._onDisposeObserver) {
  30350. this.onDisposeObservable.remove(this._onDisposeObserver);
  30351. }
  30352. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30358. get: function () {
  30359. return true;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. BaseTexture.prototype.getScene = function () {
  30365. return this._scene;
  30366. };
  30367. BaseTexture.prototype.getTextureMatrix = function () {
  30368. return BABYLON.Matrix.IdentityReadOnly;
  30369. };
  30370. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30371. return BABYLON.Matrix.IdentityReadOnly;
  30372. };
  30373. BaseTexture.prototype.getInternalTexture = function () {
  30374. return this._texture;
  30375. };
  30376. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30377. return !this.isBlocking || this.isReady();
  30378. };
  30379. BaseTexture.prototype.isReady = function () {
  30380. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30381. this.delayLoad();
  30382. return false;
  30383. }
  30384. if (this._texture) {
  30385. return this._texture.isReady;
  30386. }
  30387. return false;
  30388. };
  30389. BaseTexture.prototype.getSize = function () {
  30390. if (this._texture && this._texture.width) {
  30391. return new BABYLON.Size(this._texture.width, this._texture.height);
  30392. }
  30393. if (this._texture && this._texture._size) {
  30394. return new BABYLON.Size(this._texture._size, this._texture._size);
  30395. }
  30396. return BABYLON.Size.Zero();
  30397. };
  30398. BaseTexture.prototype.getBaseSize = function () {
  30399. if (!this.isReady() || !this._texture)
  30400. return BABYLON.Size.Zero();
  30401. if (this._texture._size) {
  30402. return new BABYLON.Size(this._texture._size, this._texture._size);
  30403. }
  30404. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30405. };
  30406. BaseTexture.prototype.scale = function (ratio) {
  30407. };
  30408. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30409. get: function () {
  30410. return false;
  30411. },
  30412. enumerable: true,
  30413. configurable: true
  30414. });
  30415. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30416. if (!this._scene) {
  30417. return null;
  30418. }
  30419. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30420. for (var index = 0; index < texturesCache.length; index++) {
  30421. var texturesCacheEntry = texturesCache[index];
  30422. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30423. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30424. texturesCacheEntry.incrementReferences();
  30425. return texturesCacheEntry;
  30426. }
  30427. }
  30428. }
  30429. return null;
  30430. };
  30431. BaseTexture.prototype._rebuild = function () {
  30432. };
  30433. BaseTexture.prototype.delayLoad = function () {
  30434. };
  30435. BaseTexture.prototype.clone = function () {
  30436. return null;
  30437. };
  30438. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30439. get: function () {
  30440. if (!this._texture) {
  30441. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30442. }
  30443. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30444. },
  30445. enumerable: true,
  30446. configurable: true
  30447. });
  30448. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30449. get: function () {
  30450. if (!this._texture) {
  30451. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30452. }
  30453. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30454. },
  30455. enumerable: true,
  30456. configurable: true
  30457. });
  30458. BaseTexture.prototype.readPixels = function (faceIndex) {
  30459. if (faceIndex === void 0) { faceIndex = 0; }
  30460. if (!this._texture) {
  30461. return null;
  30462. }
  30463. var size = this.getSize();
  30464. var scene = this.getScene();
  30465. if (!scene) {
  30466. return null;
  30467. }
  30468. var engine = scene.getEngine();
  30469. if (this._texture.isCube) {
  30470. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30471. }
  30472. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30473. };
  30474. BaseTexture.prototype.releaseInternalTexture = function () {
  30475. if (this._texture) {
  30476. this._texture.dispose();
  30477. this._texture = null;
  30478. }
  30479. };
  30480. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30481. get: function () {
  30482. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30483. return null;
  30484. }
  30485. if (!this._texture._sphericalPolynomial) {
  30486. this._texture._sphericalPolynomial =
  30487. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30488. }
  30489. return this._texture._sphericalPolynomial;
  30490. },
  30491. set: function (value) {
  30492. if (this._texture) {
  30493. this._texture._sphericalPolynomial = value;
  30494. }
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30500. get: function () {
  30501. if (this._texture) {
  30502. return this._texture._lodTextureHigh;
  30503. }
  30504. return null;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30510. get: function () {
  30511. if (this._texture) {
  30512. return this._texture._lodTextureMid;
  30513. }
  30514. return null;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30520. get: function () {
  30521. if (this._texture) {
  30522. return this._texture._lodTextureLow;
  30523. }
  30524. return null;
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. BaseTexture.prototype.dispose = function () {
  30530. if (!this._scene) {
  30531. return;
  30532. }
  30533. // Animations
  30534. this._scene.stopAnimation(this);
  30535. // Remove from scene
  30536. this._scene._removePendingData(this);
  30537. var index = this._scene.textures.indexOf(this);
  30538. if (index >= 0) {
  30539. this._scene.textures.splice(index, 1);
  30540. }
  30541. if (this._texture === undefined) {
  30542. return;
  30543. }
  30544. // Release
  30545. this.releaseInternalTexture();
  30546. // Callback
  30547. this.onDisposeObservable.notifyObservers(this);
  30548. this.onDisposeObservable.clear();
  30549. };
  30550. BaseTexture.prototype.serialize = function () {
  30551. if (!this.name) {
  30552. return null;
  30553. }
  30554. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30555. // Animations
  30556. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30557. return serializationObject;
  30558. };
  30559. BaseTexture.WhenAllReady = function (textures, callback) {
  30560. var numRemaining = textures.length;
  30561. if (numRemaining === 0) {
  30562. callback();
  30563. return;
  30564. }
  30565. var _loop_1 = function () {
  30566. texture = textures[i];
  30567. if (texture.isReady()) {
  30568. if (--numRemaining === 0) {
  30569. callback();
  30570. }
  30571. }
  30572. else {
  30573. onLoadObservable = texture.onLoadObservable;
  30574. var onLoadCallback_1 = function () {
  30575. onLoadObservable.removeCallback(onLoadCallback_1);
  30576. if (--numRemaining === 0) {
  30577. callback();
  30578. }
  30579. };
  30580. onLoadObservable.add(onLoadCallback_1);
  30581. }
  30582. };
  30583. var texture, onLoadObservable;
  30584. for (var i = 0; i < textures.length; i++) {
  30585. _loop_1();
  30586. }
  30587. };
  30588. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], BaseTexture.prototype, "name", void 0);
  30592. __decorate([
  30593. BABYLON.serialize("hasAlpha")
  30594. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30598. __decorate([
  30599. BABYLON.serialize()
  30600. ], BaseTexture.prototype, "level", void 0);
  30601. __decorate([
  30602. BABYLON.serialize()
  30603. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30604. __decorate([
  30605. BABYLON.serialize("coordinatesMode")
  30606. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30607. __decorate([
  30608. BABYLON.serialize()
  30609. ], BaseTexture.prototype, "wrapU", void 0);
  30610. __decorate([
  30611. BABYLON.serialize()
  30612. ], BaseTexture.prototype, "wrapV", void 0);
  30613. __decorate([
  30614. BABYLON.serialize()
  30615. ], BaseTexture.prototype, "wrapR", void 0);
  30616. __decorate([
  30617. BABYLON.serialize()
  30618. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30619. __decorate([
  30620. BABYLON.serialize()
  30621. ], BaseTexture.prototype, "isCube", void 0);
  30622. __decorate([
  30623. BABYLON.serialize()
  30624. ], BaseTexture.prototype, "is3D", void 0);
  30625. __decorate([
  30626. BABYLON.serialize()
  30627. ], BaseTexture.prototype, "gammaSpace", void 0);
  30628. __decorate([
  30629. BABYLON.serialize()
  30630. ], BaseTexture.prototype, "invertZ", void 0);
  30631. __decorate([
  30632. BABYLON.serialize()
  30633. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30634. __decorate([
  30635. BABYLON.serialize()
  30636. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30637. __decorate([
  30638. BABYLON.serialize()
  30639. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30640. __decorate([
  30641. BABYLON.serialize()
  30642. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30643. return BaseTexture;
  30644. }());
  30645. BABYLON.BaseTexture = BaseTexture;
  30646. })(BABYLON || (BABYLON = {}));
  30647. //# sourceMappingURL=babylon.baseTexture.js.map
  30648. var BABYLON;
  30649. (function (BABYLON) {
  30650. var Texture = /** @class */ (function (_super) {
  30651. __extends(Texture, _super);
  30652. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30653. if (noMipmap === void 0) { noMipmap = false; }
  30654. if (invertY === void 0) { invertY = true; }
  30655. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30656. if (onLoad === void 0) { onLoad = null; }
  30657. if (onError === void 0) { onError = null; }
  30658. if (buffer === void 0) { buffer = null; }
  30659. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30660. var _this = _super.call(this, scene) || this;
  30661. _this.uOffset = 0;
  30662. _this.vOffset = 0;
  30663. _this.uScale = 1.0;
  30664. _this.vScale = 1.0;
  30665. _this.uAng = 0;
  30666. _this.vAng = 0;
  30667. _this.wAng = 0;
  30668. /**
  30669. * Defines the center of rotation (U)
  30670. */
  30671. _this.uRotationCenter = 0.5;
  30672. /**
  30673. * Defines the center of rotation (V)
  30674. */
  30675. _this.vRotationCenter = 0.5;
  30676. /**
  30677. * Defines the center of rotation (W)
  30678. */
  30679. _this.wRotationCenter = 0.5;
  30680. _this._isBlocking = true;
  30681. _this.name = url || "";
  30682. _this.url = url;
  30683. _this._noMipmap = noMipmap;
  30684. _this._invertY = invertY;
  30685. _this._samplingMode = samplingMode;
  30686. _this._buffer = buffer;
  30687. _this._deleteBuffer = deleteBuffer;
  30688. if (format) {
  30689. _this._format = format;
  30690. }
  30691. scene = _this.getScene();
  30692. if (!scene) {
  30693. return _this;
  30694. }
  30695. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30696. var load = function () {
  30697. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30698. _this.onLoadObservable.notifyObservers(_this);
  30699. }
  30700. if (onLoad) {
  30701. onLoad();
  30702. }
  30703. if (!_this.isBlocking && scene) {
  30704. scene.resetCachedMaterial();
  30705. }
  30706. };
  30707. if (!_this.url) {
  30708. _this._delayedOnLoad = load;
  30709. _this._delayedOnError = onError;
  30710. return _this;
  30711. }
  30712. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30713. if (!_this._texture) {
  30714. if (!scene.useDelayedTextureLoading) {
  30715. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30716. if (deleteBuffer) {
  30717. delete _this._buffer;
  30718. }
  30719. }
  30720. else {
  30721. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30722. _this._delayedOnLoad = load;
  30723. _this._delayedOnError = onError;
  30724. }
  30725. }
  30726. else {
  30727. if (_this._texture.isReady) {
  30728. BABYLON.Tools.SetImmediate(function () { return load(); });
  30729. }
  30730. else {
  30731. _this._texture.onLoadedObservable.add(load);
  30732. }
  30733. }
  30734. return _this;
  30735. }
  30736. Object.defineProperty(Texture.prototype, "noMipmap", {
  30737. get: function () {
  30738. return this._noMipmap;
  30739. },
  30740. enumerable: true,
  30741. configurable: true
  30742. });
  30743. Object.defineProperty(Texture.prototype, "isBlocking", {
  30744. get: function () {
  30745. return this._isBlocking;
  30746. },
  30747. set: function (value) {
  30748. this._isBlocking = value;
  30749. },
  30750. enumerable: true,
  30751. configurable: true
  30752. });
  30753. Object.defineProperty(Texture.prototype, "samplingMode", {
  30754. get: function () {
  30755. return this._samplingMode;
  30756. },
  30757. enumerable: true,
  30758. configurable: true
  30759. });
  30760. /**
  30761. * Update the url (and optional buffer) of this texture if url was null during construction.
  30762. * @param url the url of the texture
  30763. * @param buffer the buffer of the texture (defaults to null)
  30764. */
  30765. Texture.prototype.updateURL = function (url, buffer) {
  30766. if (buffer === void 0) { buffer = null; }
  30767. if (this.url) {
  30768. throw new Error("URL is already set");
  30769. }
  30770. this.url = url;
  30771. this._buffer = buffer;
  30772. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30773. this.delayLoad();
  30774. };
  30775. Texture.prototype.delayLoad = function () {
  30776. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30777. return;
  30778. }
  30779. var scene = this.getScene();
  30780. if (!scene) {
  30781. return;
  30782. }
  30783. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30784. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30785. if (!this._texture) {
  30786. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30787. if (this._deleteBuffer) {
  30788. delete this._buffer;
  30789. }
  30790. }
  30791. else {
  30792. if (this._delayedOnLoad) {
  30793. if (this._texture.isReady) {
  30794. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30795. }
  30796. else {
  30797. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30798. }
  30799. }
  30800. }
  30801. this._delayedOnLoad = null;
  30802. this._delayedOnError = null;
  30803. };
  30804. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30805. if (!this._texture) {
  30806. return;
  30807. }
  30808. var scene = this.getScene();
  30809. if (!scene) {
  30810. return;
  30811. }
  30812. this._samplingMode = samplingMode;
  30813. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30814. };
  30815. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30816. x *= this.uScale;
  30817. y *= this.vScale;
  30818. x -= this.uRotationCenter * this.uScale;
  30819. y -= this.vRotationCenter * this.vScale;
  30820. z -= this.wRotationCenter;
  30821. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30822. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30823. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30824. t.z += this.wRotationCenter;
  30825. };
  30826. Texture.prototype.getTextureMatrix = function () {
  30827. var _this = this;
  30828. if (this.uOffset === this._cachedUOffset &&
  30829. this.vOffset === this._cachedVOffset &&
  30830. this.uScale === this._cachedUScale &&
  30831. this.vScale === this._cachedVScale &&
  30832. this.uAng === this._cachedUAng &&
  30833. this.vAng === this._cachedVAng &&
  30834. this.wAng === this._cachedWAng) {
  30835. return this._cachedTextureMatrix;
  30836. }
  30837. this._cachedUOffset = this.uOffset;
  30838. this._cachedVOffset = this.vOffset;
  30839. this._cachedUScale = this.uScale;
  30840. this._cachedVScale = this.vScale;
  30841. this._cachedUAng = this.uAng;
  30842. this._cachedVAng = this.vAng;
  30843. this._cachedWAng = this.wAng;
  30844. if (!this._cachedTextureMatrix) {
  30845. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30846. this._rowGenerationMatrix = new BABYLON.Matrix();
  30847. this._t0 = BABYLON.Vector3.Zero();
  30848. this._t1 = BABYLON.Vector3.Zero();
  30849. this._t2 = BABYLON.Vector3.Zero();
  30850. }
  30851. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30852. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30853. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30854. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30855. this._t1.subtractInPlace(this._t0);
  30856. this._t2.subtractInPlace(this._t0);
  30857. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30858. this._cachedTextureMatrix.m[0] = this._t1.x;
  30859. this._cachedTextureMatrix.m[1] = this._t1.y;
  30860. this._cachedTextureMatrix.m[2] = this._t1.z;
  30861. this._cachedTextureMatrix.m[4] = this._t2.x;
  30862. this._cachedTextureMatrix.m[5] = this._t2.y;
  30863. this._cachedTextureMatrix.m[6] = this._t2.z;
  30864. this._cachedTextureMatrix.m[8] = this._t0.x;
  30865. this._cachedTextureMatrix.m[9] = this._t0.y;
  30866. this._cachedTextureMatrix.m[10] = this._t0.z;
  30867. var scene = this.getScene();
  30868. if (!scene) {
  30869. return this._cachedTextureMatrix;
  30870. }
  30871. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30872. return mat.hasTexture(_this);
  30873. });
  30874. return this._cachedTextureMatrix;
  30875. };
  30876. Texture.prototype.getReflectionTextureMatrix = function () {
  30877. var _this = this;
  30878. var scene = this.getScene();
  30879. if (!scene) {
  30880. return this._cachedTextureMatrix;
  30881. }
  30882. if (this.uOffset === this._cachedUOffset &&
  30883. this.vOffset === this._cachedVOffset &&
  30884. this.uScale === this._cachedUScale &&
  30885. this.vScale === this._cachedVScale &&
  30886. this.coordinatesMode === this._cachedCoordinatesMode) {
  30887. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30888. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30889. return this._cachedTextureMatrix;
  30890. }
  30891. }
  30892. else {
  30893. return this._cachedTextureMatrix;
  30894. }
  30895. }
  30896. if (!this._cachedTextureMatrix) {
  30897. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30898. }
  30899. if (!this._projectionModeMatrix) {
  30900. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30901. }
  30902. this._cachedUOffset = this.uOffset;
  30903. this._cachedVOffset = this.vOffset;
  30904. this._cachedUScale = this.uScale;
  30905. this._cachedVScale = this.vScale;
  30906. this._cachedCoordinatesMode = this.coordinatesMode;
  30907. switch (this.coordinatesMode) {
  30908. case Texture.PLANAR_MODE:
  30909. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30910. this._cachedTextureMatrix[0] = this.uScale;
  30911. this._cachedTextureMatrix[5] = this.vScale;
  30912. this._cachedTextureMatrix[12] = this.uOffset;
  30913. this._cachedTextureMatrix[13] = this.vOffset;
  30914. break;
  30915. case Texture.PROJECTION_MODE:
  30916. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30917. this._projectionModeMatrix.m[0] = 0.5;
  30918. this._projectionModeMatrix.m[5] = -0.5;
  30919. this._projectionModeMatrix.m[10] = 0.0;
  30920. this._projectionModeMatrix.m[12] = 0.5;
  30921. this._projectionModeMatrix.m[13] = 0.5;
  30922. this._projectionModeMatrix.m[14] = 1.0;
  30923. this._projectionModeMatrix.m[15] = 1.0;
  30924. var projectionMatrix = scene.getProjectionMatrix();
  30925. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30926. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30927. break;
  30928. default:
  30929. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30930. break;
  30931. }
  30932. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30933. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30934. });
  30935. return this._cachedTextureMatrix;
  30936. };
  30937. Texture.prototype.clone = function () {
  30938. var _this = this;
  30939. return BABYLON.SerializationHelper.Clone(function () {
  30940. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30941. }, this);
  30942. };
  30943. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30944. get: function () {
  30945. if (!this._onLoadObservable) {
  30946. this._onLoadObservable = new BABYLON.Observable();
  30947. }
  30948. return this._onLoadObservable;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Texture.prototype.serialize = function () {
  30954. var serializationObject = _super.prototype.serialize.call(this);
  30955. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30956. serializationObject.base64String = this._buffer;
  30957. serializationObject.name = serializationObject.name.replace("data:", "");
  30958. }
  30959. serializationObject.invertY = this._invertY;
  30960. serializationObject.samplingMode = this.samplingMode;
  30961. return serializationObject;
  30962. };
  30963. Texture.prototype.getClassName = function () {
  30964. return "Texture";
  30965. };
  30966. Texture.prototype.dispose = function () {
  30967. _super.prototype.dispose.call(this);
  30968. if (this.onLoadObservable) {
  30969. this.onLoadObservable.clear();
  30970. this._onLoadObservable = null;
  30971. }
  30972. this._delayedOnLoad = null;
  30973. this._delayedOnError = null;
  30974. };
  30975. // Statics
  30976. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30977. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30978. if (onLoad === void 0) { onLoad = null; }
  30979. if (onError === void 0) { onError = null; }
  30980. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30981. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30982. };
  30983. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30984. if (parsedTexture.customType) {
  30985. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30986. // Update Sampling Mode
  30987. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30988. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30989. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30990. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30991. }
  30992. }
  30993. return parsedCustomTexture;
  30994. }
  30995. if (parsedTexture.isCube) {
  30996. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30997. }
  30998. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30999. return null;
  31000. }
  31001. var texture = BABYLON.SerializationHelper.Parse(function () {
  31002. var generateMipMaps = true;
  31003. if (parsedTexture.noMipmap) {
  31004. generateMipMaps = false;
  31005. }
  31006. if (parsedTexture.mirrorPlane) {
  31007. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31008. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31009. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31010. return mirrorTexture;
  31011. }
  31012. else if (parsedTexture.isRenderTarget) {
  31013. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31014. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31015. return renderTargetTexture;
  31016. }
  31017. else {
  31018. var texture;
  31019. if (parsedTexture.base64String) {
  31020. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31021. }
  31022. else {
  31023. var url = rootUrl + parsedTexture.name;
  31024. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31025. url = parsedTexture.url;
  31026. }
  31027. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31028. }
  31029. return texture;
  31030. }
  31031. }, parsedTexture, scene);
  31032. // Update Sampling Mode
  31033. if (parsedTexture.samplingMode) {
  31034. var sampling = parsedTexture.samplingMode;
  31035. if (texture._samplingMode !== sampling) {
  31036. texture.updateSamplingMode(sampling);
  31037. }
  31038. }
  31039. // Animations
  31040. if (parsedTexture.animations) {
  31041. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31042. var parsedAnimation = parsedTexture.animations[animationIndex];
  31043. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31044. }
  31045. }
  31046. return texture;
  31047. };
  31048. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31049. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31050. if (noMipmap === void 0) { noMipmap = false; }
  31051. if (invertY === void 0) { invertY = true; }
  31052. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31053. if (onLoad === void 0) { onLoad = null; }
  31054. if (onError === void 0) { onError = null; }
  31055. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31056. if (name.substr(0, 5) !== "data:") {
  31057. name = "data:" + name;
  31058. }
  31059. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31060. };
  31061. // Constants
  31062. Texture.NEAREST_SAMPLINGMODE = 1;
  31063. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31064. Texture.BILINEAR_SAMPLINGMODE = 2;
  31065. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31066. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31067. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31068. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31069. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31070. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31071. Texture.NEAREST_LINEAR = 7;
  31072. Texture.NEAREST_NEAREST = 8;
  31073. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31074. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31075. Texture.LINEAR_LINEAR = 11;
  31076. Texture.LINEAR_NEAREST = 12;
  31077. Texture.EXPLICIT_MODE = 0;
  31078. Texture.SPHERICAL_MODE = 1;
  31079. Texture.PLANAR_MODE = 2;
  31080. Texture.CUBIC_MODE = 3;
  31081. Texture.PROJECTION_MODE = 4;
  31082. Texture.SKYBOX_MODE = 5;
  31083. Texture.INVCUBIC_MODE = 6;
  31084. Texture.EQUIRECTANGULAR_MODE = 7;
  31085. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31086. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31087. Texture.CLAMP_ADDRESSMODE = 0;
  31088. Texture.WRAP_ADDRESSMODE = 1;
  31089. Texture.MIRROR_ADDRESSMODE = 2;
  31090. /**
  31091. * 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
  31092. */
  31093. Texture.UseSerializedUrlIfAny = false;
  31094. __decorate([
  31095. BABYLON.serialize()
  31096. ], Texture.prototype, "url", void 0);
  31097. __decorate([
  31098. BABYLON.serialize()
  31099. ], Texture.prototype, "uOffset", void 0);
  31100. __decorate([
  31101. BABYLON.serialize()
  31102. ], Texture.prototype, "vOffset", void 0);
  31103. __decorate([
  31104. BABYLON.serialize()
  31105. ], Texture.prototype, "uScale", void 0);
  31106. __decorate([
  31107. BABYLON.serialize()
  31108. ], Texture.prototype, "vScale", void 0);
  31109. __decorate([
  31110. BABYLON.serialize()
  31111. ], Texture.prototype, "uAng", void 0);
  31112. __decorate([
  31113. BABYLON.serialize()
  31114. ], Texture.prototype, "vAng", void 0);
  31115. __decorate([
  31116. BABYLON.serialize()
  31117. ], Texture.prototype, "wAng", void 0);
  31118. __decorate([
  31119. BABYLON.serialize()
  31120. ], Texture.prototype, "uRotationCenter", void 0);
  31121. __decorate([
  31122. BABYLON.serialize()
  31123. ], Texture.prototype, "vRotationCenter", void 0);
  31124. __decorate([
  31125. BABYLON.serialize()
  31126. ], Texture.prototype, "wRotationCenter", void 0);
  31127. __decorate([
  31128. BABYLON.serialize()
  31129. ], Texture.prototype, "isBlocking", null);
  31130. return Texture;
  31131. }(BABYLON.BaseTexture));
  31132. BABYLON.Texture = Texture;
  31133. })(BABYLON || (BABYLON = {}));
  31134. //# sourceMappingURL=babylon.texture.js.map
  31135. var BABYLON;
  31136. (function (BABYLON) {
  31137. /**
  31138. * @hidden
  31139. **/
  31140. var _InstancesBatch = /** @class */ (function () {
  31141. function _InstancesBatch() {
  31142. this.mustReturn = false;
  31143. this.visibleInstances = new Array();
  31144. this.renderSelf = new Array();
  31145. }
  31146. return _InstancesBatch;
  31147. }());
  31148. BABYLON._InstancesBatch = _InstancesBatch;
  31149. var Mesh = /** @class */ (function (_super) {
  31150. __extends(Mesh, _super);
  31151. /**
  31152. * @constructor
  31153. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31154. * @param {Scene} scene The scene to add this mesh to.
  31155. * @param {Node} parent The parent of this mesh, if it has one
  31156. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31157. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31158. * When false, achieved by calling a clone(), also passing False.
  31159. * This will make creation of children, recursive.
  31160. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31161. */
  31162. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31163. if (scene === void 0) { scene = null; }
  31164. if (parent === void 0) { parent = null; }
  31165. if (source === void 0) { source = null; }
  31166. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31167. var _this = _super.call(this, name, scene) || this;
  31168. // Events
  31169. /**
  31170. * An event triggered before rendering the mesh
  31171. */
  31172. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31173. /**
  31174. * An event triggered after rendering the mesh
  31175. */
  31176. _this.onAfterRenderObservable = new BABYLON.Observable();
  31177. /**
  31178. * An event triggered before drawing the mesh
  31179. */
  31180. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31181. // Members
  31182. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31183. _this.instances = new Array();
  31184. _this._LODLevels = new Array();
  31185. _this._visibleInstances = {};
  31186. _this._renderIdForInstances = new Array();
  31187. _this._batchCache = new _InstancesBatch();
  31188. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31189. // Use by builder only to know what orientation were the mesh build in.
  31190. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31191. _this.overrideMaterialSideOrientation = null;
  31192. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31193. // Will be used to save a source mesh reference, If any
  31194. _this._source = null;
  31195. scene = _this.getScene();
  31196. if (source) {
  31197. // Geometry
  31198. if (source._geometry) {
  31199. source._geometry.applyToMesh(_this);
  31200. }
  31201. // Deep copy
  31202. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31203. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31204. // Source mesh
  31205. _this._source = source;
  31206. // Metadata
  31207. if (source.metadata && source.metadata.clone) {
  31208. _this.metadata = source.metadata.clone();
  31209. }
  31210. else {
  31211. _this.metadata = source.metadata;
  31212. }
  31213. // Tags
  31214. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31215. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31216. }
  31217. // Parent
  31218. _this.parent = source.parent;
  31219. // Pivot
  31220. _this.setPivotMatrix(source.getPivotMatrix());
  31221. _this.id = name + "." + source.id;
  31222. // Material
  31223. _this.material = source.material;
  31224. var index;
  31225. if (!doNotCloneChildren) {
  31226. // Children
  31227. var directDescendants = source.getDescendants(true);
  31228. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31229. var child = directDescendants[index_1];
  31230. if (child.clone) {
  31231. child.clone(name + "." + child.name, _this);
  31232. }
  31233. }
  31234. }
  31235. // Physics clone
  31236. var physicsEngine = _this.getScene().getPhysicsEngine();
  31237. if (clonePhysicsImpostor && physicsEngine) {
  31238. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31239. if (impostor) {
  31240. _this.physicsImpostor = impostor.clone(_this);
  31241. }
  31242. }
  31243. // Particles
  31244. for (index = 0; index < scene.particleSystems.length; index++) {
  31245. var system = scene.particleSystems[index];
  31246. if (system.emitter === source) {
  31247. system.clone(system.name, _this);
  31248. }
  31249. }
  31250. _this.computeWorldMatrix(true);
  31251. }
  31252. // Parent
  31253. if (parent !== null) {
  31254. _this.parent = parent;
  31255. }
  31256. return _this;
  31257. }
  31258. Object.defineProperty(Mesh, "FRONTSIDE", {
  31259. /**
  31260. * Mesh side orientation : usually the external or front surface
  31261. */
  31262. get: function () {
  31263. return Mesh._FRONTSIDE;
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. Object.defineProperty(Mesh, "BACKSIDE", {
  31269. /**
  31270. * Mesh side orientation : usually the internal or back surface
  31271. */
  31272. get: function () {
  31273. return Mesh._BACKSIDE;
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31279. /**
  31280. * Mesh side orientation : both internal and external or front and back surfaces
  31281. */
  31282. get: function () {
  31283. return Mesh._DOUBLESIDE;
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31289. /**
  31290. * Mesh side orientation : by default, `FRONTSIDE`
  31291. */
  31292. get: function () {
  31293. return Mesh._DEFAULTSIDE;
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. Object.defineProperty(Mesh, "NO_CAP", {
  31299. /**
  31300. * Mesh cap setting : no cap
  31301. */
  31302. get: function () {
  31303. return Mesh._NO_CAP;
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. Object.defineProperty(Mesh, "CAP_START", {
  31309. /**
  31310. * Mesh cap setting : one cap at the beginning of the mesh
  31311. */
  31312. get: function () {
  31313. return Mesh._CAP_START;
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Mesh, "CAP_END", {
  31319. /**
  31320. * Mesh cap setting : one cap at the end of the mesh
  31321. */
  31322. get: function () {
  31323. return Mesh._CAP_END;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Mesh, "CAP_ALL", {
  31329. /**
  31330. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31331. */
  31332. get: function () {
  31333. return Mesh._CAP_ALL;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31339. set: function (callback) {
  31340. if (this._onBeforeDrawObserver) {
  31341. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31342. }
  31343. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31349. get: function () {
  31350. return this._morphTargetManager;
  31351. },
  31352. set: function (value) {
  31353. if (this._morphTargetManager === value) {
  31354. return;
  31355. }
  31356. this._morphTargetManager = value;
  31357. this._syncGeometryWithMorphTargetManager();
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. Object.defineProperty(Mesh.prototype, "source", {
  31363. get: function () {
  31364. return this._source;
  31365. },
  31366. enumerable: true,
  31367. configurable: true
  31368. });
  31369. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31370. get: function () {
  31371. return this._unIndexed;
  31372. },
  31373. set: function (value) {
  31374. if (this._unIndexed !== value) {
  31375. this._unIndexed = value;
  31376. this._markSubMeshesAsAttributesDirty();
  31377. }
  31378. },
  31379. enumerable: true,
  31380. configurable: true
  31381. });
  31382. // Methods
  31383. /**
  31384. * Returns the string "Mesh".
  31385. */
  31386. Mesh.prototype.getClassName = function () {
  31387. return "Mesh";
  31388. };
  31389. /**
  31390. * Returns a string.
  31391. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31392. */
  31393. Mesh.prototype.toString = function (fullDetails) {
  31394. var ret = _super.prototype.toString.call(this, fullDetails);
  31395. ret += ", n vertices: " + this.getTotalVertices();
  31396. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31397. if (this.animations) {
  31398. for (var i = 0; i < this.animations.length; i++) {
  31399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31400. }
  31401. }
  31402. if (fullDetails) {
  31403. if (this._geometry) {
  31404. var ib = this.getIndices();
  31405. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31406. if (vb && ib) {
  31407. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31408. }
  31409. }
  31410. else {
  31411. ret += ", flat shading: UNKNOWN";
  31412. }
  31413. }
  31414. return ret;
  31415. };
  31416. Mesh.prototype._unBindEffect = function () {
  31417. _super.prototype._unBindEffect.call(this);
  31418. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31419. var instance = _a[_i];
  31420. instance._unBindEffect();
  31421. }
  31422. };
  31423. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31424. /**
  31425. * True if the mesh has some Levels Of Details (LOD).
  31426. * Returns a boolean.
  31427. */
  31428. get: function () {
  31429. return this._LODLevels.length > 0;
  31430. },
  31431. enumerable: true,
  31432. configurable: true
  31433. });
  31434. /**
  31435. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31436. * @returns an array of {BABYLON.MeshLODLevel}
  31437. */
  31438. Mesh.prototype.getLODLevels = function () {
  31439. return this._LODLevels;
  31440. };
  31441. Mesh.prototype._sortLODLevels = function () {
  31442. this._LODLevels.sort(function (a, b) {
  31443. if (a.distance < b.distance) {
  31444. return 1;
  31445. }
  31446. if (a.distance > b.distance) {
  31447. return -1;
  31448. }
  31449. return 0;
  31450. });
  31451. };
  31452. /**
  31453. * Add a mesh as LOD level triggered at the given distance.
  31454. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31455. * @param {number} distance The distance from the center of the object to show this level
  31456. * @param {Mesh} mesh The mesh to be added as LOD level
  31457. * @return {Mesh} This mesh (for chaining)
  31458. */
  31459. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31460. if (mesh && mesh._masterMesh) {
  31461. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31462. return this;
  31463. }
  31464. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31465. this._LODLevels.push(level);
  31466. if (mesh) {
  31467. mesh._masterMesh = this;
  31468. }
  31469. this._sortLODLevels();
  31470. return this;
  31471. };
  31472. /**
  31473. * Returns the LOD level mesh at the passed distance or null if not found.
  31474. * It is related to the method `addLODLevel(distance, mesh)`.
  31475. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31476. * Returns an object Mesh or `null`.
  31477. */
  31478. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31479. for (var index = 0; index < this._LODLevels.length; index++) {
  31480. var level = this._LODLevels[index];
  31481. if (level.distance === distance) {
  31482. return level.mesh;
  31483. }
  31484. }
  31485. return null;
  31486. };
  31487. /**
  31488. * Remove a mesh from the LOD array
  31489. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31490. * @param {Mesh} mesh The mesh to be removed.
  31491. * @return {Mesh} This mesh (for chaining)
  31492. */
  31493. Mesh.prototype.removeLODLevel = function (mesh) {
  31494. for (var index = 0; index < this._LODLevels.length; index++) {
  31495. if (this._LODLevels[index].mesh === mesh) {
  31496. this._LODLevels.splice(index, 1);
  31497. if (mesh) {
  31498. mesh._masterMesh = null;
  31499. }
  31500. }
  31501. }
  31502. this._sortLODLevels();
  31503. return this;
  31504. };
  31505. /**
  31506. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31507. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31508. */
  31509. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31510. if (!this._LODLevels || this._LODLevels.length === 0) {
  31511. return this;
  31512. }
  31513. var bSphere;
  31514. if (boundingSphere) {
  31515. bSphere = boundingSphere;
  31516. }
  31517. else {
  31518. var boundingInfo = this.getBoundingInfo();
  31519. bSphere = boundingInfo.boundingSphere;
  31520. }
  31521. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31522. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31523. if (this.onLODLevelSelection) {
  31524. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31525. }
  31526. return this;
  31527. }
  31528. for (var index = 0; index < this._LODLevels.length; index++) {
  31529. var level = this._LODLevels[index];
  31530. if (level.distance < distanceToCamera) {
  31531. if (level.mesh) {
  31532. level.mesh._preActivate();
  31533. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31534. }
  31535. if (this.onLODLevelSelection) {
  31536. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31537. }
  31538. return level.mesh;
  31539. }
  31540. }
  31541. if (this.onLODLevelSelection) {
  31542. this.onLODLevelSelection(distanceToCamera, this, this);
  31543. }
  31544. return this;
  31545. };
  31546. Object.defineProperty(Mesh.prototype, "geometry", {
  31547. /**
  31548. * Returns the mesh internal Geometry object.
  31549. */
  31550. get: function () {
  31551. return this._geometry;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. /**
  31557. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31558. */
  31559. Mesh.prototype.getTotalVertices = function () {
  31560. if (this._geometry === null || this._geometry === undefined) {
  31561. return 0;
  31562. }
  31563. return this._geometry.getTotalVertices();
  31564. };
  31565. /**
  31566. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31567. * 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.
  31568. * You can force the copy with forceCopy === true
  31569. * Returns null if the mesh has no geometry or no vertex buffer.
  31570. * Possible `kind` values :
  31571. * - BABYLON.VertexBuffer.PositionKind
  31572. * - BABYLON.VertexBuffer.UVKind
  31573. * - BABYLON.VertexBuffer.UV2Kind
  31574. * - BABYLON.VertexBuffer.UV3Kind
  31575. * - BABYLON.VertexBuffer.UV4Kind
  31576. * - BABYLON.VertexBuffer.UV5Kind
  31577. * - BABYLON.VertexBuffer.UV6Kind
  31578. * - BABYLON.VertexBuffer.ColorKind
  31579. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31580. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31581. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31582. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31583. */
  31584. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31585. if (!this._geometry) {
  31586. return null;
  31587. }
  31588. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31589. };
  31590. /**
  31591. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31592. * Returns `null` if the mesh has no geometry.
  31593. * Possible `kind` values :
  31594. * - BABYLON.VertexBuffer.PositionKind
  31595. * - BABYLON.VertexBuffer.UVKind
  31596. * - BABYLON.VertexBuffer.UV2Kind
  31597. * - BABYLON.VertexBuffer.UV3Kind
  31598. * - BABYLON.VertexBuffer.UV4Kind
  31599. * - BABYLON.VertexBuffer.UV5Kind
  31600. * - BABYLON.VertexBuffer.UV6Kind
  31601. * - BABYLON.VertexBuffer.ColorKind
  31602. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31603. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31604. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31605. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31606. */
  31607. Mesh.prototype.getVertexBuffer = function (kind) {
  31608. if (!this._geometry) {
  31609. return null;
  31610. }
  31611. return this._geometry.getVertexBuffer(kind);
  31612. };
  31613. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31614. if (!this._geometry) {
  31615. if (this._delayInfo) {
  31616. return this._delayInfo.indexOf(kind) !== -1;
  31617. }
  31618. return false;
  31619. }
  31620. return this._geometry.isVerticesDataPresent(kind);
  31621. };
  31622. /**
  31623. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31624. * Possible `kind` values :
  31625. * - BABYLON.VertexBuffer.PositionKind
  31626. * - BABYLON.VertexBuffer.UVKind
  31627. * - BABYLON.VertexBuffer.UV2Kind
  31628. * - BABYLON.VertexBuffer.UV3Kind
  31629. * - BABYLON.VertexBuffer.UV4Kind
  31630. * - BABYLON.VertexBuffer.UV5Kind
  31631. * - BABYLON.VertexBuffer.UV6Kind
  31632. * - BABYLON.VertexBuffer.ColorKind
  31633. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31634. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31635. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31636. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31637. */
  31638. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31639. if (!this._geometry) {
  31640. if (this._delayInfo) {
  31641. return this._delayInfo.indexOf(kind) !== -1;
  31642. }
  31643. return false;
  31644. }
  31645. return this._geometry.isVertexBufferUpdatable(kind);
  31646. };
  31647. /**
  31648. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31649. * Possible `kind` values :
  31650. * - BABYLON.VertexBuffer.PositionKind
  31651. * - BABYLON.VertexBuffer.UVKind
  31652. * - BABYLON.VertexBuffer.UV2Kind
  31653. * - BABYLON.VertexBuffer.UV3Kind
  31654. * - BABYLON.VertexBuffer.UV4Kind
  31655. * - BABYLON.VertexBuffer.UV5Kind
  31656. * - BABYLON.VertexBuffer.UV6Kind
  31657. * - BABYLON.VertexBuffer.ColorKind
  31658. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31659. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31660. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31661. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31662. */
  31663. Mesh.prototype.getVerticesDataKinds = function () {
  31664. if (!this._geometry) {
  31665. var result = new Array();
  31666. if (this._delayInfo) {
  31667. this._delayInfo.forEach(function (kind, index, array) {
  31668. result.push(kind);
  31669. });
  31670. }
  31671. return result;
  31672. }
  31673. return this._geometry.getVerticesDataKinds();
  31674. };
  31675. /**
  31676. * Returns a positive integer : the total number of indices in this mesh geometry.
  31677. * Returns zero if the mesh has no geometry.
  31678. */
  31679. Mesh.prototype.getTotalIndices = function () {
  31680. if (!this._geometry) {
  31681. return 0;
  31682. }
  31683. return this._geometry.getTotalIndices();
  31684. };
  31685. /**
  31686. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31687. * 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.
  31688. * Returns an empty array if the mesh has no geometry.
  31689. */
  31690. Mesh.prototype.getIndices = function (copyWhenShared) {
  31691. if (!this._geometry) {
  31692. return [];
  31693. }
  31694. return this._geometry.getIndices(copyWhenShared);
  31695. };
  31696. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31697. get: function () {
  31698. return this._masterMesh !== null && this._masterMesh !== undefined;
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. /**
  31704. * Determine if the current mesh is ready to be rendered
  31705. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31706. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31707. * @returns true if all associated assets are ready (material, textures, shaders)
  31708. */
  31709. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31710. if (completeCheck === void 0) { completeCheck = false; }
  31711. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31712. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31713. return false;
  31714. }
  31715. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31716. return false;
  31717. }
  31718. if (!this.subMeshes || this.subMeshes.length === 0) {
  31719. return true;
  31720. }
  31721. if (!completeCheck) {
  31722. return true;
  31723. }
  31724. var engine = this.getEngine();
  31725. var scene = this.getScene();
  31726. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31727. this.computeWorldMatrix();
  31728. var mat = this.material || scene.defaultMaterial;
  31729. if (mat) {
  31730. if (mat.storeEffectOnSubMeshes) {
  31731. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31732. var subMesh = _a[_i];
  31733. var effectiveMaterial = subMesh.getMaterial();
  31734. if (effectiveMaterial) {
  31735. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31736. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31737. return false;
  31738. }
  31739. }
  31740. else {
  31741. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31742. return false;
  31743. }
  31744. }
  31745. }
  31746. }
  31747. }
  31748. else {
  31749. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31750. return false;
  31751. }
  31752. }
  31753. }
  31754. // Shadows
  31755. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31756. var light = _c[_b];
  31757. var generator = light.getShadowGenerator();
  31758. if (generator) {
  31759. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31760. var subMesh = _e[_d];
  31761. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31762. return false;
  31763. }
  31764. }
  31765. }
  31766. }
  31767. // LOD
  31768. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31769. var lod = _g[_f];
  31770. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31771. return false;
  31772. }
  31773. }
  31774. return true;
  31775. };
  31776. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31777. /**
  31778. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31779. * This property is pertinent only for updatable parametric shapes.
  31780. */
  31781. get: function () {
  31782. return this._areNormalsFrozen;
  31783. },
  31784. enumerable: true,
  31785. configurable: true
  31786. });
  31787. /**
  31788. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31789. * It has no effect at all on other shapes.
  31790. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31791. * Returns the Mesh.
  31792. */
  31793. Mesh.prototype.freezeNormals = function () {
  31794. this._areNormalsFrozen = true;
  31795. return this;
  31796. };
  31797. /**
  31798. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31799. * It has no effect at all on other shapes.
  31800. * It reactivates the mesh normals computation if it was previously frozen.
  31801. * Returns the Mesh.
  31802. */
  31803. Mesh.prototype.unfreezeNormals = function () {
  31804. this._areNormalsFrozen = false;
  31805. return this;
  31806. };
  31807. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31808. /**
  31809. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31810. */
  31811. set: function (count) {
  31812. this._overridenInstanceCount = count;
  31813. },
  31814. enumerable: true,
  31815. configurable: true
  31816. });
  31817. // Methods
  31818. Mesh.prototype._preActivate = function () {
  31819. var sceneRenderId = this.getScene().getRenderId();
  31820. if (this._preActivateId === sceneRenderId) {
  31821. return this;
  31822. }
  31823. this._preActivateId = sceneRenderId;
  31824. this._visibleInstances = null;
  31825. return this;
  31826. };
  31827. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31828. if (this._visibleInstances) {
  31829. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31830. }
  31831. return this;
  31832. };
  31833. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31834. if (!this._visibleInstances) {
  31835. this._visibleInstances = {};
  31836. this._visibleInstances.defaultRenderId = renderId;
  31837. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31838. }
  31839. if (!this._visibleInstances[renderId]) {
  31840. this._visibleInstances[renderId] = new Array();
  31841. }
  31842. this._visibleInstances[renderId].push(instance);
  31843. return this;
  31844. };
  31845. /**
  31846. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31847. * This means the mesh underlying bounding box and sphere are recomputed.
  31848. * Returns the Mesh.
  31849. */
  31850. Mesh.prototype.refreshBoundingInfo = function () {
  31851. return this._refreshBoundingInfo(false);
  31852. };
  31853. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31854. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31855. return this;
  31856. }
  31857. var data = this._getPositionData(applySkeleton);
  31858. if (data) {
  31859. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31860. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31861. }
  31862. if (this.subMeshes) {
  31863. for (var index = 0; index < this.subMeshes.length; index++) {
  31864. this.subMeshes[index].refreshBoundingInfo();
  31865. }
  31866. }
  31867. this._updateBoundingInfo();
  31868. return this;
  31869. };
  31870. Mesh.prototype._getPositionData = function (applySkeleton) {
  31871. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31872. if (data && applySkeleton && this.skeleton) {
  31873. data = BABYLON.Tools.Slice(data);
  31874. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31875. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31876. if (matricesWeightsData && matricesIndicesData) {
  31877. var needExtras = this.numBoneInfluencers > 4;
  31878. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31879. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31880. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31881. var tempVector = BABYLON.Tmp.Vector3[0];
  31882. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31883. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31884. var matWeightIdx = 0;
  31885. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31886. finalMatrix.reset();
  31887. var inf;
  31888. var weight;
  31889. for (inf = 0; inf < 4; inf++) {
  31890. weight = matricesWeightsData[matWeightIdx + inf];
  31891. if (weight <= 0)
  31892. break;
  31893. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31894. finalMatrix.addToSelf(tempMatrix);
  31895. }
  31896. if (needExtras) {
  31897. for (inf = 0; inf < 4; inf++) {
  31898. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31899. if (weight <= 0)
  31900. break;
  31901. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31902. finalMatrix.addToSelf(tempMatrix);
  31903. }
  31904. }
  31905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31906. tempVector.toArray(data, index);
  31907. }
  31908. }
  31909. }
  31910. return data;
  31911. };
  31912. Mesh.prototype._createGlobalSubMesh = function (force) {
  31913. var totalVertices = this.getTotalVertices();
  31914. if (!totalVertices || !this.getIndices()) {
  31915. return null;
  31916. }
  31917. // Check if we need to recreate the submeshes
  31918. if (this.subMeshes && this.subMeshes.length > 0) {
  31919. var ib = this.getIndices();
  31920. if (!ib) {
  31921. return null;
  31922. }
  31923. var totalIndices = ib.length;
  31924. var needToRecreate = false;
  31925. if (force) {
  31926. needToRecreate = true;
  31927. }
  31928. else {
  31929. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31930. var submesh = _a[_i];
  31931. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31932. needToRecreate = true;
  31933. break;
  31934. }
  31935. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31936. needToRecreate = true;
  31937. break;
  31938. }
  31939. }
  31940. }
  31941. if (!needToRecreate) {
  31942. return this.subMeshes[0];
  31943. }
  31944. }
  31945. this.releaseSubMeshes();
  31946. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31947. };
  31948. Mesh.prototype.subdivide = function (count) {
  31949. if (count < 1) {
  31950. return;
  31951. }
  31952. var totalIndices = this.getTotalIndices();
  31953. var subdivisionSize = (totalIndices / count) | 0;
  31954. var offset = 0;
  31955. // Ensure that subdivisionSize is a multiple of 3
  31956. while (subdivisionSize % 3 !== 0) {
  31957. subdivisionSize++;
  31958. }
  31959. this.releaseSubMeshes();
  31960. for (var index = 0; index < count; index++) {
  31961. if (offset >= totalIndices) {
  31962. break;
  31963. }
  31964. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31965. offset += subdivisionSize;
  31966. }
  31967. this.synchronizeInstances();
  31968. };
  31969. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31970. if (updatable === void 0) { updatable = false; }
  31971. if (!this._geometry) {
  31972. var vertexData = new BABYLON.VertexData();
  31973. vertexData.set(data, kind);
  31974. var scene = this.getScene();
  31975. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31976. }
  31977. else {
  31978. this._geometry.setVerticesData(kind, data, updatable, stride);
  31979. }
  31980. return this;
  31981. };
  31982. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31983. if (updatable === void 0) { updatable = true; }
  31984. var vb = this.getVertexBuffer(kind);
  31985. if (!vb || vb.isUpdatable() === updatable) {
  31986. return;
  31987. }
  31988. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31989. };
  31990. /**
  31991. * Sets the mesh VertexBuffer.
  31992. * Returns the Mesh.
  31993. */
  31994. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31995. if (!this._geometry) {
  31996. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31997. }
  31998. this._geometry.setVerticesBuffer(buffer);
  31999. return this;
  32000. };
  32001. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32002. if (!this._geometry) {
  32003. return this;
  32004. }
  32005. if (!makeItUnique) {
  32006. this._geometry.updateVerticesData(kind, data, updateExtends);
  32007. }
  32008. else {
  32009. this.makeGeometryUnique();
  32010. this.updateVerticesData(kind, data, updateExtends, false);
  32011. }
  32012. return this;
  32013. };
  32014. /**
  32015. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32016. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32017. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32018. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32019. * Returns the Mesh.
  32020. */
  32021. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32022. if (computeNormals === void 0) { computeNormals = true; }
  32023. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32024. if (!positions) {
  32025. return this;
  32026. }
  32027. positionFunction(positions);
  32028. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32029. if (computeNormals) {
  32030. var indices = this.getIndices();
  32031. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32032. if (!normals) {
  32033. return this;
  32034. }
  32035. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32036. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32037. }
  32038. return this;
  32039. };
  32040. /**
  32041. * Creates a un-shared specific occurence of the geometry for the mesh.
  32042. * Returns the Mesh.
  32043. */
  32044. Mesh.prototype.makeGeometryUnique = function () {
  32045. if (!this._geometry) {
  32046. return this;
  32047. }
  32048. var oldGeometry = this._geometry;
  32049. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32050. oldGeometry.releaseForMesh(this, true);
  32051. geometry.applyToMesh(this);
  32052. return this;
  32053. };
  32054. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32055. if (totalVertices === void 0) { totalVertices = null; }
  32056. if (updatable === void 0) { updatable = false; }
  32057. if (!this._geometry) {
  32058. var vertexData = new BABYLON.VertexData();
  32059. vertexData.indices = indices;
  32060. var scene = this.getScene();
  32061. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32062. }
  32063. else {
  32064. this._geometry.setIndices(indices, totalVertices, updatable);
  32065. }
  32066. return this;
  32067. };
  32068. /**
  32069. * Update the current index buffer
  32070. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32071. * Returns the Mesh.
  32072. */
  32073. Mesh.prototype.updateIndices = function (indices, offset) {
  32074. if (!this._geometry) {
  32075. return this;
  32076. }
  32077. this._geometry.updateIndices(indices, offset);
  32078. return this;
  32079. };
  32080. /**
  32081. * Invert the geometry to move from a right handed system to a left handed one.
  32082. * Returns the Mesh.
  32083. */
  32084. Mesh.prototype.toLeftHanded = function () {
  32085. if (!this._geometry) {
  32086. return this;
  32087. }
  32088. this._geometry.toLeftHanded();
  32089. return this;
  32090. };
  32091. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32092. if (!this._geometry) {
  32093. return this;
  32094. }
  32095. var engine = this.getScene().getEngine();
  32096. // Wireframe
  32097. var indexToBind;
  32098. if (this._unIndexed) {
  32099. indexToBind = null;
  32100. }
  32101. else {
  32102. switch (fillMode) {
  32103. case BABYLON.Material.PointFillMode:
  32104. indexToBind = null;
  32105. break;
  32106. case BABYLON.Material.WireFrameFillMode:
  32107. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32108. break;
  32109. default:
  32110. case BABYLON.Material.TriangleFillMode:
  32111. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32112. break;
  32113. }
  32114. }
  32115. // VBOs
  32116. this._geometry._bind(effect, indexToBind);
  32117. return this;
  32118. };
  32119. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32120. if (alternate === void 0) { alternate = false; }
  32121. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32122. return this;
  32123. }
  32124. this.onBeforeDrawObservable.notifyObservers(this);
  32125. var scene = this.getScene();
  32126. var engine = scene.getEngine();
  32127. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32128. // or triangles as points
  32129. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32130. }
  32131. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32132. // Triangles as wireframe
  32133. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32134. }
  32135. else {
  32136. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32137. }
  32138. if (scene._isAlternateRenderingEnabled && !alternate) {
  32139. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32140. if (!effect || !scene.activeCamera) {
  32141. return this;
  32142. }
  32143. scene._switchToAlternateCameraConfiguration(true);
  32144. this._effectiveMaterial.bindView(effect);
  32145. this._effectiveMaterial.bindViewProjection(effect);
  32146. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32147. this._draw(subMesh, fillMode, instancesCount, true);
  32148. engine.setViewport(scene.activeCamera.viewport);
  32149. scene._switchToAlternateCameraConfiguration(false);
  32150. this._effectiveMaterial.bindView(effect);
  32151. this._effectiveMaterial.bindViewProjection(effect);
  32152. }
  32153. return this;
  32154. };
  32155. /**
  32156. * Registers for this mesh a javascript function called just before the rendering process.
  32157. * This function is passed the current mesh.
  32158. * Return the Mesh.
  32159. */
  32160. Mesh.prototype.registerBeforeRender = function (func) {
  32161. this.onBeforeRenderObservable.add(func);
  32162. return this;
  32163. };
  32164. /**
  32165. * Disposes a previously registered javascript function called before the rendering.
  32166. * This function is passed the current mesh.
  32167. * Returns the Mesh.
  32168. */
  32169. Mesh.prototype.unregisterBeforeRender = function (func) {
  32170. this.onBeforeRenderObservable.removeCallback(func);
  32171. return this;
  32172. };
  32173. /**
  32174. * Registers for this mesh a javascript function called just after the rendering is complete.
  32175. * This function is passed the current mesh.
  32176. * Returns the Mesh.
  32177. */
  32178. Mesh.prototype.registerAfterRender = function (func) {
  32179. this.onAfterRenderObservable.add(func);
  32180. return this;
  32181. };
  32182. /**
  32183. * Disposes a previously registered javascript function called after the rendering.
  32184. * This function is passed the current mesh.
  32185. * Return the Mesh.
  32186. */
  32187. Mesh.prototype.unregisterAfterRender = function (func) {
  32188. this.onAfterRenderObservable.removeCallback(func);
  32189. return this;
  32190. };
  32191. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32192. var scene = this.getScene();
  32193. this._batchCache.mustReturn = false;
  32194. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32195. this._batchCache.visibleInstances[subMeshId] = null;
  32196. if (this._visibleInstances) {
  32197. var currentRenderId = scene.getRenderId();
  32198. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32199. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32200. var selfRenderId = this._renderId;
  32201. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32202. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32203. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32204. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32205. }
  32206. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32207. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32208. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32209. this._batchCache.mustReturn = true;
  32210. return this._batchCache;
  32211. }
  32212. if (currentRenderId !== selfRenderId) {
  32213. this._batchCache.renderSelf[subMeshId] = false;
  32214. }
  32215. }
  32216. this._renderIdForInstances[subMeshId] = currentRenderId;
  32217. }
  32218. return this._batchCache;
  32219. };
  32220. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32221. var visibleInstances = batch.visibleInstances[subMesh._id];
  32222. if (!visibleInstances) {
  32223. return this;
  32224. }
  32225. var matricesCount = visibleInstances.length + 1;
  32226. var bufferSize = matricesCount * 16 * 4;
  32227. var currentInstancesBufferSize = this._instancesBufferSize;
  32228. var instancesBuffer = this._instancesBuffer;
  32229. while (this._instancesBufferSize < bufferSize) {
  32230. this._instancesBufferSize *= 2;
  32231. }
  32232. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32233. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32234. }
  32235. var offset = 0;
  32236. var instancesCount = 0;
  32237. var world = this.getWorldMatrix();
  32238. if (batch.renderSelf[subMesh._id]) {
  32239. world.copyToArray(this._instancesData, offset);
  32240. offset += 16;
  32241. instancesCount++;
  32242. }
  32243. if (visibleInstances) {
  32244. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32245. var instance = visibleInstances[instanceIndex];
  32246. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32247. offset += 16;
  32248. instancesCount++;
  32249. }
  32250. }
  32251. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32252. if (instancesBuffer) {
  32253. instancesBuffer.dispose();
  32254. }
  32255. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32256. this._instancesBuffer = instancesBuffer;
  32257. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32258. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32259. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32260. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32261. }
  32262. else {
  32263. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32264. }
  32265. this._bind(subMesh, effect, fillMode);
  32266. this._draw(subMesh, fillMode, instancesCount);
  32267. engine.unbindInstanceAttributes();
  32268. return this;
  32269. };
  32270. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32271. var scene = this.getScene();
  32272. var engine = scene.getEngine();
  32273. if (hardwareInstancedRendering) {
  32274. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32275. }
  32276. else {
  32277. if (batch.renderSelf[subMesh._id]) {
  32278. // Draw
  32279. if (onBeforeDraw) {
  32280. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32281. }
  32282. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32283. }
  32284. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32285. if (visibleInstancesForSubMesh) {
  32286. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32287. var instance = visibleInstancesForSubMesh[instanceIndex];
  32288. // World
  32289. var world = instance.getWorldMatrix();
  32290. if (onBeforeDraw) {
  32291. onBeforeDraw(true, world, effectiveMaterial);
  32292. }
  32293. // Draw
  32294. this._draw(subMesh, fillMode);
  32295. }
  32296. }
  32297. }
  32298. return this;
  32299. };
  32300. /**
  32301. * Triggers the draw call for the mesh.
  32302. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32303. * Returns the Mesh.
  32304. */
  32305. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32306. this._checkOcclusionQuery();
  32307. if (this._isOccluded) {
  32308. return this;
  32309. }
  32310. var scene = this.getScene();
  32311. // Managing instances
  32312. var batch = this._getInstancesRenderList(subMesh._id);
  32313. if (batch.mustReturn) {
  32314. return this;
  32315. }
  32316. // Checking geometry state
  32317. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32318. return this;
  32319. }
  32320. this.onBeforeRenderObservable.notifyObservers(this);
  32321. var engine = scene.getEngine();
  32322. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32323. // Material
  32324. var material = subMesh.getMaterial();
  32325. if (!material) {
  32326. return this;
  32327. }
  32328. this._effectiveMaterial = material;
  32329. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32330. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32331. return this;
  32332. }
  32333. }
  32334. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32335. return this;
  32336. }
  32337. // Alpha mode
  32338. if (enableAlphaMode) {
  32339. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32340. }
  32341. // Outline - step 1
  32342. var savedDepthWrite = engine.getDepthWrite();
  32343. if (this.renderOutline) {
  32344. engine.setDepthWrite(false);
  32345. scene.getOutlineRenderer().render(subMesh, batch);
  32346. engine.setDepthWrite(savedDepthWrite);
  32347. }
  32348. var effect;
  32349. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32350. effect = subMesh.effect;
  32351. }
  32352. else {
  32353. effect = this._effectiveMaterial.getEffect();
  32354. }
  32355. if (!effect) {
  32356. return this;
  32357. }
  32358. var sideOrientation = this.overrideMaterialSideOrientation;
  32359. if (sideOrientation == null) {
  32360. sideOrientation = this._effectiveMaterial.sideOrientation;
  32361. if (this._getWorldMatrixDeterminant() < 0) {
  32362. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32363. }
  32364. }
  32365. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32366. if (this._effectiveMaterial.forceDepthWrite) {
  32367. engine.setDepthWrite(true);
  32368. }
  32369. // Bind
  32370. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32371. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32372. this._bind(subMesh, effect, fillMode);
  32373. }
  32374. var world = this.getWorldMatrix();
  32375. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32376. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32377. }
  32378. else {
  32379. this._effectiveMaterial.bind(world, this);
  32380. }
  32381. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32382. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32383. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32384. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32385. }
  32386. // Draw
  32387. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32388. // Unbind
  32389. this._effectiveMaterial.unbind();
  32390. // Outline - step 2
  32391. if (this.renderOutline && savedDepthWrite) {
  32392. engine.setDepthWrite(true);
  32393. engine.setColorWrite(false);
  32394. scene.getOutlineRenderer().render(subMesh, batch);
  32395. engine.setColorWrite(true);
  32396. }
  32397. // Overlay
  32398. if (this.renderOverlay) {
  32399. var currentMode = engine.getAlphaMode();
  32400. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32401. scene.getOutlineRenderer().render(subMesh, batch, true);
  32402. engine.setAlphaMode(currentMode);
  32403. }
  32404. this.onAfterRenderObservable.notifyObservers(this);
  32405. return this;
  32406. };
  32407. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32408. if (isInstance && effectiveMaterial) {
  32409. effectiveMaterial.bindOnlyWorldMatrix(world);
  32410. }
  32411. };
  32412. /**
  32413. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32414. */
  32415. Mesh.prototype.getEmittedParticleSystems = function () {
  32416. var results = new Array();
  32417. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32418. var particleSystem = this.getScene().particleSystems[index];
  32419. if (particleSystem.emitter === this) {
  32420. results.push(particleSystem);
  32421. }
  32422. }
  32423. return results;
  32424. };
  32425. /**
  32426. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32427. */
  32428. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32429. var results = new Array();
  32430. var descendants = this.getDescendants();
  32431. descendants.push(this);
  32432. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32433. var particleSystem = this.getScene().particleSystems[index];
  32434. var emitter = particleSystem.emitter;
  32435. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32436. results.push(particleSystem);
  32437. }
  32438. }
  32439. return results;
  32440. };
  32441. /**
  32442. * Normalize matrix weights so that all vertices have a total weight set to 1
  32443. */
  32444. Mesh.prototype.cleanMatrixWeights = function () {
  32445. var epsilon = 1e-3;
  32446. var noInfluenceBoneIndex = 0.0;
  32447. if (this.skeleton) {
  32448. noInfluenceBoneIndex = this.skeleton.bones.length;
  32449. }
  32450. else {
  32451. return;
  32452. }
  32453. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32454. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32455. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32456. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32457. var influencers = this.numBoneInfluencers;
  32458. var size = matricesWeights.length;
  32459. for (var i = 0; i < size; i += 4) {
  32460. var weight = 0.0;
  32461. var firstZeroWeight = -1;
  32462. for (var j = 0; j < 4; j++) {
  32463. var w = matricesWeights[i + j];
  32464. weight += w;
  32465. if (w < epsilon && firstZeroWeight < 0) {
  32466. firstZeroWeight = j;
  32467. }
  32468. }
  32469. if (matricesWeightsExtra) {
  32470. for (var j = 0; j < 4; j++) {
  32471. var w = matricesWeightsExtra[i + j];
  32472. weight += w;
  32473. if (w < epsilon && firstZeroWeight < 0) {
  32474. firstZeroWeight = j + 4;
  32475. }
  32476. }
  32477. }
  32478. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32479. firstZeroWeight = influencers - 1;
  32480. }
  32481. if (weight > epsilon) {
  32482. var mweight = 1.0 / weight;
  32483. for (var j = 0; j < 4; j++) {
  32484. matricesWeights[i + j] *= mweight;
  32485. }
  32486. if (matricesWeightsExtra) {
  32487. for (var j = 0; j < 4; j++) {
  32488. matricesWeightsExtra[i + j] *= mweight;
  32489. }
  32490. }
  32491. }
  32492. else {
  32493. if (firstZeroWeight >= 4) {
  32494. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32495. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32496. }
  32497. else {
  32498. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32499. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32500. }
  32501. }
  32502. }
  32503. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32504. if (matricesIndicesExtra) {
  32505. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32506. }
  32507. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32508. if (matricesWeightsExtra) {
  32509. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32510. }
  32511. };
  32512. Mesh.prototype._checkDelayState = function () {
  32513. var scene = this.getScene();
  32514. if (this._geometry) {
  32515. this._geometry.load(scene);
  32516. }
  32517. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32518. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32519. this._queueLoad(scene);
  32520. }
  32521. return this;
  32522. };
  32523. Mesh.prototype._queueLoad = function (scene) {
  32524. var _this = this;
  32525. scene._addPendingData(this);
  32526. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32527. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32528. if (data instanceof ArrayBuffer) {
  32529. _this._delayLoadingFunction(data, _this);
  32530. }
  32531. else {
  32532. _this._delayLoadingFunction(JSON.parse(data), _this);
  32533. }
  32534. _this.instances.forEach(function (instance) {
  32535. instance._syncSubMeshes();
  32536. });
  32537. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32538. scene._removePendingData(_this);
  32539. }, function () { }, scene.database, getBinaryData);
  32540. return this;
  32541. };
  32542. /**
  32543. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32544. */
  32545. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32546. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32547. return false;
  32548. }
  32549. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32550. return false;
  32551. }
  32552. this._checkDelayState();
  32553. return true;
  32554. };
  32555. /**
  32556. * Sets the mesh material by the material or multiMaterial `id` property.
  32557. * The material `id` is a string identifying the material or the multiMaterial.
  32558. * This method returns the Mesh.
  32559. */
  32560. Mesh.prototype.setMaterialByID = function (id) {
  32561. var materials = this.getScene().materials;
  32562. var index;
  32563. for (index = materials.length - 1; index > -1; index--) {
  32564. if (materials[index].id === id) {
  32565. this.material = materials[index];
  32566. return this;
  32567. }
  32568. }
  32569. // Multi
  32570. var multiMaterials = this.getScene().multiMaterials;
  32571. for (index = multiMaterials.length - 1; index > -1; index--) {
  32572. if (multiMaterials[index].id === id) {
  32573. this.material = multiMaterials[index];
  32574. return this;
  32575. }
  32576. }
  32577. return this;
  32578. };
  32579. /**
  32580. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32581. */
  32582. Mesh.prototype.getAnimatables = function () {
  32583. var results = new Array();
  32584. if (this.material) {
  32585. results.push(this.material);
  32586. }
  32587. if (this.skeleton) {
  32588. results.push(this.skeleton);
  32589. }
  32590. return results;
  32591. };
  32592. /**
  32593. * Modifies the mesh geometry according to the passed transformation matrix.
  32594. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32595. * The mesh normals are modified accordingly the same transformation.
  32596. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32597. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32598. * Returns the Mesh.
  32599. */
  32600. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32601. // Position
  32602. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32603. return this;
  32604. }
  32605. var submeshes = this.subMeshes.splice(0);
  32606. this._resetPointsArrayCache();
  32607. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32608. var temp = new Array();
  32609. var index;
  32610. for (index = 0; index < data.length; index += 3) {
  32611. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32612. }
  32613. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32614. // Normals
  32615. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32616. return this;
  32617. }
  32618. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32619. temp = [];
  32620. for (index = 0; index < data.length; index += 3) {
  32621. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32622. }
  32623. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32624. // flip faces?
  32625. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32626. this.flipFaces();
  32627. }
  32628. // Restore submeshes
  32629. this.releaseSubMeshes();
  32630. this.subMeshes = submeshes;
  32631. return this;
  32632. };
  32633. /**
  32634. * Modifies the mesh geometry according to its own current World Matrix.
  32635. * The mesh World Matrix is then reset.
  32636. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32637. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32638. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32639. * Returns the Mesh.
  32640. */
  32641. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32642. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32643. this.scaling.copyFromFloats(1, 1, 1);
  32644. this.position.copyFromFloats(0, 0, 0);
  32645. this.rotation.copyFromFloats(0, 0, 0);
  32646. //only if quaternion is already set
  32647. if (this.rotationQuaternion) {
  32648. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32649. }
  32650. this._worldMatrix = BABYLON.Matrix.Identity();
  32651. return this;
  32652. };
  32653. Object.defineProperty(Mesh.prototype, "_positions", {
  32654. // Cache
  32655. get: function () {
  32656. if (this._geometry) {
  32657. return this._geometry._positions;
  32658. }
  32659. return null;
  32660. },
  32661. enumerable: true,
  32662. configurable: true
  32663. });
  32664. Mesh.prototype._resetPointsArrayCache = function () {
  32665. if (this._geometry) {
  32666. this._geometry._resetPointsArrayCache();
  32667. }
  32668. return this;
  32669. };
  32670. Mesh.prototype._generatePointsArray = function () {
  32671. if (this._geometry) {
  32672. return this._geometry._generatePointsArray();
  32673. }
  32674. return false;
  32675. };
  32676. /**
  32677. * Returns a new Mesh object generated from the current mesh properties.
  32678. * This method must not get confused with createInstance().
  32679. * The parameter `name` is a string, the name given to the new mesh.
  32680. * The optional parameter `newParent` can be any Node object (default `null`).
  32681. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32682. * 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.
  32683. */
  32684. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32685. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32686. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32687. };
  32688. /**
  32689. * Releases resources associated with this mesh.
  32690. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32691. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32692. */
  32693. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32694. var _this = this;
  32695. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32696. this.morphTargetManager = null;
  32697. if (this._geometry) {
  32698. this._geometry.releaseForMesh(this, true);
  32699. }
  32700. // Sources
  32701. var meshes = this.getScene().meshes;
  32702. meshes.forEach(function (abstractMesh) {
  32703. var mesh = abstractMesh;
  32704. if (mesh._source && mesh._source === _this) {
  32705. mesh._source = null;
  32706. }
  32707. });
  32708. this._source = null;
  32709. // Instances
  32710. if (this._instancesBuffer) {
  32711. this._instancesBuffer.dispose();
  32712. this._instancesBuffer = null;
  32713. }
  32714. while (this.instances.length) {
  32715. this.instances[0].dispose();
  32716. }
  32717. // Effect layers.
  32718. var effectLayers = this.getScene().effectLayers;
  32719. for (var i = 0; i < effectLayers.length; i++) {
  32720. var effectLayer = effectLayers[i];
  32721. if (effectLayer) {
  32722. effectLayer._disposeMesh(this);
  32723. }
  32724. }
  32725. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32726. };
  32727. /**
  32728. * Modifies the mesh geometry according to a displacement map.
  32729. * 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.
  32730. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32731. * This method returns nothing.
  32732. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32733. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32734. * 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.
  32735. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32736. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32737. *
  32738. * Returns the Mesh.
  32739. */
  32740. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32741. var _this = this;
  32742. var scene = this.getScene();
  32743. var onload = function (img) {
  32744. // Getting height map data
  32745. var canvas = document.createElement("canvas");
  32746. var context = canvas.getContext("2d");
  32747. var heightMapWidth = img.width;
  32748. var heightMapHeight = img.height;
  32749. canvas.width = heightMapWidth;
  32750. canvas.height = heightMapHeight;
  32751. context.drawImage(img, 0, 0);
  32752. // Create VertexData from map data
  32753. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32754. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32755. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32756. //execute success callback, if set
  32757. if (onSuccess) {
  32758. onSuccess(_this);
  32759. }
  32760. };
  32761. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32762. return this;
  32763. };
  32764. /**
  32765. * Modifies the mesh geometry according to a displacementMap buffer.
  32766. * 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.
  32767. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32768. * This method returns nothing.
  32769. * 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.
  32770. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32771. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32772. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32773. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32774. *
  32775. * Returns the Mesh.
  32776. */
  32777. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32778. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32779. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32780. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32781. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32782. return this;
  32783. }
  32784. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32785. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32786. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32787. var position = BABYLON.Vector3.Zero();
  32788. var normal = BABYLON.Vector3.Zero();
  32789. var uv = BABYLON.Vector2.Zero();
  32790. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32791. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32792. for (var index = 0; index < positions.length; index += 3) {
  32793. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32794. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32795. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32796. // Compute height
  32797. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32798. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32799. var pos = (u + v * heightMapWidth) * 4;
  32800. var r = buffer[pos] / 255.0;
  32801. var g = buffer[pos + 1] / 255.0;
  32802. var b = buffer[pos + 2] / 255.0;
  32803. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32804. normal.normalize();
  32805. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32806. position = position.add(normal);
  32807. position.toArray(positions, index);
  32808. }
  32809. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32810. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32811. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32812. return this;
  32813. };
  32814. /**
  32815. * Modify the mesh to get a flat shading rendering.
  32816. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32817. * This method returns the Mesh.
  32818. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32819. */
  32820. Mesh.prototype.convertToFlatShadedMesh = function () {
  32821. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32822. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32823. var kinds = this.getVerticesDataKinds();
  32824. var vbs = {};
  32825. var data = {};
  32826. var newdata = {};
  32827. var updatableNormals = false;
  32828. var kindIndex;
  32829. var kind;
  32830. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32831. kind = kinds[kindIndex];
  32832. var vertexBuffer = this.getVertexBuffer(kind);
  32833. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32834. updatableNormals = vertexBuffer.isUpdatable();
  32835. kinds.splice(kindIndex, 1);
  32836. kindIndex--;
  32837. continue;
  32838. }
  32839. vbs[kind] = vertexBuffer;
  32840. data[kind] = vbs[kind].getData();
  32841. newdata[kind] = [];
  32842. }
  32843. // Save previous submeshes
  32844. var previousSubmeshes = this.subMeshes.slice(0);
  32845. var indices = this.getIndices();
  32846. var totalIndices = this.getTotalIndices();
  32847. // Generating unique vertices per face
  32848. var index;
  32849. for (index = 0; index < totalIndices; index++) {
  32850. var vertexIndex = indices[index];
  32851. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32852. kind = kinds[kindIndex];
  32853. var stride = vbs[kind].getStrideSize();
  32854. for (var offset = 0; offset < stride; offset++) {
  32855. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32856. }
  32857. }
  32858. }
  32859. // Updating faces & normal
  32860. var normals = [];
  32861. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32862. for (index = 0; index < totalIndices; index += 3) {
  32863. indices[index] = index;
  32864. indices[index + 1] = index + 1;
  32865. indices[index + 2] = index + 2;
  32866. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32867. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32868. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32869. var p1p2 = p1.subtract(p2);
  32870. var p3p2 = p3.subtract(p2);
  32871. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32872. // Store same normals for every vertex
  32873. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32874. normals.push(normal.x);
  32875. normals.push(normal.y);
  32876. normals.push(normal.z);
  32877. }
  32878. }
  32879. this.setIndices(indices);
  32880. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32881. // Updating vertex buffers
  32882. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32883. kind = kinds[kindIndex];
  32884. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32885. }
  32886. // Updating submeshes
  32887. this.releaseSubMeshes();
  32888. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32889. var previousOne = previousSubmeshes[submeshIndex];
  32890. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32891. }
  32892. this.synchronizeInstances();
  32893. return this;
  32894. };
  32895. /**
  32896. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32897. * In other words, more vertices, no more indices and a single bigger VBO.
  32898. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32899. * Returns the Mesh.
  32900. */
  32901. Mesh.prototype.convertToUnIndexedMesh = function () {
  32902. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32903. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32904. var kinds = this.getVerticesDataKinds();
  32905. var vbs = {};
  32906. var data = {};
  32907. var newdata = {};
  32908. var kindIndex;
  32909. var kind;
  32910. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32911. kind = kinds[kindIndex];
  32912. var vertexBuffer = this.getVertexBuffer(kind);
  32913. vbs[kind] = vertexBuffer;
  32914. data[kind] = vbs[kind].getData();
  32915. newdata[kind] = [];
  32916. }
  32917. // Save previous submeshes
  32918. var previousSubmeshes = this.subMeshes.slice(0);
  32919. var indices = this.getIndices();
  32920. var totalIndices = this.getTotalIndices();
  32921. // Generating unique vertices per face
  32922. var index;
  32923. for (index = 0; index < totalIndices; index++) {
  32924. var vertexIndex = indices[index];
  32925. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32926. kind = kinds[kindIndex];
  32927. var stride = vbs[kind].getStrideSize();
  32928. for (var offset = 0; offset < stride; offset++) {
  32929. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32930. }
  32931. }
  32932. }
  32933. // Updating indices
  32934. for (index = 0; index < totalIndices; index += 3) {
  32935. indices[index] = index;
  32936. indices[index + 1] = index + 1;
  32937. indices[index + 2] = index + 2;
  32938. }
  32939. this.setIndices(indices);
  32940. // Updating vertex buffers
  32941. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32942. kind = kinds[kindIndex];
  32943. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32944. }
  32945. // Updating submeshes
  32946. this.releaseSubMeshes();
  32947. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32948. var previousOne = previousSubmeshes[submeshIndex];
  32949. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32950. }
  32951. this._unIndexed = true;
  32952. this.synchronizeInstances();
  32953. return this;
  32954. };
  32955. /**
  32956. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32957. * This method returns the Mesh.
  32958. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32959. */
  32960. Mesh.prototype.flipFaces = function (flipNormals) {
  32961. if (flipNormals === void 0) { flipNormals = false; }
  32962. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32963. var i;
  32964. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32965. for (i = 0; i < vertex_data.normals.length; i++) {
  32966. vertex_data.normals[i] *= -1;
  32967. }
  32968. }
  32969. if (vertex_data.indices) {
  32970. var temp;
  32971. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32972. // reassign indices
  32973. temp = vertex_data.indices[i + 1];
  32974. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32975. vertex_data.indices[i + 2] = temp;
  32976. }
  32977. }
  32978. vertex_data.applyToMesh(this);
  32979. return this;
  32980. };
  32981. // Instances
  32982. /**
  32983. * Creates a new InstancedMesh object from the mesh model.
  32984. * An instance shares the same properties and the same material than its model.
  32985. * Only these properties of each instance can then be set individually :
  32986. * - position
  32987. * - rotation
  32988. * - rotationQuaternion
  32989. * - setPivotMatrix
  32990. * - scaling
  32991. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32992. * Warning : this method is not supported for Line mesh and LineSystem
  32993. */
  32994. Mesh.prototype.createInstance = function (name) {
  32995. return new BABYLON.InstancedMesh(name, this);
  32996. };
  32997. /**
  32998. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32999. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33000. * This method returns the Mesh.
  33001. */
  33002. Mesh.prototype.synchronizeInstances = function () {
  33003. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33004. var instance = this.instances[instanceIndex];
  33005. instance._syncSubMeshes();
  33006. }
  33007. return this;
  33008. };
  33009. /**
  33010. * Simplify the mesh according to the given array of settings.
  33011. * Function will return immediately and will simplify async. It returns the Mesh.
  33012. * @param settings a collection of simplification settings.
  33013. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33014. * @param type the type of simplification to run.
  33015. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33016. */
  33017. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33018. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33019. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33020. this.getScene().simplificationQueue.addTask({
  33021. settings: settings,
  33022. parallelProcessing: parallelProcessing,
  33023. mesh: this,
  33024. simplificationType: simplificationType,
  33025. successCallback: successCallback
  33026. });
  33027. return this;
  33028. };
  33029. /**
  33030. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33031. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33032. * This should be used together with the simplification to avoid disappearing triangles.
  33033. * Returns the Mesh.
  33034. * @param successCallback an optional success callback to be called after the optimization finished.
  33035. */
  33036. Mesh.prototype.optimizeIndices = function (successCallback) {
  33037. var _this = this;
  33038. var indices = this.getIndices();
  33039. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33040. if (!positions || !indices) {
  33041. return this;
  33042. }
  33043. var vectorPositions = new Array();
  33044. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33045. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33046. }
  33047. var dupes = new Array();
  33048. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33049. var realPos = vectorPositions.length - 1 - iteration;
  33050. var testedPosition = vectorPositions[realPos];
  33051. for (var j = 0; j < realPos; ++j) {
  33052. var againstPosition = vectorPositions[j];
  33053. if (testedPosition.equals(againstPosition)) {
  33054. dupes[realPos] = j;
  33055. break;
  33056. }
  33057. }
  33058. }, function () {
  33059. for (var i = 0; i < indices.length; ++i) {
  33060. indices[i] = dupes[indices[i]] || indices[i];
  33061. }
  33062. //indices are now reordered
  33063. var originalSubMeshes = _this.subMeshes.slice(0);
  33064. _this.setIndices(indices);
  33065. _this.subMeshes = originalSubMeshes;
  33066. if (successCallback) {
  33067. successCallback(_this);
  33068. }
  33069. });
  33070. return this;
  33071. };
  33072. Mesh.prototype.serialize = function (serializationObject) {
  33073. serializationObject.name = this.name;
  33074. serializationObject.id = this.id;
  33075. serializationObject.type = this.getClassName();
  33076. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33077. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33078. }
  33079. serializationObject.position = this.position.asArray();
  33080. if (this.rotationQuaternion) {
  33081. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33082. }
  33083. else if (this.rotation) {
  33084. serializationObject.rotation = this.rotation.asArray();
  33085. }
  33086. serializationObject.scaling = this.scaling.asArray();
  33087. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33088. serializationObject.isEnabled = this.isEnabled(false);
  33089. serializationObject.isVisible = this.isVisible;
  33090. serializationObject.infiniteDistance = this.infiniteDistance;
  33091. serializationObject.pickable = this.isPickable;
  33092. serializationObject.receiveShadows = this.receiveShadows;
  33093. serializationObject.billboardMode = this.billboardMode;
  33094. serializationObject.visibility = this.visibility;
  33095. serializationObject.checkCollisions = this.checkCollisions;
  33096. serializationObject.isBlocker = this.isBlocker;
  33097. // Parent
  33098. if (this.parent) {
  33099. serializationObject.parentId = this.parent.id;
  33100. }
  33101. // Geometry
  33102. serializationObject.isUnIndexed = this.isUnIndexed;
  33103. var geometry = this._geometry;
  33104. if (geometry) {
  33105. var geometryId = geometry.id;
  33106. serializationObject.geometryId = geometryId;
  33107. // SubMeshes
  33108. serializationObject.subMeshes = [];
  33109. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33110. var subMesh = this.subMeshes[subIndex];
  33111. serializationObject.subMeshes.push({
  33112. materialIndex: subMesh.materialIndex,
  33113. verticesStart: subMesh.verticesStart,
  33114. verticesCount: subMesh.verticesCount,
  33115. indexStart: subMesh.indexStart,
  33116. indexCount: subMesh.indexCount
  33117. });
  33118. }
  33119. }
  33120. // Material
  33121. if (this.material) {
  33122. serializationObject.materialId = this.material.id;
  33123. }
  33124. else {
  33125. this.material = null;
  33126. }
  33127. // Morph targets
  33128. if (this.morphTargetManager) {
  33129. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33130. }
  33131. // Skeleton
  33132. if (this.skeleton) {
  33133. serializationObject.skeletonId = this.skeleton.id;
  33134. }
  33135. // Physics
  33136. //TODO implement correct serialization for physics impostors.
  33137. var impostor = this.getPhysicsImpostor();
  33138. if (impostor) {
  33139. serializationObject.physicsMass = impostor.getParam("mass");
  33140. serializationObject.physicsFriction = impostor.getParam("friction");
  33141. serializationObject.physicsRestitution = impostor.getParam("mass");
  33142. serializationObject.physicsImpostor = impostor.type;
  33143. }
  33144. // Metadata
  33145. if (this.metadata) {
  33146. serializationObject.metadata = this.metadata;
  33147. }
  33148. // Instances
  33149. serializationObject.instances = [];
  33150. for (var index = 0; index < this.instances.length; index++) {
  33151. var instance = this.instances[index];
  33152. var serializationInstance = {
  33153. name: instance.name,
  33154. id: instance.id,
  33155. position: instance.position.asArray(),
  33156. scaling: instance.scaling.asArray()
  33157. };
  33158. if (instance.rotationQuaternion) {
  33159. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33160. }
  33161. else if (instance.rotation) {
  33162. serializationInstance.rotation = instance.rotation.asArray();
  33163. }
  33164. serializationObject.instances.push(serializationInstance);
  33165. // Animations
  33166. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33167. serializationInstance.ranges = instance.serializeAnimationRanges();
  33168. }
  33169. //
  33170. // Animations
  33171. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33172. serializationObject.ranges = this.serializeAnimationRanges();
  33173. // Layer mask
  33174. serializationObject.layerMask = this.layerMask;
  33175. // Alpha
  33176. serializationObject.alphaIndex = this.alphaIndex;
  33177. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33178. // Overlay
  33179. serializationObject.overlayAlpha = this.overlayAlpha;
  33180. serializationObject.overlayColor = this.overlayColor.asArray();
  33181. serializationObject.renderOverlay = this.renderOverlay;
  33182. // Fog
  33183. serializationObject.applyFog = this.applyFog;
  33184. // Action Manager
  33185. if (this.actionManager) {
  33186. serializationObject.actions = this.actionManager.serialize(this.name);
  33187. }
  33188. };
  33189. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33190. if (!this.geometry) {
  33191. return;
  33192. }
  33193. this._markSubMeshesAsAttributesDirty();
  33194. var morphTargetManager = this._morphTargetManager;
  33195. if (morphTargetManager && morphTargetManager.vertexCount) {
  33196. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33197. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33198. this.morphTargetManager = null;
  33199. return;
  33200. }
  33201. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33202. var morphTarget = morphTargetManager.getActiveTarget(index);
  33203. var positions = morphTarget.getPositions();
  33204. if (!positions) {
  33205. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33206. return;
  33207. }
  33208. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33209. var normals = morphTarget.getNormals();
  33210. if (normals) {
  33211. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33212. }
  33213. var tangents = morphTarget.getTangents();
  33214. if (tangents) {
  33215. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33216. }
  33217. }
  33218. }
  33219. else {
  33220. var index = 0;
  33221. // Positions
  33222. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33223. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33224. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33225. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33226. }
  33227. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33228. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33229. }
  33230. index++;
  33231. }
  33232. }
  33233. };
  33234. // Statics
  33235. /**
  33236. * Returns a new Mesh object parsed from the source provided.
  33237. * The parameter `parsedMesh` is the source.
  33238. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33239. */
  33240. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33241. var mesh;
  33242. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33243. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33244. }
  33245. else {
  33246. mesh = new Mesh(parsedMesh.name, scene);
  33247. }
  33248. mesh.id = parsedMesh.id;
  33249. if (BABYLON.Tags) {
  33250. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33251. }
  33252. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33253. if (parsedMesh.metadata !== undefined) {
  33254. mesh.metadata = parsedMesh.metadata;
  33255. }
  33256. if (parsedMesh.rotationQuaternion) {
  33257. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33258. }
  33259. else if (parsedMesh.rotation) {
  33260. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33261. }
  33262. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33263. if (parsedMesh.localMatrix) {
  33264. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33265. }
  33266. else if (parsedMesh.pivotMatrix) {
  33267. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33268. }
  33269. mesh.setEnabled(parsedMesh.isEnabled);
  33270. mesh.isVisible = parsedMesh.isVisible;
  33271. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33272. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33273. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33274. if (parsedMesh.applyFog !== undefined) {
  33275. mesh.applyFog = parsedMesh.applyFog;
  33276. }
  33277. if (parsedMesh.pickable !== undefined) {
  33278. mesh.isPickable = parsedMesh.pickable;
  33279. }
  33280. if (parsedMesh.alphaIndex !== undefined) {
  33281. mesh.alphaIndex = parsedMesh.alphaIndex;
  33282. }
  33283. mesh.receiveShadows = parsedMesh.receiveShadows;
  33284. mesh.billboardMode = parsedMesh.billboardMode;
  33285. if (parsedMesh.visibility !== undefined) {
  33286. mesh.visibility = parsedMesh.visibility;
  33287. }
  33288. mesh.checkCollisions = parsedMesh.checkCollisions;
  33289. if (parsedMesh.isBlocker !== undefined) {
  33290. mesh.isBlocker = parsedMesh.isBlocker;
  33291. }
  33292. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33293. // freezeWorldMatrix
  33294. if (parsedMesh.freezeWorldMatrix) {
  33295. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33296. }
  33297. // Parent
  33298. if (parsedMesh.parentId) {
  33299. mesh._waitingParentId = parsedMesh.parentId;
  33300. }
  33301. // Actions
  33302. if (parsedMesh.actions !== undefined) {
  33303. mesh._waitingActions = parsedMesh.actions;
  33304. }
  33305. // Overlay
  33306. if (parsedMesh.overlayAlpha !== undefined) {
  33307. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33308. }
  33309. if (parsedMesh.overlayColor !== undefined) {
  33310. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33311. }
  33312. if (parsedMesh.renderOverlay !== undefined) {
  33313. mesh.renderOverlay = parsedMesh.renderOverlay;
  33314. }
  33315. // Geometry
  33316. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33317. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33318. if (parsedMesh.delayLoadingFile) {
  33319. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33320. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33321. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33322. if (parsedMesh._binaryInfo) {
  33323. mesh._binaryInfo = parsedMesh._binaryInfo;
  33324. }
  33325. mesh._delayInfo = [];
  33326. if (parsedMesh.hasUVs) {
  33327. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33328. }
  33329. if (parsedMesh.hasUVs2) {
  33330. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33331. }
  33332. if (parsedMesh.hasUVs3) {
  33333. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33334. }
  33335. if (parsedMesh.hasUVs4) {
  33336. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33337. }
  33338. if (parsedMesh.hasUVs5) {
  33339. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33340. }
  33341. if (parsedMesh.hasUVs6) {
  33342. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33343. }
  33344. if (parsedMesh.hasColors) {
  33345. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33346. }
  33347. if (parsedMesh.hasMatricesIndices) {
  33348. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33349. }
  33350. if (parsedMesh.hasMatricesWeights) {
  33351. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33352. }
  33353. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33354. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33355. mesh._checkDelayState();
  33356. }
  33357. }
  33358. else {
  33359. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33360. }
  33361. // Material
  33362. if (parsedMesh.materialId) {
  33363. mesh.setMaterialByID(parsedMesh.materialId);
  33364. }
  33365. else {
  33366. mesh.material = null;
  33367. }
  33368. // Morph targets
  33369. if (parsedMesh.morphTargetManagerId > -1) {
  33370. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33371. }
  33372. // Skeleton
  33373. if (parsedMesh.skeletonId > -1) {
  33374. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33375. if (parsedMesh.numBoneInfluencers) {
  33376. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33377. }
  33378. }
  33379. // Animations
  33380. if (parsedMesh.animations) {
  33381. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33382. var parsedAnimation = parsedMesh.animations[animationIndex];
  33383. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33384. }
  33385. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33386. }
  33387. if (parsedMesh.autoAnimate) {
  33388. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33389. }
  33390. // Layer Mask
  33391. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33392. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33393. }
  33394. else {
  33395. mesh.layerMask = 0x0FFFFFFF;
  33396. }
  33397. // Physics
  33398. if (parsedMesh.physicsImpostor) {
  33399. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33400. mass: parsedMesh.physicsMass,
  33401. friction: parsedMesh.physicsFriction,
  33402. restitution: parsedMesh.physicsRestitution
  33403. }, scene);
  33404. }
  33405. // Instances
  33406. if (parsedMesh.instances) {
  33407. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33408. var parsedInstance = parsedMesh.instances[index];
  33409. var instance = mesh.createInstance(parsedInstance.name);
  33410. if (parsedInstance.id) {
  33411. instance.id = parsedInstance.id;
  33412. }
  33413. if (BABYLON.Tags) {
  33414. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33415. }
  33416. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33417. if (parsedInstance.parentId) {
  33418. instance._waitingParentId = parsedInstance.parentId;
  33419. }
  33420. if (parsedInstance.rotationQuaternion) {
  33421. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33422. }
  33423. else if (parsedInstance.rotation) {
  33424. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33425. }
  33426. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33427. instance.checkCollisions = mesh.checkCollisions;
  33428. if (parsedMesh.animations) {
  33429. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33430. parsedAnimation = parsedMesh.animations[animationIndex];
  33431. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33432. }
  33433. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33434. }
  33435. }
  33436. }
  33437. return mesh;
  33438. };
  33439. /**
  33440. * Creates a ribbon mesh.
  33441. * Please consider using the same method from the MeshBuilder class instead.
  33442. * 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.
  33443. *
  33444. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33445. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33446. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33447. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33448. * 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.
  33449. * 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.
  33450. * 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
  33451. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33452. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33454. */
  33455. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33456. if (closeArray === void 0) { closeArray = false; }
  33457. if (updatable === void 0) { updatable = false; }
  33458. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33459. pathArray: pathArray,
  33460. closeArray: closeArray,
  33461. closePath: closePath,
  33462. offset: offset,
  33463. updatable: updatable,
  33464. sideOrientation: sideOrientation,
  33465. instance: instance
  33466. }, scene);
  33467. };
  33468. /**
  33469. * Creates a plane polygonal mesh. By default, this is a disc.
  33470. * Please consider using the same method from the MeshBuilder class instead.
  33471. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33472. * 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.
  33473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33474. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33476. */
  33477. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33478. if (scene === void 0) { scene = null; }
  33479. var options = {
  33480. radius: radius,
  33481. tessellation: tessellation,
  33482. sideOrientation: sideOrientation,
  33483. updatable: updatable
  33484. };
  33485. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33486. };
  33487. /**
  33488. * Creates a box mesh.
  33489. * Please consider using the same method from the MeshBuilder class instead.
  33490. * The parameter `size` sets the size (float) of each box side (default 1).
  33491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33492. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33494. */
  33495. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33496. if (scene === void 0) { scene = null; }
  33497. var options = {
  33498. size: size,
  33499. sideOrientation: sideOrientation,
  33500. updatable: updatable
  33501. };
  33502. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33503. };
  33504. /**
  33505. * Creates a sphere mesh.
  33506. * Please consider using the same method from the MeshBuilder class instead.
  33507. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33508. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33510. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33512. */
  33513. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33514. var options = {
  33515. segments: segments,
  33516. diameterX: diameter,
  33517. diameterY: diameter,
  33518. diameterZ: diameter,
  33519. sideOrientation: sideOrientation,
  33520. updatable: updatable
  33521. };
  33522. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a cylinder or a cone mesh.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33528. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33529. * 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.
  33530. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33531. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33533. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. */
  33536. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33537. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33538. if (scene !== undefined) {
  33539. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33540. updatable = scene;
  33541. }
  33542. scene = subdivisions;
  33543. subdivisions = 1;
  33544. }
  33545. var options = {
  33546. height: height,
  33547. diameterTop: diameterTop,
  33548. diameterBottom: diameterBottom,
  33549. tessellation: tessellation,
  33550. subdivisions: subdivisions,
  33551. sideOrientation: sideOrientation,
  33552. updatable: updatable
  33553. };
  33554. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33555. };
  33556. // Torus (Code from SharpDX.org)
  33557. /**
  33558. * Creates a torus mesh.
  33559. * Please consider using the same method from the MeshBuilder class instead.
  33560. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33561. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33562. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33564. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33566. */
  33567. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33568. var options = {
  33569. diameter: diameter,
  33570. thickness: thickness,
  33571. tessellation: tessellation,
  33572. sideOrientation: sideOrientation,
  33573. updatable: updatable
  33574. };
  33575. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33576. };
  33577. /**
  33578. * Creates a torus knot mesh.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33581. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33582. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33583. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33585. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33587. */
  33588. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33589. var options = {
  33590. radius: radius,
  33591. tube: tube,
  33592. radialSegments: radialSegments,
  33593. tubularSegments: tubularSegments,
  33594. p: p,
  33595. q: q,
  33596. sideOrientation: sideOrientation,
  33597. updatable: updatable
  33598. };
  33599. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33600. };
  33601. /**
  33602. * Creates a line mesh.
  33603. * Please consider using the same method from the MeshBuilder class instead.
  33604. * 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.
  33605. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33606. * The parameter `points` is an array successive Vector3.
  33607. * 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
  33608. * When updating an instance, remember that only point positions can change, not the number of points.
  33609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33610. */
  33611. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33612. if (scene === void 0) { scene = null; }
  33613. if (updatable === void 0) { updatable = false; }
  33614. if (instance === void 0) { instance = null; }
  33615. var options = {
  33616. points: points,
  33617. updatable: updatable,
  33618. instance: instance
  33619. };
  33620. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33621. };
  33622. /**
  33623. * Creates a dashed line mesh.
  33624. * Please consider using the same method from the MeshBuilder class instead.
  33625. * 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.
  33626. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33627. * The parameter `points` is an array successive Vector3.
  33628. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33629. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33630. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33631. * 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
  33632. * When updating an instance, remember that only point positions can change, not the number of points.
  33633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33634. */
  33635. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33636. if (scene === void 0) { scene = null; }
  33637. var options = {
  33638. points: points,
  33639. dashSize: dashSize,
  33640. gapSize: gapSize,
  33641. dashNb: dashNb,
  33642. updatable: updatable,
  33643. instance: instance
  33644. };
  33645. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33646. };
  33647. /**
  33648. * Creates a polygon mesh.
  33649. * Please consider using the same method from the MeshBuilder class instead.
  33650. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33651. * 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.
  33652. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33654. * Remember you can only change the shape positions, not their number when updating a polygon.
  33655. */
  33656. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33657. var options = {
  33658. shape: shape,
  33659. holes: holes,
  33660. updatable: updatable,
  33661. sideOrientation: sideOrientation
  33662. };
  33663. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33664. };
  33665. /**
  33666. * Creates an extruded polygon mesh, with depth in the Y direction.
  33667. * Please consider using the same method from the MeshBuilder class instead.
  33668. */
  33669. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33670. var options = {
  33671. shape: shape,
  33672. holes: holes,
  33673. depth: depth,
  33674. updatable: updatable,
  33675. sideOrientation: sideOrientation
  33676. };
  33677. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33678. };
  33679. /**
  33680. * Creates an extruded shape mesh.
  33681. * 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.
  33682. * Please consider using the same method from the MeshBuilder class instead.
  33683. *
  33684. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33685. * 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
  33686. * extruded along the Z axis.
  33687. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33688. * 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.
  33689. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33690. * 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
  33691. * 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
  33692. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33694. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33696. */
  33697. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33698. if (scene === void 0) { scene = null; }
  33699. var options = {
  33700. shape: shape,
  33701. path: path,
  33702. scale: scale,
  33703. rotation: rotation,
  33704. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33705. sideOrientation: sideOrientation,
  33706. instance: instance,
  33707. updatable: updatable
  33708. };
  33709. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33710. };
  33711. /**
  33712. * Creates an custom extruded shape mesh.
  33713. * 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.
  33714. * Please consider using the same method from the MeshBuilder class instead.
  33715. *
  33716. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33717. * 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
  33718. * extruded along the Z axis.
  33719. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33720. * 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
  33721. * and the distance of this point from the begining of the path :
  33722. * ```javascript
  33723. * var rotationFunction = function(i, distance) {
  33724. * // do things
  33725. * return rotationValue; }
  33726. * ```
  33727. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33728. * 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
  33729. * and the distance of this point from the begining of the path :
  33730. * ```javascript
  33731. * var scaleFunction = function(i, distance) {
  33732. * // do things
  33733. * return scaleValue;}
  33734. * ```
  33735. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33736. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33737. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33738. * 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
  33739. * 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
  33740. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33742. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33744. */
  33745. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33746. var options = {
  33747. shape: shape,
  33748. path: path,
  33749. scaleFunction: scaleFunction,
  33750. rotationFunction: rotationFunction,
  33751. ribbonCloseArray: ribbonCloseArray,
  33752. ribbonClosePath: ribbonClosePath,
  33753. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33754. sideOrientation: sideOrientation,
  33755. instance: instance,
  33756. updatable: updatable
  33757. };
  33758. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33759. };
  33760. /**
  33761. * Creates lathe mesh.
  33762. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33763. * Please consider using the same method from the MeshBuilder class instead.
  33764. * 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
  33765. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33766. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33767. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33769. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33771. */
  33772. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33773. var options = {
  33774. shape: shape,
  33775. radius: radius,
  33776. tessellation: tessellation,
  33777. sideOrientation: sideOrientation,
  33778. updatable: updatable
  33779. };
  33780. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33781. };
  33782. /**
  33783. * Creates a plane mesh.
  33784. * Please consider using the same method from the MeshBuilder class instead.
  33785. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33787. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33789. */
  33790. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33791. var options = {
  33792. size: size,
  33793. width: size,
  33794. height: size,
  33795. sideOrientation: sideOrientation,
  33796. updatable: updatable
  33797. };
  33798. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33799. };
  33800. /**
  33801. * Creates a ground mesh.
  33802. * Please consider using the same method from the MeshBuilder class instead.
  33803. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33804. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33806. */
  33807. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33808. var options = {
  33809. width: width,
  33810. height: height,
  33811. subdivisions: subdivisions,
  33812. updatable: updatable
  33813. };
  33814. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33815. };
  33816. /**
  33817. * Creates a tiled ground mesh.
  33818. * Please consider using the same method from the MeshBuilder class instead.
  33819. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33820. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33821. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33822. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33823. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33824. * numbers of subdivisions on the ground width and height of each tile.
  33825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33826. */
  33827. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33828. var options = {
  33829. xmin: xmin,
  33830. zmin: zmin,
  33831. xmax: xmax,
  33832. zmax: zmax,
  33833. subdivisions: subdivisions,
  33834. precision: precision,
  33835. updatable: updatable
  33836. };
  33837. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33838. };
  33839. /**
  33840. * Creates a ground mesh from a height map.
  33841. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33842. * Please consider using the same method from the MeshBuilder class instead.
  33843. * The parameter `url` sets the URL of the height map image resource.
  33844. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33845. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33846. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33847. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33848. * 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).
  33849. * This function is passed the newly built mesh :
  33850. * ```javascript
  33851. * function(mesh) { // do things
  33852. * return; }
  33853. * ```
  33854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33855. */
  33856. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33857. var options = {
  33858. width: width,
  33859. height: height,
  33860. subdivisions: subdivisions,
  33861. minHeight: minHeight,
  33862. maxHeight: maxHeight,
  33863. updatable: updatable,
  33864. onReady: onReady
  33865. };
  33866. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33867. };
  33868. /**
  33869. * Creates a tube mesh.
  33870. * 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.
  33871. * Please consider using the same method from the MeshBuilder class instead.
  33872. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33873. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33874. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33875. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33876. * 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.
  33877. * It must return a radius value (positive float) :
  33878. * ```javascript
  33879. * var radiusFunction = function(i, distance) {
  33880. * // do things
  33881. * return radius; }
  33882. * ```
  33883. * 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
  33884. * 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
  33885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33886. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33888. */
  33889. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33890. var options = {
  33891. path: path,
  33892. radius: radius,
  33893. tessellation: tessellation,
  33894. radiusFunction: radiusFunction,
  33895. arc: 1,
  33896. cap: cap,
  33897. updatable: updatable,
  33898. sideOrientation: sideOrientation,
  33899. instance: instance
  33900. };
  33901. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33902. };
  33903. /**
  33904. * Creates a polyhedron mesh.
  33905. * Please consider using the same method from the MeshBuilder class instead.
  33906. * 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
  33907. * to choose the wanted type.
  33908. * The parameter `size` (positive float, default 1) sets the polygon size.
  33909. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33910. * 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`.
  33911. * 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
  33912. * 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)`).
  33913. * 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
  33914. * 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.
  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.CreatePolyhedron = function (name, options, scene) {
  33920. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33921. };
  33922. /**
  33923. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33924. * Please consider using the same method from the MeshBuilder class instead.
  33925. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33926. * 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`).
  33927. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33928. * 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.
  33929. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33930. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33932. */
  33933. Mesh.CreateIcoSphere = function (name, options, scene) {
  33934. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33935. };
  33936. /**
  33937. * Creates a decal mesh.
  33938. * Please consider using the same method from the MeshBuilder class instead.
  33939. * 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.
  33940. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33941. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33942. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33943. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33944. */
  33945. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33946. var options = {
  33947. position: position,
  33948. normal: normal,
  33949. size: size,
  33950. angle: angle
  33951. };
  33952. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33953. };
  33954. // Skeletons
  33955. /**
  33956. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33957. */
  33958. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33959. if (!this._sourcePositions) {
  33960. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33961. if (!source) {
  33962. return this._sourcePositions;
  33963. }
  33964. this._sourcePositions = new Float32Array(source);
  33965. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33966. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33967. }
  33968. }
  33969. return this._sourcePositions;
  33970. };
  33971. /**
  33972. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33973. */
  33974. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33975. if (!this._sourceNormals) {
  33976. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33977. if (!source) {
  33978. return this._sourceNormals;
  33979. }
  33980. this._sourceNormals = new Float32Array(source);
  33981. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33982. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33983. }
  33984. }
  33985. return this._sourceNormals;
  33986. };
  33987. /**
  33988. * Updates the vertex buffer by applying transformation from the bones.
  33989. * Returns the Mesh.
  33990. *
  33991. * @param {skeleton} skeleton to apply
  33992. */
  33993. Mesh.prototype.applySkeleton = function (skeleton) {
  33994. if (!this.geometry) {
  33995. return this;
  33996. }
  33997. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33998. return this;
  33999. }
  34000. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34001. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34002. return this;
  34003. }
  34004. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34005. return this;
  34006. }
  34007. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34008. return this;
  34009. }
  34010. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34011. return this;
  34012. }
  34013. if (!this._sourcePositions) {
  34014. var submeshes = this.subMeshes.slice();
  34015. this.setPositionsForCPUSkinning();
  34016. this.subMeshes = submeshes;
  34017. }
  34018. if (!this._sourceNormals) {
  34019. this.setNormalsForCPUSkinning();
  34020. }
  34021. // positionsData checks for not being Float32Array will only pass at most once
  34022. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34023. if (!positionsData) {
  34024. return this;
  34025. }
  34026. if (!(positionsData instanceof Float32Array)) {
  34027. positionsData = new Float32Array(positionsData);
  34028. }
  34029. // normalsData checks for not being Float32Array will only pass at most once
  34030. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34031. if (!normalsData) {
  34032. return this;
  34033. }
  34034. if (!(normalsData instanceof Float32Array)) {
  34035. normalsData = new Float32Array(normalsData);
  34036. }
  34037. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34038. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34039. if (!matricesWeightsData || !matricesIndicesData) {
  34040. return this;
  34041. }
  34042. var needExtras = this.numBoneInfluencers > 4;
  34043. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34044. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34045. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34046. var tempVector3 = BABYLON.Vector3.Zero();
  34047. var finalMatrix = new BABYLON.Matrix();
  34048. var tempMatrix = new BABYLON.Matrix();
  34049. var matWeightIdx = 0;
  34050. var inf;
  34051. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34052. var weight;
  34053. for (inf = 0; inf < 4; inf++) {
  34054. weight = matricesWeightsData[matWeightIdx + inf];
  34055. if (weight > 0) {
  34056. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34057. finalMatrix.addToSelf(tempMatrix);
  34058. }
  34059. else
  34060. break;
  34061. }
  34062. if (needExtras) {
  34063. for (inf = 0; inf < 4; inf++) {
  34064. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34065. if (weight > 0) {
  34066. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34067. finalMatrix.addToSelf(tempMatrix);
  34068. }
  34069. else
  34070. break;
  34071. }
  34072. }
  34073. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34074. tempVector3.toArray(positionsData, index);
  34075. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34076. tempVector3.toArray(normalsData, index);
  34077. finalMatrix.reset();
  34078. }
  34079. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34080. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34081. return this;
  34082. };
  34083. // Tools
  34084. /**
  34085. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34086. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34087. */
  34088. Mesh.MinMax = function (meshes) {
  34089. var minVector = null;
  34090. var maxVector = null;
  34091. meshes.forEach(function (mesh, index, array) {
  34092. var boundingInfo = mesh.getBoundingInfo();
  34093. var boundingBox = boundingInfo.boundingBox;
  34094. if (!minVector || !maxVector) {
  34095. minVector = boundingBox.minimumWorld;
  34096. maxVector = boundingBox.maximumWorld;
  34097. }
  34098. else {
  34099. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34100. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34101. }
  34102. });
  34103. if (!minVector || !maxVector) {
  34104. return {
  34105. min: BABYLON.Vector3.Zero(),
  34106. max: BABYLON.Vector3.Zero()
  34107. };
  34108. }
  34109. return {
  34110. min: minVector,
  34111. max: maxVector
  34112. };
  34113. };
  34114. /**
  34115. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34116. */
  34117. Mesh.Center = function (meshesOrMinMaxVector) {
  34118. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34119. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34120. };
  34121. /**
  34122. * Merge the array of meshes into a single mesh for performance reasons.
  34123. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34124. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34125. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34126. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34127. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34128. */
  34129. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34130. if (disposeSource === void 0) { disposeSource = true; }
  34131. var index;
  34132. if (!allow32BitsIndices) {
  34133. var totalVertices = 0;
  34134. // Counting vertices
  34135. for (index = 0; index < meshes.length; index++) {
  34136. if (meshes[index]) {
  34137. totalVertices += meshes[index].getTotalVertices();
  34138. if (totalVertices > 65536) {
  34139. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34140. return null;
  34141. }
  34142. }
  34143. }
  34144. }
  34145. // Merge
  34146. var vertexData = null;
  34147. var otherVertexData;
  34148. var indiceArray = new Array();
  34149. var source = null;
  34150. for (index = 0; index < meshes.length; index++) {
  34151. if (meshes[index]) {
  34152. meshes[index].computeWorldMatrix(true);
  34153. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34154. otherVertexData.transform(meshes[index].getWorldMatrix());
  34155. if (vertexData) {
  34156. vertexData.merge(otherVertexData);
  34157. }
  34158. else {
  34159. vertexData = otherVertexData;
  34160. source = meshes[index];
  34161. }
  34162. if (subdivideWithSubMeshes) {
  34163. indiceArray.push(meshes[index].getTotalIndices());
  34164. }
  34165. }
  34166. }
  34167. source = source;
  34168. if (!meshSubclass) {
  34169. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34170. }
  34171. vertexData.applyToMesh(meshSubclass);
  34172. // Setting properties
  34173. meshSubclass.material = source.material;
  34174. meshSubclass.checkCollisions = source.checkCollisions;
  34175. // Cleaning
  34176. if (disposeSource) {
  34177. for (index = 0; index < meshes.length; index++) {
  34178. if (meshes[index]) {
  34179. meshes[index].dispose();
  34180. }
  34181. }
  34182. }
  34183. // Subdivide
  34184. if (subdivideWithSubMeshes) {
  34185. //-- removal of global submesh
  34186. meshSubclass.releaseSubMeshes();
  34187. index = 0;
  34188. var offset = 0;
  34189. //-- apply subdivision according to index table
  34190. while (index < indiceArray.length) {
  34191. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34192. offset += indiceArray[index];
  34193. index++;
  34194. }
  34195. }
  34196. return meshSubclass;
  34197. };
  34198. // Consts
  34199. Mesh._FRONTSIDE = 0;
  34200. Mesh._BACKSIDE = 1;
  34201. Mesh._DOUBLESIDE = 2;
  34202. Mesh._DEFAULTSIDE = 0;
  34203. Mesh._NO_CAP = 0;
  34204. Mesh._CAP_START = 1;
  34205. Mesh._CAP_END = 2;
  34206. Mesh._CAP_ALL = 3;
  34207. return Mesh;
  34208. }(BABYLON.AbstractMesh));
  34209. BABYLON.Mesh = Mesh;
  34210. })(BABYLON || (BABYLON = {}));
  34211. //# sourceMappingURL=babylon.mesh.js.map
  34212. var BABYLON;
  34213. (function (BABYLON) {
  34214. var BaseSubMesh = /** @class */ (function () {
  34215. function BaseSubMesh() {
  34216. }
  34217. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34218. get: function () {
  34219. return this._materialEffect;
  34220. },
  34221. enumerable: true,
  34222. configurable: true
  34223. });
  34224. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34225. if (defines === void 0) { defines = null; }
  34226. if (this._materialEffect === effect) {
  34227. if (!effect) {
  34228. this._materialDefines = null;
  34229. }
  34230. return;
  34231. }
  34232. this._materialDefines = defines;
  34233. this._materialEffect = effect;
  34234. };
  34235. return BaseSubMesh;
  34236. }());
  34237. BABYLON.BaseSubMesh = BaseSubMesh;
  34238. var SubMesh = /** @class */ (function (_super) {
  34239. __extends(SubMesh, _super);
  34240. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34241. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34242. var _this = _super.call(this) || this;
  34243. _this.materialIndex = materialIndex;
  34244. _this.verticesStart = verticesStart;
  34245. _this.verticesCount = verticesCount;
  34246. _this.indexStart = indexStart;
  34247. _this.indexCount = indexCount;
  34248. _this._renderId = 0;
  34249. _this._mesh = mesh;
  34250. _this._renderingMesh = renderingMesh || mesh;
  34251. mesh.subMeshes.push(_this);
  34252. _this._trianglePlanes = [];
  34253. _this._id = mesh.subMeshes.length - 1;
  34254. if (createBoundingBox) {
  34255. _this.refreshBoundingInfo();
  34256. mesh.computeWorldMatrix(true);
  34257. }
  34258. return _this;
  34259. }
  34260. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34261. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34262. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34263. };
  34264. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34265. get: function () {
  34266. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34267. },
  34268. enumerable: true,
  34269. configurable: true
  34270. });
  34271. /**
  34272. * Returns the submesh BoudingInfo object.
  34273. */
  34274. SubMesh.prototype.getBoundingInfo = function () {
  34275. if (this.IsGlobal) {
  34276. return this._mesh.getBoundingInfo();
  34277. }
  34278. return this._boundingInfo;
  34279. };
  34280. /**
  34281. * Sets the submesh BoundingInfo.
  34282. * Return the SubMesh.
  34283. */
  34284. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34285. this._boundingInfo = boundingInfo;
  34286. return this;
  34287. };
  34288. /**
  34289. * Returns the mesh of the current submesh.
  34290. */
  34291. SubMesh.prototype.getMesh = function () {
  34292. return this._mesh;
  34293. };
  34294. /**
  34295. * Returns the rendering mesh of the submesh.
  34296. */
  34297. SubMesh.prototype.getRenderingMesh = function () {
  34298. return this._renderingMesh;
  34299. };
  34300. /**
  34301. * Returns the submesh material.
  34302. */
  34303. SubMesh.prototype.getMaterial = function () {
  34304. var rootMaterial = this._renderingMesh.material;
  34305. if (rootMaterial === null || rootMaterial === undefined) {
  34306. return this._mesh.getScene().defaultMaterial;
  34307. }
  34308. else if (rootMaterial.getSubMaterial) {
  34309. var multiMaterial = rootMaterial;
  34310. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34311. if (this._currentMaterial !== effectiveMaterial) {
  34312. this._currentMaterial = effectiveMaterial;
  34313. this._materialDefines = null;
  34314. }
  34315. return effectiveMaterial;
  34316. }
  34317. return rootMaterial;
  34318. };
  34319. // Methods
  34320. /**
  34321. * Sets a new updated BoundingInfo object to the submesh.
  34322. * Returns the SubMesh.
  34323. */
  34324. SubMesh.prototype.refreshBoundingInfo = function () {
  34325. this._lastColliderWorldVertices = null;
  34326. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34327. return this;
  34328. }
  34329. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34330. if (!data) {
  34331. this._boundingInfo = this._mesh.getBoundingInfo();
  34332. return this;
  34333. }
  34334. var indices = this._renderingMesh.getIndices();
  34335. var extend;
  34336. //is this the only submesh?
  34337. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34338. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34339. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34340. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34341. }
  34342. else {
  34343. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34344. }
  34345. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34346. return this;
  34347. };
  34348. SubMesh.prototype._checkCollision = function (collider) {
  34349. var boundingInfo = this.getBoundingInfo();
  34350. return boundingInfo._checkCollision(collider);
  34351. };
  34352. /**
  34353. * Updates the submesh BoundingInfo.
  34354. * Returns the Submesh.
  34355. */
  34356. SubMesh.prototype.updateBoundingInfo = function (world) {
  34357. var boundingInfo = this.getBoundingInfo();
  34358. if (!boundingInfo) {
  34359. this.refreshBoundingInfo();
  34360. boundingInfo = this.getBoundingInfo();
  34361. }
  34362. boundingInfo.update(world);
  34363. return this;
  34364. };
  34365. /**
  34366. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34367. * Boolean returned.
  34368. */
  34369. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34370. var boundingInfo = this.getBoundingInfo();
  34371. if (!boundingInfo) {
  34372. return false;
  34373. }
  34374. return boundingInfo.isInFrustum(frustumPlanes);
  34375. };
  34376. /**
  34377. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34378. * Boolean returned.
  34379. */
  34380. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34381. var boundingInfo = this.getBoundingInfo();
  34382. if (!boundingInfo) {
  34383. return false;
  34384. }
  34385. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34386. };
  34387. /**
  34388. * Renders the submesh.
  34389. * Returns it.
  34390. */
  34391. SubMesh.prototype.render = function (enableAlphaMode) {
  34392. this._renderingMesh.render(this, enableAlphaMode);
  34393. return this;
  34394. };
  34395. /**
  34396. * Returns a new Index Buffer.
  34397. * Type returned : WebGLBuffer.
  34398. */
  34399. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34400. if (!this._linesIndexBuffer) {
  34401. var linesIndices = [];
  34402. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34403. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34404. }
  34405. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34406. this.linesIndexCount = linesIndices.length;
  34407. }
  34408. return this._linesIndexBuffer;
  34409. };
  34410. /**
  34411. * True is the passed Ray intersects the submesh bounding box.
  34412. * Boolean returned.
  34413. */
  34414. SubMesh.prototype.canIntersects = function (ray) {
  34415. var boundingInfo = this.getBoundingInfo();
  34416. if (!boundingInfo) {
  34417. return false;
  34418. }
  34419. return ray.intersectsBox(boundingInfo.boundingBox);
  34420. };
  34421. /**
  34422. * Returns an object IntersectionInfo.
  34423. */
  34424. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34425. var intersectInfo = null;
  34426. var material = this.getMaterial();
  34427. if (!material) {
  34428. return null;
  34429. }
  34430. switch (material.fillMode) {
  34431. case BABYLON.Material.PointListDrawMode:
  34432. case BABYLON.Material.LineListDrawMode:
  34433. case BABYLON.Material.LineLoopDrawMode:
  34434. case BABYLON.Material.LineStripDrawMode:
  34435. case BABYLON.Material.TriangleFanDrawMode:
  34436. case BABYLON.Material.TriangleStripDrawMode:
  34437. return null;
  34438. }
  34439. // LineMesh first as it's also a Mesh...
  34440. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34441. var lineMesh = this._mesh;
  34442. // Line test
  34443. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34444. var p0 = positions[indices[index]];
  34445. var p1 = positions[indices[index + 1]];
  34446. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34447. if (length < 0) {
  34448. continue;
  34449. }
  34450. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34451. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34452. if (fastCheck) {
  34453. break;
  34454. }
  34455. }
  34456. }
  34457. }
  34458. else {
  34459. // Triangles test
  34460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34461. var p0 = positions[indices[index]];
  34462. var p1 = positions[indices[index + 1]];
  34463. var p2 = positions[indices[index + 2]];
  34464. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34465. if (currentIntersectInfo) {
  34466. if (currentIntersectInfo.distance < 0) {
  34467. continue;
  34468. }
  34469. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34470. intersectInfo = currentIntersectInfo;
  34471. intersectInfo.faceId = index / 3;
  34472. if (fastCheck) {
  34473. break;
  34474. }
  34475. }
  34476. }
  34477. }
  34478. }
  34479. return intersectInfo;
  34480. };
  34481. SubMesh.prototype._rebuild = function () {
  34482. if (this._linesIndexBuffer) {
  34483. this._linesIndexBuffer = null;
  34484. }
  34485. };
  34486. // Clone
  34487. /**
  34488. * Creates a new Submesh from the passed Mesh.
  34489. */
  34490. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34491. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34492. if (!this.IsGlobal) {
  34493. var boundingInfo = this.getBoundingInfo();
  34494. if (!boundingInfo) {
  34495. return result;
  34496. }
  34497. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34498. }
  34499. return result;
  34500. };
  34501. // Dispose
  34502. /**
  34503. * Disposes the Submesh.
  34504. * Returns nothing.
  34505. */
  34506. SubMesh.prototype.dispose = function () {
  34507. if (this._linesIndexBuffer) {
  34508. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34509. this._linesIndexBuffer = null;
  34510. }
  34511. // Remove from mesh
  34512. var index = this._mesh.subMeshes.indexOf(this);
  34513. this._mesh.subMeshes.splice(index, 1);
  34514. };
  34515. // Statics
  34516. /**
  34517. * Creates a new Submesh from the passed parameters :
  34518. * - materialIndex (integer) : the index of the main mesh material.
  34519. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34520. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34521. * - mesh (Mesh) : the main mesh to create the submesh from.
  34522. * - renderingMesh (optional Mesh) : rendering mesh.
  34523. */
  34524. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34525. var minVertexIndex = Number.MAX_VALUE;
  34526. var maxVertexIndex = -Number.MAX_VALUE;
  34527. renderingMesh = (renderingMesh || mesh);
  34528. var indices = renderingMesh.getIndices();
  34529. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34530. var vertexIndex = indices[index];
  34531. if (vertexIndex < minVertexIndex)
  34532. minVertexIndex = vertexIndex;
  34533. if (vertexIndex > maxVertexIndex)
  34534. maxVertexIndex = vertexIndex;
  34535. }
  34536. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34537. };
  34538. return SubMesh;
  34539. }(BaseSubMesh));
  34540. BABYLON.SubMesh = SubMesh;
  34541. })(BABYLON || (BABYLON = {}));
  34542. //# sourceMappingURL=babylon.subMesh.js.map
  34543. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34544. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34545. s = arguments[i];
  34546. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34547. t[p] = s[p];
  34548. }
  34549. return t;
  34550. };
  34551. var BABYLON;
  34552. (function (BABYLON) {
  34553. /**
  34554. * Manages the defines for the Material
  34555. */
  34556. var MaterialDefines = /** @class */ (function () {
  34557. function MaterialDefines() {
  34558. this._isDirty = true;
  34559. /** @hidden */
  34560. this._areLightsDirty = true;
  34561. /** @hidden */
  34562. this._areAttributesDirty = true;
  34563. /** @hidden */
  34564. this._areTexturesDirty = true;
  34565. /** @hidden */
  34566. this._areFresnelDirty = true;
  34567. /** @hidden */
  34568. this._areMiscDirty = true;
  34569. /** @hidden */
  34570. this._areImageProcessingDirty = true;
  34571. /** @hidden */
  34572. this._normals = false;
  34573. /** @hidden */
  34574. this._uvs = false;
  34575. /** @hidden */
  34576. this._needNormals = false;
  34577. /** @hidden */
  34578. this._needUVs = false;
  34579. }
  34580. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34581. /**
  34582. * Specifies if the material needs to be re-calculated
  34583. */
  34584. get: function () {
  34585. return this._isDirty;
  34586. },
  34587. enumerable: true,
  34588. configurable: true
  34589. });
  34590. /**
  34591. * Marks the material to indicate that it has been re-calculated
  34592. */
  34593. MaterialDefines.prototype.markAsProcessed = function () {
  34594. this._isDirty = false;
  34595. this._areAttributesDirty = false;
  34596. this._areTexturesDirty = false;
  34597. this._areFresnelDirty = false;
  34598. this._areLightsDirty = false;
  34599. this._areMiscDirty = false;
  34600. this._areImageProcessingDirty = false;
  34601. };
  34602. /**
  34603. * Marks the material to indicate that it needs to be re-calculated
  34604. */
  34605. MaterialDefines.prototype.markAsUnprocessed = function () {
  34606. this._isDirty = true;
  34607. };
  34608. /**
  34609. * Marks the material to indicate all of its defines need to be re-calculated
  34610. */
  34611. MaterialDefines.prototype.markAllAsDirty = function () {
  34612. this._areTexturesDirty = true;
  34613. this._areAttributesDirty = true;
  34614. this._areLightsDirty = true;
  34615. this._areFresnelDirty = true;
  34616. this._areMiscDirty = true;
  34617. this._areImageProcessingDirty = true;
  34618. this._isDirty = true;
  34619. };
  34620. /**
  34621. * Marks the material to indicate that image processing needs to be re-calculated
  34622. */
  34623. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34624. this._areImageProcessingDirty = true;
  34625. this._isDirty = true;
  34626. };
  34627. /**
  34628. * Marks the material to indicate the lights need to be re-calculated
  34629. */
  34630. MaterialDefines.prototype.markAsLightDirty = function () {
  34631. this._areLightsDirty = true;
  34632. this._isDirty = true;
  34633. };
  34634. /**
  34635. * Marks the attribute state as changed
  34636. */
  34637. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34638. this._areAttributesDirty = true;
  34639. this._isDirty = true;
  34640. };
  34641. /**
  34642. * Marks the texture state as changed
  34643. */
  34644. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34645. this._areTexturesDirty = true;
  34646. this._isDirty = true;
  34647. };
  34648. /**
  34649. * Marks the fresnel state as changed
  34650. */
  34651. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34652. this._areFresnelDirty = true;
  34653. this._isDirty = true;
  34654. };
  34655. /**
  34656. * Marks the misc state as changed
  34657. */
  34658. MaterialDefines.prototype.markAsMiscDirty = function () {
  34659. this._areMiscDirty = true;
  34660. this._isDirty = true;
  34661. };
  34662. /**
  34663. * Rebuilds the material defines
  34664. */
  34665. MaterialDefines.prototype.rebuild = function () {
  34666. if (this._keys) {
  34667. delete this._keys;
  34668. }
  34669. this._keys = [];
  34670. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34671. var key = _a[_i];
  34672. if (key[0] === "_") {
  34673. continue;
  34674. }
  34675. this._keys.push(key);
  34676. }
  34677. };
  34678. /**
  34679. * Specifies if two material defines are equal
  34680. * @param other - A material define instance to compare to
  34681. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34682. */
  34683. MaterialDefines.prototype.isEqual = function (other) {
  34684. if (this._keys.length !== other._keys.length) {
  34685. return false;
  34686. }
  34687. for (var index = 0; index < this._keys.length; index++) {
  34688. var prop = this._keys[index];
  34689. if (this[prop] !== other[prop]) {
  34690. return false;
  34691. }
  34692. }
  34693. return true;
  34694. };
  34695. /**
  34696. * Clones this instance's defines to another instance
  34697. * @param other - material defines to clone values to
  34698. */
  34699. MaterialDefines.prototype.cloneTo = function (other) {
  34700. if (this._keys.length !== other._keys.length) {
  34701. other._keys = this._keys.slice(0);
  34702. }
  34703. for (var index = 0; index < this._keys.length; index++) {
  34704. var prop = this._keys[index];
  34705. other[prop] = this[prop];
  34706. }
  34707. };
  34708. /**
  34709. * Resets the material define values
  34710. */
  34711. MaterialDefines.prototype.reset = function () {
  34712. for (var index = 0; index < this._keys.length; index++) {
  34713. var prop = this._keys[index];
  34714. var type = typeof this[prop];
  34715. switch (type) {
  34716. case "number":
  34717. this[prop] = 0;
  34718. break;
  34719. case "string":
  34720. this[prop] = "";
  34721. break;
  34722. default:
  34723. this[prop] = false;
  34724. break;
  34725. }
  34726. }
  34727. };
  34728. /**
  34729. * Converts the material define values to a string
  34730. * @returns - String of material define information
  34731. */
  34732. MaterialDefines.prototype.toString = function () {
  34733. var result = "";
  34734. for (var index = 0; index < this._keys.length; index++) {
  34735. var prop = this._keys[index];
  34736. var value = this[prop];
  34737. var type = typeof value;
  34738. switch (type) {
  34739. case "number":
  34740. case "string":
  34741. result += "#define " + prop + " " + value + "\n";
  34742. break;
  34743. default:
  34744. if (value) {
  34745. result += "#define " + prop + "\n";
  34746. }
  34747. break;
  34748. }
  34749. }
  34750. return result;
  34751. };
  34752. return MaterialDefines;
  34753. }());
  34754. BABYLON.MaterialDefines = MaterialDefines;
  34755. /**
  34756. * Base class for the main features of a material in Babylon.js
  34757. */
  34758. var Material = /** @class */ (function () {
  34759. /**
  34760. * Creates a material instance
  34761. * @param name defines the name of the material
  34762. * @param scene defines the scene to reference
  34763. * @param doNotAdd specifies if the material should be added to the scene
  34764. */
  34765. function Material(name, scene, doNotAdd) {
  34766. /**
  34767. * Specifies if the ready state should be checked on each call
  34768. */
  34769. this.checkReadyOnEveryCall = false;
  34770. /**
  34771. * Specifies if the ready state should be checked once
  34772. */
  34773. this.checkReadyOnlyOnce = false;
  34774. /**
  34775. * The state of the material
  34776. */
  34777. this.state = "";
  34778. /**
  34779. * The alpha value of the material
  34780. */
  34781. this._alpha = 1.0;
  34782. /**
  34783. * Specifies if back face culling is enabled
  34784. */
  34785. this._backFaceCulling = true;
  34786. /**
  34787. * Specifies if the material should be serialized
  34788. */
  34789. this.doNotSerialize = false;
  34790. /**
  34791. * Specifies if the effect should be stored on sub meshes
  34792. */
  34793. this.storeEffectOnSubMeshes = false;
  34794. /**
  34795. * An event triggered when the material is disposed
  34796. */
  34797. this.onDisposeObservable = new BABYLON.Observable();
  34798. /**
  34799. * An event triggered when the material is bound
  34800. */
  34801. this.onBindObservable = new BABYLON.Observable();
  34802. /**
  34803. * An event triggered when the material is unbound
  34804. */
  34805. this.onUnBindObservable = new BABYLON.Observable();
  34806. /**
  34807. * Stores the value of the alpha mode
  34808. */
  34809. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34810. /**
  34811. * Stores the state of the need depth pre-pass value
  34812. */
  34813. this._needDepthPrePass = false;
  34814. /**
  34815. * Specifies if depth writing should be disabled
  34816. */
  34817. this.disableDepthWrite = false;
  34818. /**
  34819. * Specifies if depth writing should be forced
  34820. */
  34821. this.forceDepthWrite = false;
  34822. /**
  34823. * Specifies if there should be a separate pass for culling
  34824. */
  34825. this.separateCullingPass = false;
  34826. /**
  34827. * Stores the state specifing if fog should be enabled
  34828. */
  34829. this._fogEnabled = true;
  34830. /**
  34831. * Stores the size of points
  34832. */
  34833. this.pointSize = 1.0;
  34834. /**
  34835. * Stores the z offset value
  34836. */
  34837. this.zOffset = 0;
  34838. /**
  34839. * Specifies if the material was previously ready
  34840. */
  34841. this._wasPreviouslyReady = false;
  34842. /**
  34843. * Stores the fill mode state
  34844. */
  34845. this._fillMode = Material.TriangleFillMode;
  34846. this.name = name;
  34847. this.id = name || BABYLON.Tools.RandomId();
  34848. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34849. this.uniqueId = this._scene.getUniqueId();
  34850. if (this._scene.useRightHandedSystem) {
  34851. this.sideOrientation = Material.ClockWiseSideOrientation;
  34852. }
  34853. else {
  34854. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34855. }
  34856. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34857. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34858. if (!doNotAdd) {
  34859. this._scene.materials.push(this);
  34860. }
  34861. }
  34862. Object.defineProperty(Material, "TriangleFillMode", {
  34863. /**
  34864. * Returns the triangle fill mode
  34865. */
  34866. get: function () {
  34867. return Material._TriangleFillMode;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material, "WireFrameFillMode", {
  34873. /**
  34874. * Returns the wireframe mode
  34875. */
  34876. get: function () {
  34877. return Material._WireFrameFillMode;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(Material, "PointFillMode", {
  34883. /**
  34884. * Returns the point fill mode
  34885. */
  34886. get: function () {
  34887. return Material._PointFillMode;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material, "PointListDrawMode", {
  34893. /**
  34894. * Returns the point list draw mode
  34895. */
  34896. get: function () {
  34897. return Material._PointListDrawMode;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(Material, "LineListDrawMode", {
  34903. /**
  34904. * Returns the line list draw mode
  34905. */
  34906. get: function () {
  34907. return Material._LineListDrawMode;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(Material, "LineLoopDrawMode", {
  34913. /**
  34914. * Returns the line loop draw mode
  34915. */
  34916. get: function () {
  34917. return Material._LineLoopDrawMode;
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. Object.defineProperty(Material, "LineStripDrawMode", {
  34923. /**
  34924. * Returns the line strip draw mode
  34925. */
  34926. get: function () {
  34927. return Material._LineStripDrawMode;
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34933. /**
  34934. * Returns the triangle strip draw mode
  34935. */
  34936. get: function () {
  34937. return Material._TriangleStripDrawMode;
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34943. /**
  34944. * Returns the triangle fan draw mode
  34945. */
  34946. get: function () {
  34947. return Material._TriangleFanDrawMode;
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34953. /**
  34954. * Returns the clock-wise side orientation
  34955. */
  34956. get: function () {
  34957. return Material._ClockWiseSideOrientation;
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34963. /**
  34964. * Returns the counter clock-wise side orientation
  34965. */
  34966. get: function () {
  34967. return Material._CounterClockWiseSideOrientation;
  34968. },
  34969. enumerable: true,
  34970. configurable: true
  34971. });
  34972. Object.defineProperty(Material, "TextureDirtyFlag", {
  34973. /**
  34974. * Returns the dirty texture flag value
  34975. */
  34976. get: function () {
  34977. return Material._TextureDirtyFlag;
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(Material, "LightDirtyFlag", {
  34983. /**
  34984. * Returns the dirty light flag value
  34985. */
  34986. get: function () {
  34987. return Material._LightDirtyFlag;
  34988. },
  34989. enumerable: true,
  34990. configurable: true
  34991. });
  34992. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34993. /**
  34994. * Returns the dirty fresnel flag value
  34995. */
  34996. get: function () {
  34997. return Material._FresnelDirtyFlag;
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35003. /**
  35004. * Returns the dirty attributes flag value
  35005. */
  35006. get: function () {
  35007. return Material._AttributesDirtyFlag;
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(Material, "MiscDirtyFlag", {
  35013. /**
  35014. * Returns the dirty misc flag value
  35015. */
  35016. get: function () {
  35017. return Material._MiscDirtyFlag;
  35018. },
  35019. enumerable: true,
  35020. configurable: true
  35021. });
  35022. Object.defineProperty(Material.prototype, "alpha", {
  35023. /**
  35024. * Gets the alpha value of the material
  35025. */
  35026. get: function () {
  35027. return this._alpha;
  35028. },
  35029. /**
  35030. * Sets the alpha value of the material
  35031. */
  35032. set: function (value) {
  35033. if (this._alpha === value) {
  35034. return;
  35035. }
  35036. this._alpha = value;
  35037. this.markAsDirty(Material.MiscDirtyFlag);
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35043. /**
  35044. * Gets the back-face culling state
  35045. */
  35046. get: function () {
  35047. return this._backFaceCulling;
  35048. },
  35049. /**
  35050. * Sets the back-face culling state
  35051. */
  35052. set: function (value) {
  35053. if (this._backFaceCulling === value) {
  35054. return;
  35055. }
  35056. this._backFaceCulling = value;
  35057. this.markAsDirty(Material.TextureDirtyFlag);
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. Object.defineProperty(Material.prototype, "onDispose", {
  35063. /**
  35064. * Called during a dispose event
  35065. */
  35066. set: function (callback) {
  35067. if (this._onDisposeObserver) {
  35068. this.onDisposeObservable.remove(this._onDisposeObserver);
  35069. }
  35070. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(Material.prototype, "onBind", {
  35076. /**
  35077. * Called during a bind event
  35078. */
  35079. set: function (callback) {
  35080. if (this._onBindObserver) {
  35081. this.onBindObservable.remove(this._onBindObserver);
  35082. }
  35083. this._onBindObserver = this.onBindObservable.add(callback);
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(Material.prototype, "alphaMode", {
  35089. /**
  35090. * Gets the value of the alpha mode
  35091. */
  35092. get: function () {
  35093. return this._alphaMode;
  35094. },
  35095. /**
  35096. * Sets the value of the alpha mode.
  35097. *
  35098. * | Value | Type | Description |
  35099. * | --- | --- | --- |
  35100. * | 0 | ALPHA_DISABLE | |
  35101. * | 1 | ALPHA_ADD | |
  35102. * | 2 | ALPHA_COMBINE | |
  35103. * | 3 | ALPHA_SUBTRACT | |
  35104. * | 4 | ALPHA_MULTIPLY | |
  35105. * | 5 | ALPHA_MAXIMIZED | |
  35106. * | 6 | ALPHA_ONEONE | |
  35107. * | 7 | ALPHA_PREMULTIPLIED | |
  35108. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35109. * | 9 | ALPHA_INTERPOLATE | |
  35110. * | 10 | ALPHA_SCREENMODE | |
  35111. *
  35112. */
  35113. set: function (value) {
  35114. if (this._alphaMode === value) {
  35115. return;
  35116. }
  35117. this._alphaMode = value;
  35118. this.markAsDirty(Material.TextureDirtyFlag);
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35124. /**
  35125. * Gets the depth pre-pass value
  35126. */
  35127. get: function () {
  35128. return this._needDepthPrePass;
  35129. },
  35130. /**
  35131. * Sets the need depth pre-pass value
  35132. */
  35133. set: function (value) {
  35134. if (this._needDepthPrePass === value) {
  35135. return;
  35136. }
  35137. this._needDepthPrePass = value;
  35138. if (this._needDepthPrePass) {
  35139. this.checkReadyOnEveryCall = true;
  35140. }
  35141. },
  35142. enumerable: true,
  35143. configurable: true
  35144. });
  35145. Object.defineProperty(Material.prototype, "fogEnabled", {
  35146. /**
  35147. * Gets the value of the fog enabled state
  35148. */
  35149. get: function () {
  35150. return this._fogEnabled;
  35151. },
  35152. /**
  35153. * Sets the state for enabling fog
  35154. */
  35155. set: function (value) {
  35156. if (this._fogEnabled === value) {
  35157. return;
  35158. }
  35159. this._fogEnabled = value;
  35160. this.markAsDirty(Material.MiscDirtyFlag);
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. Object.defineProperty(Material.prototype, "wireframe", {
  35166. /**
  35167. * Gets a value specifying if wireframe mode is enabled
  35168. */
  35169. get: function () {
  35170. switch (this._fillMode) {
  35171. case Material.WireFrameFillMode:
  35172. case Material.LineListDrawMode:
  35173. case Material.LineLoopDrawMode:
  35174. case Material.LineStripDrawMode:
  35175. return true;
  35176. }
  35177. return this._scene.forceWireframe;
  35178. },
  35179. /**
  35180. * Sets the state of wireframe mode
  35181. */
  35182. set: function (value) {
  35183. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(Material.prototype, "pointsCloud", {
  35189. /**
  35190. * Gets the value specifying if point clouds are enabled
  35191. */
  35192. get: function () {
  35193. switch (this._fillMode) {
  35194. case Material.PointFillMode:
  35195. case Material.PointListDrawMode:
  35196. return true;
  35197. }
  35198. return this._scene.forcePointsCloud;
  35199. },
  35200. /**
  35201. * Sets the state of point cloud mode
  35202. */
  35203. set: function (value) {
  35204. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. Object.defineProperty(Material.prototype, "fillMode", {
  35210. /**
  35211. * Gets the material fill mode
  35212. */
  35213. get: function () {
  35214. return this._fillMode;
  35215. },
  35216. /**
  35217. * Sets the material fill mode
  35218. */
  35219. set: function (value) {
  35220. if (this._fillMode === value) {
  35221. return;
  35222. }
  35223. this._fillMode = value;
  35224. this.markAsDirty(Material.MiscDirtyFlag);
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. /**
  35230. * Returns a string representation of the current material
  35231. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35232. * @returns a string with material information
  35233. */
  35234. Material.prototype.toString = function (fullDetails) {
  35235. var ret = "Name: " + this.name;
  35236. if (fullDetails) {
  35237. }
  35238. return ret;
  35239. };
  35240. /**
  35241. * Gets the class name of the material
  35242. * @returns a string with the class name of the material
  35243. */
  35244. Material.prototype.getClassName = function () {
  35245. return "Material";
  35246. };
  35247. Object.defineProperty(Material.prototype, "isFrozen", {
  35248. /**
  35249. * Specifies if updates for the material been locked
  35250. */
  35251. get: function () {
  35252. return this.checkReadyOnlyOnce;
  35253. },
  35254. enumerable: true,
  35255. configurable: true
  35256. });
  35257. /**
  35258. * Locks updates for the material
  35259. */
  35260. Material.prototype.freeze = function () {
  35261. this.checkReadyOnlyOnce = true;
  35262. };
  35263. /**
  35264. * Unlocks updates for the material
  35265. */
  35266. Material.prototype.unfreeze = function () {
  35267. this.checkReadyOnlyOnce = false;
  35268. };
  35269. /**
  35270. * Specifies if the material is ready to be used
  35271. * @param mesh defines the mesh to check
  35272. * @param useInstances specifies if instances should be used
  35273. * @returns a boolean indicating if the material is ready to be used
  35274. */
  35275. Material.prototype.isReady = function (mesh, useInstances) {
  35276. return true;
  35277. };
  35278. /**
  35279. * Specifies that the submesh is ready to be used
  35280. * @param mesh defines the mesh to check
  35281. * @param subMesh defines which submesh to check
  35282. * @param useInstances specifies that instances should be used
  35283. * @returns a boolean indicating that the submesh is ready or not
  35284. */
  35285. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35286. return false;
  35287. };
  35288. /**
  35289. * Returns the material effect
  35290. * @returns the effect associated with the material
  35291. */
  35292. Material.prototype.getEffect = function () {
  35293. return this._effect;
  35294. };
  35295. /**
  35296. * Returns the current scene
  35297. * @returns a Scene
  35298. */
  35299. Material.prototype.getScene = function () {
  35300. return this._scene;
  35301. };
  35302. /**
  35303. * Specifies if the material will require alpha blending
  35304. * @returns a boolean specifying if alpha blending is needed
  35305. */
  35306. Material.prototype.needAlphaBlending = function () {
  35307. return (this.alpha < 1.0);
  35308. };
  35309. /**
  35310. * Specifies if the mesh will require alpha blending
  35311. * @param mesh defines the mesh to check
  35312. * @returns a boolean specifying if alpha blending is needed for the mesh
  35313. */
  35314. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35315. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35316. };
  35317. /**
  35318. * Specifies if this material should be rendered in alpha test mode
  35319. * @returns a boolean specifying if an alpha test is needed.
  35320. */
  35321. Material.prototype.needAlphaTesting = function () {
  35322. return false;
  35323. };
  35324. /**
  35325. * Gets the texture used for the alpha test
  35326. * @returns the texture to use for alpha testing
  35327. */
  35328. Material.prototype.getAlphaTestTexture = function () {
  35329. return null;
  35330. };
  35331. /**
  35332. * Marks the material to indicate that it needs to be re-calculated
  35333. */
  35334. Material.prototype.markDirty = function () {
  35335. this._wasPreviouslyReady = false;
  35336. };
  35337. /** @hidden */
  35338. Material.prototype._preBind = function (effect, overrideOrientation) {
  35339. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35340. var engine = this._scene.getEngine();
  35341. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35342. var reverse = orientation === Material.ClockWiseSideOrientation;
  35343. engine.enableEffect(effect ? effect : this._effect);
  35344. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35345. return reverse;
  35346. };
  35347. /**
  35348. * Binds the material to the mesh
  35349. * @param world defines the world transformation matrix
  35350. * @param mesh defines the mesh to bind the material to
  35351. */
  35352. Material.prototype.bind = function (world, mesh) {
  35353. };
  35354. /**
  35355. * Binds the submesh to the material
  35356. * @param world defines the world transformation matrix
  35357. * @param mesh defines the mesh containing the submesh
  35358. * @param subMesh defines the submesh to bind the material to
  35359. */
  35360. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35361. };
  35362. /**
  35363. * Binds the world matrix to the material
  35364. * @param world defines the world transformation matrix
  35365. */
  35366. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35367. };
  35368. /**
  35369. * Binds the scene's uniform buffer to the effect.
  35370. * @param effect defines the effect to bind to the scene uniform buffer
  35371. * @param sceneUbo defines the uniform buffer storing scene data
  35372. */
  35373. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35374. sceneUbo.bindToEffect(effect, "Scene");
  35375. };
  35376. /**
  35377. * Binds the view matrix to the effect
  35378. * @param effect defines the effect to bind the view matrix to
  35379. */
  35380. Material.prototype.bindView = function (effect) {
  35381. if (!this._useUBO) {
  35382. effect.setMatrix("view", this.getScene().getViewMatrix());
  35383. }
  35384. else {
  35385. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35386. }
  35387. };
  35388. /**
  35389. * Binds the view projection matrix to the effect
  35390. * @param effect defines the effect to bind the view projection matrix to
  35391. */
  35392. Material.prototype.bindViewProjection = function (effect) {
  35393. if (!this._useUBO) {
  35394. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35395. }
  35396. else {
  35397. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35398. }
  35399. };
  35400. /**
  35401. * Specifies if material alpha testing should be turned on for the mesh
  35402. * @param mesh defines the mesh to check
  35403. */
  35404. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35405. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35406. };
  35407. /**
  35408. * Processes to execute after binding the material to a mesh
  35409. * @param mesh defines the rendered mesh
  35410. */
  35411. Material.prototype._afterBind = function (mesh) {
  35412. this._scene._cachedMaterial = this;
  35413. if (mesh) {
  35414. this._scene._cachedVisibility = mesh.visibility;
  35415. }
  35416. else {
  35417. this._scene._cachedVisibility = 1;
  35418. }
  35419. if (mesh) {
  35420. this.onBindObservable.notifyObservers(mesh);
  35421. }
  35422. if (this.disableDepthWrite) {
  35423. var engine = this._scene.getEngine();
  35424. this._cachedDepthWriteState = engine.getDepthWrite();
  35425. engine.setDepthWrite(false);
  35426. }
  35427. };
  35428. /**
  35429. * Unbinds the material from the mesh
  35430. */
  35431. Material.prototype.unbind = function () {
  35432. this.onUnBindObservable.notifyObservers(this);
  35433. if (this.disableDepthWrite) {
  35434. var engine = this._scene.getEngine();
  35435. engine.setDepthWrite(this._cachedDepthWriteState);
  35436. }
  35437. };
  35438. /**
  35439. * Gets the active textures from the material
  35440. * @returns an array of textures
  35441. */
  35442. Material.prototype.getActiveTextures = function () {
  35443. return [];
  35444. };
  35445. /**
  35446. * Specifies if the material uses a texture
  35447. * @param texture defines the texture to check against the material
  35448. * @returns a boolean specifying if the material uses the texture
  35449. */
  35450. Material.prototype.hasTexture = function (texture) {
  35451. return false;
  35452. };
  35453. /**
  35454. * Makes a duplicate of the material, and gives it a new name
  35455. * @param name defines the new name for the duplicated material
  35456. * @returns the cloned material
  35457. */
  35458. Material.prototype.clone = function (name) {
  35459. return null;
  35460. };
  35461. /**
  35462. * Gets the meshes bound to the material
  35463. * @returns an array of meshes bound to the material
  35464. */
  35465. Material.prototype.getBindedMeshes = function () {
  35466. var result = new Array();
  35467. for (var index = 0; index < this._scene.meshes.length; index++) {
  35468. var mesh = this._scene.meshes[index];
  35469. if (mesh.material === this) {
  35470. result.push(mesh);
  35471. }
  35472. }
  35473. return result;
  35474. };
  35475. /**
  35476. * Force shader compilation
  35477. * @param mesh defines the mesh associated with this material
  35478. * @param onCompiled defines a function to execute once the material is compiled
  35479. * @param options defines the options to configure the compilation
  35480. */
  35481. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35482. var _this = this;
  35483. var localOptions = __assign({ clipPlane: false }, options);
  35484. var subMesh = new BABYLON.BaseSubMesh();
  35485. var scene = this.getScene();
  35486. var checkReady = function () {
  35487. if (!_this._scene || !_this._scene.getEngine()) {
  35488. return;
  35489. }
  35490. if (subMesh._materialDefines) {
  35491. subMesh._materialDefines._renderId = -1;
  35492. }
  35493. var clipPlaneState = scene.clipPlane;
  35494. if (localOptions.clipPlane) {
  35495. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35496. }
  35497. if (_this.storeEffectOnSubMeshes) {
  35498. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35499. if (onCompiled) {
  35500. onCompiled(_this);
  35501. }
  35502. }
  35503. else {
  35504. setTimeout(checkReady, 16);
  35505. }
  35506. }
  35507. else {
  35508. if (_this.isReady(mesh)) {
  35509. if (onCompiled) {
  35510. onCompiled(_this);
  35511. }
  35512. }
  35513. else {
  35514. setTimeout(checkReady, 16);
  35515. }
  35516. }
  35517. if (localOptions.clipPlane) {
  35518. scene.clipPlane = clipPlaneState;
  35519. }
  35520. };
  35521. checkReady();
  35522. };
  35523. /**
  35524. * Force shader compilation
  35525. * @param mesh defines the mesh that will use this material
  35526. * @param options defines additional options for compiling the shaders
  35527. * @returns a promise that resolves when the compilation completes
  35528. */
  35529. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35530. var _this = this;
  35531. return new Promise(function (resolve) {
  35532. _this.forceCompilation(mesh, function () {
  35533. resolve();
  35534. }, options);
  35535. });
  35536. };
  35537. /**
  35538. * Marks a define in the material to indicate that it needs to be re-computed
  35539. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35540. */
  35541. Material.prototype.markAsDirty = function (flag) {
  35542. if (flag & Material.TextureDirtyFlag) {
  35543. this._markAllSubMeshesAsTexturesDirty();
  35544. }
  35545. if (flag & Material.LightDirtyFlag) {
  35546. this._markAllSubMeshesAsLightsDirty();
  35547. }
  35548. if (flag & Material.FresnelDirtyFlag) {
  35549. this._markAllSubMeshesAsFresnelDirty();
  35550. }
  35551. if (flag & Material.AttributesDirtyFlag) {
  35552. this._markAllSubMeshesAsAttributesDirty();
  35553. }
  35554. if (flag & Material.MiscDirtyFlag) {
  35555. this._markAllSubMeshesAsMiscDirty();
  35556. }
  35557. this.getScene().resetCachedMaterial();
  35558. };
  35559. /**
  35560. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35561. * @param func defines a function which checks material defines against the submeshes
  35562. */
  35563. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35564. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35565. var mesh = _a[_i];
  35566. if (!mesh.subMeshes) {
  35567. continue;
  35568. }
  35569. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35570. var subMesh = _c[_b];
  35571. if (subMesh.getMaterial() !== this) {
  35572. continue;
  35573. }
  35574. if (!subMesh._materialDefines) {
  35575. continue;
  35576. }
  35577. func(subMesh._materialDefines);
  35578. }
  35579. }
  35580. };
  35581. /**
  35582. * Indicates that image processing needs to be re-calculated for all submeshes
  35583. */
  35584. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35585. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35586. };
  35587. /**
  35588. * Indicates that textures need to be re-calculated for all submeshes
  35589. */
  35590. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35591. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35592. };
  35593. /**
  35594. * Indicates that fresnel needs to be re-calculated for all submeshes
  35595. */
  35596. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35597. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35598. };
  35599. /**
  35600. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35601. */
  35602. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35603. this._markAllSubMeshesAsDirty(function (defines) {
  35604. defines.markAsFresnelDirty();
  35605. defines.markAsMiscDirty();
  35606. });
  35607. };
  35608. /**
  35609. * Indicates that lights need to be re-calculated for all submeshes
  35610. */
  35611. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35612. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35613. };
  35614. /**
  35615. * Indicates that attributes need to be re-calculated for all submeshes
  35616. */
  35617. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35618. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35619. };
  35620. /**
  35621. * Indicates that misc needs to be re-calculated for all submeshes
  35622. */
  35623. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35624. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35625. };
  35626. /**
  35627. * Indicates that textures and misc need to be re-calculated for all submeshes
  35628. */
  35629. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35630. this._markAllSubMeshesAsDirty(function (defines) {
  35631. defines.markAsTexturesDirty();
  35632. defines.markAsMiscDirty();
  35633. });
  35634. };
  35635. /**
  35636. * Disposes the material
  35637. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35638. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35639. */
  35640. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35641. // Animations
  35642. this.getScene().stopAnimation(this);
  35643. this.getScene().freeProcessedMaterials();
  35644. // Remove from scene
  35645. var index = this._scene.materials.indexOf(this);
  35646. if (index >= 0) {
  35647. this._scene.materials.splice(index, 1);
  35648. }
  35649. // Remove from meshes
  35650. for (index = 0; index < this._scene.meshes.length; index++) {
  35651. var mesh = this._scene.meshes[index];
  35652. if (mesh.material === this) {
  35653. mesh.material = null;
  35654. if (mesh.geometry) {
  35655. var geometry = (mesh.geometry);
  35656. if (this.storeEffectOnSubMeshes) {
  35657. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35658. var subMesh = _a[_i];
  35659. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35660. if (forceDisposeEffect && subMesh._materialEffect) {
  35661. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35662. }
  35663. }
  35664. }
  35665. else {
  35666. geometry._releaseVertexArrayObject(this._effect);
  35667. }
  35668. }
  35669. }
  35670. }
  35671. this._uniformBuffer.dispose();
  35672. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35673. if (forceDisposeEffect && this._effect) {
  35674. if (!this.storeEffectOnSubMeshes) {
  35675. this._scene.getEngine()._releaseEffect(this._effect);
  35676. }
  35677. this._effect = null;
  35678. }
  35679. // Callback
  35680. this.onDisposeObservable.notifyObservers(this);
  35681. this.onDisposeObservable.clear();
  35682. this.onBindObservable.clear();
  35683. this.onUnBindObservable.clear();
  35684. };
  35685. /**
  35686. * Serializes this material
  35687. * @returns the serialized material object
  35688. */
  35689. Material.prototype.serialize = function () {
  35690. return BABYLON.SerializationHelper.Serialize(this);
  35691. };
  35692. /**
  35693. * Creates a MultiMaterial from parsed MultiMaterial data.
  35694. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35695. * @param scene defines the hosting scene
  35696. * @returns a new MultiMaterial
  35697. */
  35698. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35699. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35700. multiMaterial.id = parsedMultiMaterial.id;
  35701. if (BABYLON.Tags) {
  35702. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35703. }
  35704. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35705. var subMatId = parsedMultiMaterial.materials[matIndex];
  35706. if (subMatId) {
  35707. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35708. }
  35709. else {
  35710. multiMaterial.subMaterials.push(null);
  35711. }
  35712. }
  35713. return multiMaterial;
  35714. };
  35715. /**
  35716. * Creates a material from parsed material data
  35717. * @param parsedMaterial defines parsed material data
  35718. * @param scene defines the hosting scene
  35719. * @param rootUrl defines the root URL to use to load textures
  35720. * @returns a new material
  35721. */
  35722. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35723. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35724. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35725. }
  35726. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35727. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35728. if (!BABYLON.LegacyPBRMaterial) {
  35729. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35730. return;
  35731. }
  35732. }
  35733. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35734. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35735. };
  35736. // Triangle views
  35737. Material._TriangleFillMode = 0;
  35738. Material._WireFrameFillMode = 1;
  35739. Material._PointFillMode = 2;
  35740. // Draw modes
  35741. Material._PointListDrawMode = 3;
  35742. Material._LineListDrawMode = 4;
  35743. Material._LineLoopDrawMode = 5;
  35744. Material._LineStripDrawMode = 6;
  35745. Material._TriangleStripDrawMode = 7;
  35746. Material._TriangleFanDrawMode = 8;
  35747. /**
  35748. * Stores the clock-wise side orientation
  35749. */
  35750. Material._ClockWiseSideOrientation = 0;
  35751. /**
  35752. * Stores the counter clock-wise side orientation
  35753. */
  35754. Material._CounterClockWiseSideOrientation = 1;
  35755. /**
  35756. * The dirty texture flag value
  35757. */
  35758. Material._TextureDirtyFlag = 1;
  35759. /**
  35760. * The dirty light flag value
  35761. */
  35762. Material._LightDirtyFlag = 2;
  35763. /**
  35764. * The dirty fresnel flag value
  35765. */
  35766. Material._FresnelDirtyFlag = 4;
  35767. /**
  35768. * The dirty attribute flag value
  35769. */
  35770. Material._AttributesDirtyFlag = 8;
  35771. /**
  35772. * The dirty misc flag value
  35773. */
  35774. Material._MiscDirtyFlag = 16;
  35775. __decorate([
  35776. BABYLON.serialize()
  35777. ], Material.prototype, "id", void 0);
  35778. __decorate([
  35779. BABYLON.serialize()
  35780. ], Material.prototype, "uniqueId", void 0);
  35781. __decorate([
  35782. BABYLON.serialize()
  35783. ], Material.prototype, "name", void 0);
  35784. __decorate([
  35785. BABYLON.serialize()
  35786. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35787. __decorate([
  35788. BABYLON.serialize()
  35789. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35790. __decorate([
  35791. BABYLON.serialize()
  35792. ], Material.prototype, "state", void 0);
  35793. __decorate([
  35794. BABYLON.serialize("alpha")
  35795. ], Material.prototype, "_alpha", void 0);
  35796. __decorate([
  35797. BABYLON.serialize("backFaceCulling")
  35798. ], Material.prototype, "_backFaceCulling", void 0);
  35799. __decorate([
  35800. BABYLON.serialize()
  35801. ], Material.prototype, "sideOrientation", void 0);
  35802. __decorate([
  35803. BABYLON.serialize("alphaMode")
  35804. ], Material.prototype, "_alphaMode", void 0);
  35805. __decorate([
  35806. BABYLON.serialize()
  35807. ], Material.prototype, "_needDepthPrePass", void 0);
  35808. __decorate([
  35809. BABYLON.serialize()
  35810. ], Material.prototype, "disableDepthWrite", void 0);
  35811. __decorate([
  35812. BABYLON.serialize()
  35813. ], Material.prototype, "forceDepthWrite", void 0);
  35814. __decorate([
  35815. BABYLON.serialize()
  35816. ], Material.prototype, "separateCullingPass", void 0);
  35817. __decorate([
  35818. BABYLON.serialize("fogEnabled")
  35819. ], Material.prototype, "_fogEnabled", void 0);
  35820. __decorate([
  35821. BABYLON.serialize()
  35822. ], Material.prototype, "pointSize", void 0);
  35823. __decorate([
  35824. BABYLON.serialize()
  35825. ], Material.prototype, "zOffset", void 0);
  35826. __decorate([
  35827. BABYLON.serialize()
  35828. ], Material.prototype, "wireframe", null);
  35829. __decorate([
  35830. BABYLON.serialize()
  35831. ], Material.prototype, "pointsCloud", null);
  35832. __decorate([
  35833. BABYLON.serialize()
  35834. ], Material.prototype, "fillMode", null);
  35835. return Material;
  35836. }());
  35837. BABYLON.Material = Material;
  35838. })(BABYLON || (BABYLON = {}));
  35839. //# sourceMappingURL=babylon.material.js.map
  35840. var BABYLON;
  35841. (function (BABYLON) {
  35842. var UniformBuffer = /** @class */ (function () {
  35843. /**
  35844. * Uniform buffer objects.
  35845. *
  35846. * Handles blocks of uniform on the GPU.
  35847. *
  35848. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35849. *
  35850. * For more information, please refer to :
  35851. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35852. */
  35853. function UniformBuffer(engine, data, dynamic) {
  35854. this._engine = engine;
  35855. this._noUBO = !engine.supportsUniformBuffers;
  35856. this._dynamic = dynamic;
  35857. this._data = data || [];
  35858. this._uniformLocations = {};
  35859. this._uniformSizes = {};
  35860. this._uniformLocationPointer = 0;
  35861. this._needSync = false;
  35862. if (this._noUBO) {
  35863. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35864. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35865. this.updateFloat = this._updateFloatForEffect;
  35866. this.updateFloat2 = this._updateFloat2ForEffect;
  35867. this.updateFloat3 = this._updateFloat3ForEffect;
  35868. this.updateFloat4 = this._updateFloat4ForEffect;
  35869. this.updateMatrix = this._updateMatrixForEffect;
  35870. this.updateVector3 = this._updateVector3ForEffect;
  35871. this.updateVector4 = this._updateVector4ForEffect;
  35872. this.updateColor3 = this._updateColor3ForEffect;
  35873. this.updateColor4 = this._updateColor4ForEffect;
  35874. }
  35875. else {
  35876. this._engine._uniformBuffers.push(this);
  35877. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35878. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35879. this.updateFloat = this._updateFloatForUniform;
  35880. this.updateFloat2 = this._updateFloat2ForUniform;
  35881. this.updateFloat3 = this._updateFloat3ForUniform;
  35882. this.updateFloat4 = this._updateFloat4ForUniform;
  35883. this.updateMatrix = this._updateMatrixForUniform;
  35884. this.updateVector3 = this._updateVector3ForUniform;
  35885. this.updateVector4 = this._updateVector4ForUniform;
  35886. this.updateColor3 = this._updateColor3ForUniform;
  35887. this.updateColor4 = this._updateColor4ForUniform;
  35888. }
  35889. }
  35890. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35891. // Properties
  35892. /**
  35893. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35894. * or just falling back on setUniformXXX calls.
  35895. */
  35896. get: function () {
  35897. return !this._noUBO;
  35898. },
  35899. enumerable: true,
  35900. configurable: true
  35901. });
  35902. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35903. /**
  35904. * Indicates if the WebGL underlying uniform buffer is in sync
  35905. * with the javascript cache data.
  35906. */
  35907. get: function () {
  35908. return !this._needSync;
  35909. },
  35910. enumerable: true,
  35911. configurable: true
  35912. });
  35913. /**
  35914. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35915. * Also, a dynamic UniformBuffer will disable cache verification and always
  35916. * update the underlying WebGL uniform buffer to the GPU.
  35917. */
  35918. UniformBuffer.prototype.isDynamic = function () {
  35919. return this._dynamic !== undefined;
  35920. };
  35921. /**
  35922. * The data cache on JS side.
  35923. */
  35924. UniformBuffer.prototype.getData = function () {
  35925. return this._bufferData;
  35926. };
  35927. /**
  35928. * The underlying WebGL Uniform buffer.
  35929. */
  35930. UniformBuffer.prototype.getBuffer = function () {
  35931. return this._buffer;
  35932. };
  35933. /**
  35934. * std140 layout specifies how to align data within an UBO structure.
  35935. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35936. * for specs.
  35937. */
  35938. UniformBuffer.prototype._fillAlignment = function (size) {
  35939. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35940. // and 4x4 matrices
  35941. // TODO : change if other types are used
  35942. var alignment;
  35943. if (size <= 2) {
  35944. alignment = size;
  35945. }
  35946. else {
  35947. alignment = 4;
  35948. }
  35949. if ((this._uniformLocationPointer % alignment) !== 0) {
  35950. var oldPointer = this._uniformLocationPointer;
  35951. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35952. var diff = this._uniformLocationPointer - oldPointer;
  35953. for (var i = 0; i < diff; i++) {
  35954. this._data.push(0);
  35955. }
  35956. }
  35957. };
  35958. /**
  35959. * Adds an uniform in the buffer.
  35960. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35961. * for the layout to be correct !
  35962. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35963. * @param {number|number[]} size Data size, or data directly.
  35964. */
  35965. UniformBuffer.prototype.addUniform = function (name, size) {
  35966. if (this._noUBO) {
  35967. return;
  35968. }
  35969. if (this._uniformLocations[name] !== undefined) {
  35970. // Already existing uniform
  35971. return;
  35972. }
  35973. // This function must be called in the order of the shader layout !
  35974. // size can be the size of the uniform, or data directly
  35975. var data;
  35976. if (size instanceof Array) {
  35977. data = size;
  35978. size = data.length;
  35979. }
  35980. else {
  35981. size = size;
  35982. data = [];
  35983. // Fill with zeros
  35984. for (var i = 0; i < size; i++) {
  35985. data.push(0);
  35986. }
  35987. }
  35988. this._fillAlignment(size);
  35989. this._uniformSizes[name] = size;
  35990. this._uniformLocations[name] = this._uniformLocationPointer;
  35991. this._uniformLocationPointer += size;
  35992. for (var i = 0; i < size; i++) {
  35993. this._data.push(data[i]);
  35994. }
  35995. this._needSync = true;
  35996. };
  35997. /**
  35998. * Wrapper for addUniform.
  35999. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36000. * @param {Matrix} mat A 4x4 matrix.
  36001. */
  36002. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36003. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36004. };
  36005. /**
  36006. * Wrapper for addUniform.
  36007. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36008. * @param {number} x
  36009. * @param {number} y
  36010. */
  36011. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36012. var temp = [x, y];
  36013. this.addUniform(name, temp);
  36014. };
  36015. /**
  36016. * Wrapper for addUniform.
  36017. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36018. * @param {number} x
  36019. * @param {number} y
  36020. * @param {number} z
  36021. */
  36022. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36023. var temp = [x, y, z];
  36024. this.addUniform(name, temp);
  36025. };
  36026. /**
  36027. * Wrapper for addUniform.
  36028. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36029. * @param {Color3} color
  36030. */
  36031. UniformBuffer.prototype.addColor3 = function (name, color) {
  36032. var temp = new Array();
  36033. color.toArray(temp);
  36034. this.addUniform(name, temp);
  36035. };
  36036. /**
  36037. * Wrapper for addUniform.
  36038. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36039. * @param {Color3} color
  36040. * @param {number} alpha
  36041. */
  36042. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36043. var temp = new Array();
  36044. color.toArray(temp);
  36045. temp.push(alpha);
  36046. this.addUniform(name, temp);
  36047. };
  36048. /**
  36049. * Wrapper for addUniform.
  36050. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36051. * @param {Vector3} vector
  36052. */
  36053. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36054. var temp = new Array();
  36055. vector.toArray(temp);
  36056. this.addUniform(name, temp);
  36057. };
  36058. /**
  36059. * Wrapper for addUniform.
  36060. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36061. */
  36062. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36063. this.addUniform(name, 12);
  36064. };
  36065. /**
  36066. * Wrapper for addUniform.
  36067. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36068. */
  36069. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36070. this.addUniform(name, 8);
  36071. };
  36072. /**
  36073. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36074. */
  36075. UniformBuffer.prototype.create = function () {
  36076. if (this._noUBO) {
  36077. return;
  36078. }
  36079. if (this._buffer) {
  36080. return; // nothing to do
  36081. }
  36082. // See spec, alignment must be filled as a vec4
  36083. this._fillAlignment(4);
  36084. this._bufferData = new Float32Array(this._data);
  36085. this._rebuild();
  36086. this._needSync = true;
  36087. };
  36088. UniformBuffer.prototype._rebuild = function () {
  36089. if (this._noUBO) {
  36090. return;
  36091. }
  36092. if (this._dynamic) {
  36093. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36094. }
  36095. else {
  36096. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36097. }
  36098. };
  36099. /**
  36100. * Updates the WebGL Uniform Buffer on the GPU.
  36101. * If the `dynamic` flag is set to true, no cache comparison is done.
  36102. * Otherwise, the buffer will be updated only if the cache differs.
  36103. */
  36104. UniformBuffer.prototype.update = function () {
  36105. if (!this._buffer) {
  36106. this.create();
  36107. return;
  36108. }
  36109. if (!this._dynamic && !this._needSync) {
  36110. return;
  36111. }
  36112. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36113. this._needSync = false;
  36114. };
  36115. /**
  36116. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36117. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36118. * @param {number[]|Float32Array} data Flattened data
  36119. * @param {number} size Size of the data.
  36120. */
  36121. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36122. var location = this._uniformLocations[uniformName];
  36123. if (location === undefined) {
  36124. if (this._buffer) {
  36125. // Cannot add an uniform if the buffer is already created
  36126. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36127. return;
  36128. }
  36129. this.addUniform(uniformName, size);
  36130. location = this._uniformLocations[uniformName];
  36131. }
  36132. if (!this._buffer) {
  36133. this.create();
  36134. }
  36135. if (!this._dynamic) {
  36136. // Cache for static uniform buffers
  36137. var changed = false;
  36138. for (var i = 0; i < size; i++) {
  36139. if (this._bufferData[location + i] !== data[i]) {
  36140. changed = true;
  36141. this._bufferData[location + i] = data[i];
  36142. }
  36143. }
  36144. this._needSync = this._needSync || changed;
  36145. }
  36146. else {
  36147. // No cache for dynamic
  36148. for (var i = 0; i < size; i++) {
  36149. this._bufferData[location + i] = data[i];
  36150. }
  36151. }
  36152. };
  36153. // Update methods
  36154. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36155. // To match std140, matrix must be realigned
  36156. for (var i = 0; i < 3; i++) {
  36157. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36158. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36159. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36160. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36161. }
  36162. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36163. };
  36164. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36165. this._currentEffect.setMatrix3x3(name, matrix);
  36166. };
  36167. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36168. this._currentEffect.setMatrix2x2(name, matrix);
  36169. };
  36170. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36171. // To match std140, matrix must be realigned
  36172. for (var i = 0; i < 2; i++) {
  36173. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36174. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36175. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36176. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36177. }
  36178. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36179. };
  36180. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36181. this._currentEffect.setFloat(name, x);
  36182. };
  36183. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36184. UniformBuffer._tempBuffer[0] = x;
  36185. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36186. };
  36187. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36188. if (suffix === void 0) { suffix = ""; }
  36189. this._currentEffect.setFloat2(name + suffix, x, y);
  36190. };
  36191. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36192. if (suffix === void 0) { suffix = ""; }
  36193. UniformBuffer._tempBuffer[0] = x;
  36194. UniformBuffer._tempBuffer[1] = y;
  36195. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36196. };
  36197. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36198. if (suffix === void 0) { suffix = ""; }
  36199. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36200. };
  36201. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36202. if (suffix === void 0) { suffix = ""; }
  36203. UniformBuffer._tempBuffer[0] = x;
  36204. UniformBuffer._tempBuffer[1] = y;
  36205. UniformBuffer._tempBuffer[2] = z;
  36206. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36207. };
  36208. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36209. if (suffix === void 0) { suffix = ""; }
  36210. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36211. };
  36212. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36213. if (suffix === void 0) { suffix = ""; }
  36214. UniformBuffer._tempBuffer[0] = x;
  36215. UniformBuffer._tempBuffer[1] = y;
  36216. UniformBuffer._tempBuffer[2] = z;
  36217. UniformBuffer._tempBuffer[3] = w;
  36218. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36219. };
  36220. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36221. this._currentEffect.setMatrix(name, mat);
  36222. };
  36223. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36224. this.updateUniform(name, mat.toArray(), 16);
  36225. };
  36226. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36227. this._currentEffect.setVector3(name, vector);
  36228. };
  36229. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36230. vector.toArray(UniformBuffer._tempBuffer);
  36231. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36232. };
  36233. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36234. this._currentEffect.setVector4(name, vector);
  36235. };
  36236. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36237. vector.toArray(UniformBuffer._tempBuffer);
  36238. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36239. };
  36240. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36241. if (suffix === void 0) { suffix = ""; }
  36242. this._currentEffect.setColor3(name + suffix, color);
  36243. };
  36244. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36245. if (suffix === void 0) { suffix = ""; }
  36246. color.toArray(UniformBuffer._tempBuffer);
  36247. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36248. };
  36249. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36250. if (suffix === void 0) { suffix = ""; }
  36251. this._currentEffect.setColor4(name + suffix, color, alpha);
  36252. };
  36253. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36254. if (suffix === void 0) { suffix = ""; }
  36255. color.toArray(UniformBuffer._tempBuffer);
  36256. UniformBuffer._tempBuffer[3] = alpha;
  36257. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36258. };
  36259. /**
  36260. * Sets a sampler uniform on the effect.
  36261. * @param {string} name Name of the sampler.
  36262. * @param {Texture} texture
  36263. */
  36264. UniformBuffer.prototype.setTexture = function (name, texture) {
  36265. this._currentEffect.setTexture(name, texture);
  36266. };
  36267. /**
  36268. * Directly updates the value of the uniform in the cache AND on the GPU.
  36269. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36270. * @param {number[]|Float32Array} data Flattened data
  36271. */
  36272. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36273. this.updateUniform(uniformName, data, data.length);
  36274. this.update();
  36275. };
  36276. /**
  36277. * Binds this uniform buffer to an effect.
  36278. * @param {Effect} effect
  36279. * @param {string} name Name of the uniform block in the shader.
  36280. */
  36281. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36282. this._currentEffect = effect;
  36283. if (this._noUBO || !this._buffer) {
  36284. return;
  36285. }
  36286. effect.bindUniformBuffer(this._buffer, name);
  36287. };
  36288. /**
  36289. * Disposes the uniform buffer.
  36290. */
  36291. UniformBuffer.prototype.dispose = function () {
  36292. if (this._noUBO) {
  36293. return;
  36294. }
  36295. var index = this._engine._uniformBuffers.indexOf(this);
  36296. if (index !== -1) {
  36297. this._engine._uniformBuffers.splice(index, 1);
  36298. }
  36299. if (!this._buffer) {
  36300. return;
  36301. }
  36302. if (this._engine._releaseBuffer(this._buffer)) {
  36303. this._buffer = null;
  36304. }
  36305. };
  36306. // Pool for avoiding memory leaks
  36307. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36308. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36309. return UniformBuffer;
  36310. }());
  36311. BABYLON.UniformBuffer = UniformBuffer;
  36312. })(BABYLON || (BABYLON = {}));
  36313. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36314. var BABYLON;
  36315. (function (BABYLON) {
  36316. /**
  36317. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36318. */
  36319. var VertexData = /** @class */ (function () {
  36320. function VertexData() {
  36321. }
  36322. /**
  36323. * Uses the passed data array to set the set the values for the specified kind of data
  36324. * @param data a linear array of floating numbers
  36325. * @param kind the type of data that is being set, eg positions, colors etc
  36326. */
  36327. VertexData.prototype.set = function (data, kind) {
  36328. switch (kind) {
  36329. case BABYLON.VertexBuffer.PositionKind:
  36330. this.positions = data;
  36331. break;
  36332. case BABYLON.VertexBuffer.NormalKind:
  36333. this.normals = data;
  36334. break;
  36335. case BABYLON.VertexBuffer.TangentKind:
  36336. this.tangents = data;
  36337. break;
  36338. case BABYLON.VertexBuffer.UVKind:
  36339. this.uvs = data;
  36340. break;
  36341. case BABYLON.VertexBuffer.UV2Kind:
  36342. this.uvs2 = data;
  36343. break;
  36344. case BABYLON.VertexBuffer.UV3Kind:
  36345. this.uvs3 = data;
  36346. break;
  36347. case BABYLON.VertexBuffer.UV4Kind:
  36348. this.uvs4 = data;
  36349. break;
  36350. case BABYLON.VertexBuffer.UV5Kind:
  36351. this.uvs5 = data;
  36352. break;
  36353. case BABYLON.VertexBuffer.UV6Kind:
  36354. this.uvs6 = data;
  36355. break;
  36356. case BABYLON.VertexBuffer.ColorKind:
  36357. this.colors = data;
  36358. break;
  36359. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36360. this.matricesIndices = data;
  36361. break;
  36362. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36363. this.matricesWeights = data;
  36364. break;
  36365. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36366. this.matricesIndicesExtra = data;
  36367. break;
  36368. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36369. this.matricesWeightsExtra = data;
  36370. break;
  36371. }
  36372. };
  36373. /**
  36374. * Associates the vertexData to the passed Mesh.
  36375. * Sets it as updatable or not (default `false`)
  36376. * @param mesh the mesh the vertexData is applied to
  36377. * @param updatable when used and having the value true allows new data to update the vertexData
  36378. * @returns the VertexData
  36379. */
  36380. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36381. this._applyTo(mesh, updatable);
  36382. return this;
  36383. };
  36384. /**
  36385. * Associates the vertexData to the passed Geometry.
  36386. * Sets it as updatable or not (default `false`)
  36387. * @param geometry the geometry the vertexData is applied to
  36388. * @param updatable when used and having the value true allows new data to update the vertexData
  36389. * @returns VertexData
  36390. */
  36391. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36392. this._applyTo(geometry, updatable);
  36393. return this;
  36394. };
  36395. /**
  36396. * Updates the associated mesh
  36397. * @param mesh the mesh to be updated
  36398. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36399. * @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
  36400. * @returns VertexData
  36401. */
  36402. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36403. this._update(mesh);
  36404. return this;
  36405. };
  36406. /**
  36407. * Updates the associated geometry
  36408. * @param geometry the geometry to be updated
  36409. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36410. * @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
  36411. * @returns VertexData.
  36412. */
  36413. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36414. this._update(geometry);
  36415. return this;
  36416. };
  36417. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36418. if (updatable === void 0) { updatable = false; }
  36419. if (this.positions) {
  36420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36421. }
  36422. if (this.normals) {
  36423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36424. }
  36425. if (this.tangents) {
  36426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36427. }
  36428. if (this.uvs) {
  36429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36430. }
  36431. if (this.uvs2) {
  36432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36433. }
  36434. if (this.uvs3) {
  36435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36436. }
  36437. if (this.uvs4) {
  36438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36439. }
  36440. if (this.uvs5) {
  36441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36442. }
  36443. if (this.uvs6) {
  36444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36445. }
  36446. if (this.colors) {
  36447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36448. }
  36449. if (this.matricesIndices) {
  36450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36451. }
  36452. if (this.matricesWeights) {
  36453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36454. }
  36455. if (this.matricesIndicesExtra) {
  36456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36457. }
  36458. if (this.matricesWeightsExtra) {
  36459. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36460. }
  36461. if (this.indices) {
  36462. meshOrGeometry.setIndices(this.indices, null, updatable);
  36463. }
  36464. else {
  36465. meshOrGeometry.setIndices([], null);
  36466. }
  36467. return this;
  36468. };
  36469. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36470. if (this.positions) {
  36471. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36472. }
  36473. if (this.normals) {
  36474. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36475. }
  36476. if (this.tangents) {
  36477. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36478. }
  36479. if (this.uvs) {
  36480. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36481. }
  36482. if (this.uvs2) {
  36483. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36484. }
  36485. if (this.uvs3) {
  36486. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36487. }
  36488. if (this.uvs4) {
  36489. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36490. }
  36491. if (this.uvs5) {
  36492. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36493. }
  36494. if (this.uvs6) {
  36495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36496. }
  36497. if (this.colors) {
  36498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36499. }
  36500. if (this.matricesIndices) {
  36501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36502. }
  36503. if (this.matricesWeights) {
  36504. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36505. }
  36506. if (this.matricesIndicesExtra) {
  36507. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36508. }
  36509. if (this.matricesWeightsExtra) {
  36510. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36511. }
  36512. if (this.indices) {
  36513. meshOrGeometry.setIndices(this.indices, null);
  36514. }
  36515. return this;
  36516. };
  36517. /**
  36518. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36519. * @param matrix the transforming matrix
  36520. * @returns the VertexData
  36521. */
  36522. VertexData.prototype.transform = function (matrix) {
  36523. var transformed = BABYLON.Vector3.Zero();
  36524. var index;
  36525. if (this.positions) {
  36526. var position = BABYLON.Vector3.Zero();
  36527. for (index = 0; index < this.positions.length; index += 3) {
  36528. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36529. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36530. this.positions[index] = transformed.x;
  36531. this.positions[index + 1] = transformed.y;
  36532. this.positions[index + 2] = transformed.z;
  36533. }
  36534. }
  36535. if (this.normals) {
  36536. var normal = BABYLON.Vector3.Zero();
  36537. for (index = 0; index < this.normals.length; index += 3) {
  36538. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36539. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36540. this.normals[index] = transformed.x;
  36541. this.normals[index + 1] = transformed.y;
  36542. this.normals[index + 2] = transformed.z;
  36543. }
  36544. }
  36545. if (this.tangents) {
  36546. var tangent = BABYLON.Vector4.Zero();
  36547. var tangentTransformed = BABYLON.Vector4.Zero();
  36548. for (index = 0; index < this.tangents.length; index += 4) {
  36549. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36550. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36551. this.tangents[index] = tangentTransformed.x;
  36552. this.tangents[index + 1] = tangentTransformed.y;
  36553. this.tangents[index + 2] = tangentTransformed.z;
  36554. this.tangents[index + 3] = tangentTransformed.w;
  36555. }
  36556. }
  36557. return this;
  36558. };
  36559. /**
  36560. * Merges the passed VertexData into the current one
  36561. * @param other the VertexData to be merged into the current one
  36562. * @returns the modified VertexData
  36563. */
  36564. VertexData.prototype.merge = function (other) {
  36565. this._validate();
  36566. other._validate();
  36567. if (!this.normals !== !other.normals ||
  36568. !this.tangents !== !other.tangents ||
  36569. !this.uvs !== !other.uvs ||
  36570. !this.uvs2 !== !other.uvs2 ||
  36571. !this.uvs3 !== !other.uvs3 ||
  36572. !this.uvs4 !== !other.uvs4 ||
  36573. !this.uvs5 !== !other.uvs5 ||
  36574. !this.uvs6 !== !other.uvs6 ||
  36575. !this.colors !== !other.colors ||
  36576. !this.matricesIndices !== !other.matricesIndices ||
  36577. !this.matricesWeights !== !other.matricesWeights ||
  36578. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36579. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36580. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36581. }
  36582. if (other.indices) {
  36583. if (!this.indices) {
  36584. this.indices = [];
  36585. }
  36586. var offset = this.positions ? this.positions.length / 3 : 0;
  36587. for (var index = 0; index < other.indices.length; index++) {
  36588. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36589. this.indices.push(other.indices[index] + offset);
  36590. }
  36591. }
  36592. this.positions = this._mergeElement(this.positions, other.positions);
  36593. this.normals = this._mergeElement(this.normals, other.normals);
  36594. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36595. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36596. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36597. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36598. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36599. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36600. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36601. this.colors = this._mergeElement(this.colors, other.colors);
  36602. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36603. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36604. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36605. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36606. return this;
  36607. };
  36608. VertexData.prototype._mergeElement = function (source, other) {
  36609. if (!source) {
  36610. return other;
  36611. }
  36612. if (!other) {
  36613. return source;
  36614. }
  36615. var len = other.length + source.length;
  36616. var isSrcTypedArray = source instanceof Float32Array;
  36617. var isOthTypedArray = other instanceof Float32Array;
  36618. // use non-loop method when the source is Float32Array
  36619. if (isSrcTypedArray) {
  36620. var ret32 = new Float32Array(len);
  36621. ret32.set(source);
  36622. ret32.set(other, source.length);
  36623. return ret32;
  36624. // source is number[], when other is also use concat
  36625. }
  36626. else if (!isOthTypedArray) {
  36627. return source.concat(other);
  36628. // source is a number[], but other is a Float32Array, loop required
  36629. }
  36630. else {
  36631. var ret = source.slice(0); // copy source to a separate array
  36632. for (var i = 0, len = other.length; i < len; i++) {
  36633. ret.push(other[i]);
  36634. }
  36635. return ret;
  36636. }
  36637. };
  36638. VertexData.prototype._validate = function () {
  36639. if (!this.positions) {
  36640. throw new Error("Positions are required");
  36641. }
  36642. var getElementCount = function (kind, values) {
  36643. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36644. if ((values.length % stride) !== 0) {
  36645. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36646. }
  36647. return values.length / stride;
  36648. };
  36649. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36650. var validateElementCount = function (kind, values) {
  36651. var elementCount = getElementCount(kind, values);
  36652. if (elementCount !== positionsElementCount) {
  36653. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36654. }
  36655. };
  36656. if (this.normals)
  36657. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36658. if (this.tangents)
  36659. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36660. if (this.uvs)
  36661. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36662. if (this.uvs2)
  36663. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36664. if (this.uvs3)
  36665. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36666. if (this.uvs4)
  36667. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36668. if (this.uvs5)
  36669. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36670. if (this.uvs6)
  36671. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36672. if (this.colors)
  36673. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36674. if (this.matricesIndices)
  36675. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36676. if (this.matricesWeights)
  36677. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36678. if (this.matricesIndicesExtra)
  36679. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36680. if (this.matricesWeightsExtra)
  36681. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36682. };
  36683. /**
  36684. * Serializes the VertexData
  36685. * @returns a serialized object
  36686. */
  36687. VertexData.prototype.serialize = function () {
  36688. var serializationObject = this.serialize();
  36689. if (this.positions) {
  36690. serializationObject.positions = this.positions;
  36691. }
  36692. if (this.normals) {
  36693. serializationObject.normals = this.normals;
  36694. }
  36695. if (this.tangents) {
  36696. serializationObject.tangents = this.tangents;
  36697. }
  36698. if (this.uvs) {
  36699. serializationObject.uvs = this.uvs;
  36700. }
  36701. if (this.uvs2) {
  36702. serializationObject.uvs2 = this.uvs2;
  36703. }
  36704. if (this.uvs3) {
  36705. serializationObject.uvs3 = this.uvs3;
  36706. }
  36707. if (this.uvs4) {
  36708. serializationObject.uvs4 = this.uvs4;
  36709. }
  36710. if (this.uvs5) {
  36711. serializationObject.uvs5 = this.uvs5;
  36712. }
  36713. if (this.uvs6) {
  36714. serializationObject.uvs6 = this.uvs6;
  36715. }
  36716. if (this.colors) {
  36717. serializationObject.colors = this.colors;
  36718. }
  36719. if (this.matricesIndices) {
  36720. serializationObject.matricesIndices = this.matricesIndices;
  36721. serializationObject.matricesIndices._isExpanded = true;
  36722. }
  36723. if (this.matricesWeights) {
  36724. serializationObject.matricesWeights = this.matricesWeights;
  36725. }
  36726. if (this.matricesIndicesExtra) {
  36727. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36728. serializationObject.matricesIndicesExtra._isExpanded = true;
  36729. }
  36730. if (this.matricesWeightsExtra) {
  36731. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36732. }
  36733. serializationObject.indices = this.indices;
  36734. return serializationObject;
  36735. };
  36736. // Statics
  36737. /**
  36738. * Extracts the vertexData from a mesh
  36739. * @param mesh the mesh from which to extract the VertexData
  36740. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36741. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36742. * @returns the object VertexData associated to the passed mesh
  36743. */
  36744. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36745. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36746. };
  36747. /**
  36748. * Extracts the vertexData from the geometry
  36749. * @param geometry the geometry from which to extract the VertexData
  36750. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36751. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36752. * @returns the object VertexData associated to the passed mesh
  36753. */
  36754. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36755. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36756. };
  36757. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36758. var result = new VertexData();
  36759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36760. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36761. }
  36762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36763. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36764. }
  36765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36766. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36767. }
  36768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36769. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36770. }
  36771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36772. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36773. }
  36774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36775. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36776. }
  36777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36778. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36779. }
  36780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36781. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36782. }
  36783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36784. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36785. }
  36786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36787. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36788. }
  36789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36790. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36791. }
  36792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36793. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36794. }
  36795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36796. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36797. }
  36798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36799. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36800. }
  36801. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36802. return result;
  36803. };
  36804. /**
  36805. * Creates the VertexData for a Ribbon
  36806. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36807. * * pathArray array of paths, each of which an array of successive Vector3
  36808. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36809. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36810. * * 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
  36811. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36812. * * 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)
  36813. * * 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)
  36814. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36815. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36816. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36817. * @returns the VertexData of the ribbon
  36818. */
  36819. VertexData.CreateRibbon = function (options) {
  36820. var pathArray = options.pathArray;
  36821. var closeArray = options.closeArray || false;
  36822. var closePath = options.closePath || false;
  36823. var invertUV = options.invertUV || false;
  36824. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36825. var offset = options.offset || defaultOffset;
  36826. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36827. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36828. var customUV = options.uvs;
  36829. var customColors = options.colors;
  36830. var positions = [];
  36831. var indices = [];
  36832. var normals = [];
  36833. var uvs = [];
  36834. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36835. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36836. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36837. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36838. var minlg; // minimal length among all paths from pathArray
  36839. var lg = []; // array of path lengths : nb of vertex per path
  36840. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36841. var p; // path iterator
  36842. var i; // point iterator
  36843. var j; // point iterator
  36844. // if single path in pathArray
  36845. if (pathArray.length < 2) {
  36846. var ar1 = [];
  36847. var ar2 = [];
  36848. for (i = 0; i < pathArray[0].length - offset; i++) {
  36849. ar1.push(pathArray[0][i]);
  36850. ar2.push(pathArray[0][i + offset]);
  36851. }
  36852. pathArray = [ar1, ar2];
  36853. }
  36854. // positions and horizontal distances (u)
  36855. var idc = 0;
  36856. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36857. var path;
  36858. var l;
  36859. minlg = pathArray[0].length;
  36860. var vectlg;
  36861. var dist;
  36862. for (p = 0; p < pathArray.length; p++) {
  36863. uTotalDistance[p] = 0;
  36864. us[p] = [0];
  36865. path = pathArray[p];
  36866. l = path.length;
  36867. minlg = (minlg < l) ? minlg : l;
  36868. j = 0;
  36869. while (j < l) {
  36870. positions.push(path[j].x, path[j].y, path[j].z);
  36871. if (j > 0) {
  36872. vectlg = path[j].subtract(path[j - 1]).length();
  36873. dist = vectlg + uTotalDistance[p];
  36874. us[p].push(dist);
  36875. uTotalDistance[p] = dist;
  36876. }
  36877. j++;
  36878. }
  36879. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36880. j--;
  36881. positions.push(path[0].x, path[0].y, path[0].z);
  36882. vectlg = path[j].subtract(path[0]).length();
  36883. dist = vectlg + uTotalDistance[p];
  36884. us[p].push(dist);
  36885. uTotalDistance[p] = dist;
  36886. }
  36887. lg[p] = l + closePathCorr;
  36888. idx[p] = idc;
  36889. idc += (l + closePathCorr);
  36890. }
  36891. // vertical distances (v)
  36892. var path1;
  36893. var path2;
  36894. var vertex1 = null;
  36895. var vertex2 = null;
  36896. for (i = 0; i < minlg + closePathCorr; i++) {
  36897. vTotalDistance[i] = 0;
  36898. vs[i] = [0];
  36899. for (p = 0; p < pathArray.length - 1; p++) {
  36900. path1 = pathArray[p];
  36901. path2 = pathArray[p + 1];
  36902. if (i === minlg) { // closePath
  36903. vertex1 = path1[0];
  36904. vertex2 = path2[0];
  36905. }
  36906. else {
  36907. vertex1 = path1[i];
  36908. vertex2 = path2[i];
  36909. }
  36910. vectlg = vertex2.subtract(vertex1).length();
  36911. dist = vectlg + vTotalDistance[i];
  36912. vs[i].push(dist);
  36913. vTotalDistance[i] = dist;
  36914. }
  36915. if (closeArray && vertex2 && vertex1) {
  36916. path1 = pathArray[p];
  36917. path2 = pathArray[0];
  36918. if (i === minlg) { // closePath
  36919. vertex2 = path2[0];
  36920. }
  36921. vectlg = vertex2.subtract(vertex1).length();
  36922. dist = vectlg + vTotalDistance[i];
  36923. vTotalDistance[i] = dist;
  36924. }
  36925. }
  36926. // uvs
  36927. var u;
  36928. var v;
  36929. if (customUV) {
  36930. for (p = 0; p < customUV.length; p++) {
  36931. uvs.push(customUV[p].x, customUV[p].y);
  36932. }
  36933. }
  36934. else {
  36935. for (p = 0; p < pathArray.length; p++) {
  36936. for (i = 0; i < minlg + closePathCorr; i++) {
  36937. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36938. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36939. if (invertUV) {
  36940. uvs.push(v, u);
  36941. }
  36942. else {
  36943. uvs.push(u, v);
  36944. }
  36945. }
  36946. }
  36947. }
  36948. // indices
  36949. p = 0; // path index
  36950. var pi = 0; // positions array index
  36951. var l1 = lg[p] - 1; // path1 length
  36952. var l2 = lg[p + 1] - 1; // path2 length
  36953. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36954. var shft = idx[1] - idx[0]; // shift
  36955. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36956. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36957. // 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
  36958. indices.push(pi, pi + shft, pi + 1);
  36959. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36960. pi += 1;
  36961. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36962. p++;
  36963. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36964. shft = idx[0] - idx[p];
  36965. l1 = lg[p] - 1;
  36966. l2 = lg[0] - 1;
  36967. }
  36968. else {
  36969. shft = idx[p + 1] - idx[p];
  36970. l1 = lg[p] - 1;
  36971. l2 = lg[p + 1] - 1;
  36972. }
  36973. pi = idx[p];
  36974. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36975. }
  36976. }
  36977. // normals
  36978. VertexData.ComputeNormals(positions, indices, normals);
  36979. if (closePath) { // update both the first and last vertex normals to their average value
  36980. var indexFirst = 0;
  36981. var indexLast = 0;
  36982. for (p = 0; p < pathArray.length; p++) {
  36983. indexFirst = idx[p] * 3;
  36984. if (p + 1 < pathArray.length) {
  36985. indexLast = (idx[p + 1] - 1) * 3;
  36986. }
  36987. else {
  36988. indexLast = normals.length - 3;
  36989. }
  36990. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36991. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36992. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36993. normals[indexLast] = normals[indexFirst];
  36994. normals[indexLast + 1] = normals[indexFirst + 1];
  36995. normals[indexLast + 2] = normals[indexFirst + 2];
  36996. }
  36997. }
  36998. // sides
  36999. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37000. // Colors
  37001. var colors = null;
  37002. if (customColors) {
  37003. colors = new Float32Array(customColors.length * 4);
  37004. for (var c = 0; c < customColors.length; c++) {
  37005. colors[c * 4] = customColors[c].r;
  37006. colors[c * 4 + 1] = customColors[c].g;
  37007. colors[c * 4 + 2] = customColors[c].b;
  37008. colors[c * 4 + 3] = customColors[c].a;
  37009. }
  37010. }
  37011. // Result
  37012. var vertexData = new VertexData();
  37013. var positions32 = new Float32Array(positions);
  37014. var normals32 = new Float32Array(normals);
  37015. var uvs32 = new Float32Array(uvs);
  37016. vertexData.indices = indices;
  37017. vertexData.positions = positions32;
  37018. vertexData.normals = normals32;
  37019. vertexData.uvs = uvs32;
  37020. if (colors) {
  37021. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37022. }
  37023. if (closePath) {
  37024. vertexData._idx = idx;
  37025. }
  37026. return vertexData;
  37027. };
  37028. /**
  37029. * Creates the VertexData for a box
  37030. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37031. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37032. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37033. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37034. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37035. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37036. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37037. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37038. * * 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)
  37039. * * 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)
  37040. * @returns the VertexData of the box
  37041. */
  37042. VertexData.CreateBox = function (options) {
  37043. var normalsSource = [
  37044. new BABYLON.Vector3(0, 0, 1),
  37045. new BABYLON.Vector3(0, 0, -1),
  37046. new BABYLON.Vector3(1, 0, 0),
  37047. new BABYLON.Vector3(-1, 0, 0),
  37048. new BABYLON.Vector3(0, 1, 0),
  37049. new BABYLON.Vector3(0, -1, 0)
  37050. ];
  37051. var indices = [];
  37052. var positions = [];
  37053. var normals = [];
  37054. var uvs = [];
  37055. var width = options.width || options.size || 1;
  37056. var height = options.height || options.size || 1;
  37057. var depth = options.depth || options.size || 1;
  37058. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37059. var faceUV = options.faceUV || new Array(6);
  37060. var faceColors = options.faceColors;
  37061. var colors = [];
  37062. // default face colors and UV if undefined
  37063. for (var f = 0; f < 6; f++) {
  37064. if (faceUV[f] === undefined) {
  37065. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37066. }
  37067. if (faceColors && faceColors[f] === undefined) {
  37068. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37069. }
  37070. }
  37071. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37072. // Create each face in turn.
  37073. for (var index = 0; index < normalsSource.length; index++) {
  37074. var normal = normalsSource[index];
  37075. // Get two vectors perpendicular to the face normal and to each other.
  37076. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37077. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37078. // Six indices (two triangles) per face.
  37079. var verticesLength = positions.length / 3;
  37080. indices.push(verticesLength);
  37081. indices.push(verticesLength + 1);
  37082. indices.push(verticesLength + 2);
  37083. indices.push(verticesLength);
  37084. indices.push(verticesLength + 2);
  37085. indices.push(verticesLength + 3);
  37086. // Four vertices per face.
  37087. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37088. positions.push(vertex.x, vertex.y, vertex.z);
  37089. normals.push(normal.x, normal.y, normal.z);
  37090. uvs.push(faceUV[index].z, faceUV[index].w);
  37091. if (faceColors) {
  37092. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37093. }
  37094. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37095. positions.push(vertex.x, vertex.y, vertex.z);
  37096. normals.push(normal.x, normal.y, normal.z);
  37097. uvs.push(faceUV[index].x, faceUV[index].w);
  37098. if (faceColors) {
  37099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37100. }
  37101. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37102. positions.push(vertex.x, vertex.y, vertex.z);
  37103. normals.push(normal.x, normal.y, normal.z);
  37104. uvs.push(faceUV[index].x, faceUV[index].y);
  37105. if (faceColors) {
  37106. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37107. }
  37108. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37109. positions.push(vertex.x, vertex.y, vertex.z);
  37110. normals.push(normal.x, normal.y, normal.z);
  37111. uvs.push(faceUV[index].z, faceUV[index].y);
  37112. if (faceColors) {
  37113. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37114. }
  37115. }
  37116. // sides
  37117. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37118. // Result
  37119. var vertexData = new VertexData();
  37120. vertexData.indices = indices;
  37121. vertexData.positions = positions;
  37122. vertexData.normals = normals;
  37123. vertexData.uvs = uvs;
  37124. if (faceColors) {
  37125. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37126. vertexData.colors = totalColors;
  37127. }
  37128. return vertexData;
  37129. };
  37130. /**
  37131. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37132. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37133. * * segments sets the number of horizontal strips optional, default 32
  37134. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37135. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37136. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37137. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37138. * * 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
  37139. * * 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
  37140. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37141. * * 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)
  37142. * * 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)
  37143. * @returns the VertexData of the ellipsoid
  37144. */
  37145. VertexData.CreateSphere = function (options) {
  37146. var segments = options.segments || 32;
  37147. var diameterX = options.diameterX || options.diameter || 1;
  37148. var diameterY = options.diameterY || options.diameter || 1;
  37149. var diameterZ = options.diameterZ || options.diameter || 1;
  37150. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37151. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37152. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37153. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37154. var totalZRotationSteps = 2 + segments;
  37155. var totalYRotationSteps = 2 * totalZRotationSteps;
  37156. var indices = [];
  37157. var positions = [];
  37158. var normals = [];
  37159. var uvs = [];
  37160. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37161. var normalizedZ = zRotationStep / totalZRotationSteps;
  37162. var angleZ = normalizedZ * Math.PI * slice;
  37163. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37164. var normalizedY = yRotationStep / totalYRotationSteps;
  37165. var angleY = normalizedY * Math.PI * 2 * arc;
  37166. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37167. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37168. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37169. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37170. var vertex = complete.multiply(radius);
  37171. var normal = complete.divide(radius).normalize();
  37172. positions.push(vertex.x, vertex.y, vertex.z);
  37173. normals.push(normal.x, normal.y, normal.z);
  37174. uvs.push(normalizedY, normalizedZ);
  37175. }
  37176. if (zRotationStep > 0) {
  37177. var verticesCount = positions.length / 3;
  37178. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37179. indices.push((firstIndex));
  37180. indices.push((firstIndex + 1));
  37181. indices.push(firstIndex + totalYRotationSteps + 1);
  37182. indices.push((firstIndex + totalYRotationSteps + 1));
  37183. indices.push((firstIndex + 1));
  37184. indices.push((firstIndex + totalYRotationSteps + 2));
  37185. }
  37186. }
  37187. }
  37188. // Sides
  37189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37190. // Result
  37191. var vertexData = new VertexData();
  37192. vertexData.indices = indices;
  37193. vertexData.positions = positions;
  37194. vertexData.normals = normals;
  37195. vertexData.uvs = uvs;
  37196. return vertexData;
  37197. };
  37198. /**
  37199. * Creates the VertexData for a cylinder, cone or prism
  37200. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37201. * * height sets the height (y direction) of the cylinder, optional, default 2
  37202. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37203. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37204. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37205. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37206. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37207. * * 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
  37208. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37209. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37210. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37211. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37212. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37213. * * 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)
  37214. * * 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)
  37215. * @returns the VertexData of the cylinder, cone or prism
  37216. */
  37217. VertexData.CreateCylinder = function (options) {
  37218. var height = options.height || 2;
  37219. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37220. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37221. var tessellation = options.tessellation || 24;
  37222. var subdivisions = options.subdivisions || 1;
  37223. var hasRings = options.hasRings ? true : false;
  37224. var enclose = options.enclose ? true : false;
  37225. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37226. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37227. var faceUV = options.faceUV || new Array(3);
  37228. var faceColors = options.faceColors;
  37229. // default face colors and UV if undefined
  37230. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37231. var ringNb = (hasRings) ? subdivisions : 1;
  37232. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37233. var f;
  37234. for (f = 0; f < surfaceNb; f++) {
  37235. if (faceColors && faceColors[f] === undefined) {
  37236. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37237. }
  37238. }
  37239. for (f = 0; f < surfaceNb; f++) {
  37240. if (faceUV && faceUV[f] === undefined) {
  37241. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37242. }
  37243. }
  37244. var indices = new Array();
  37245. var positions = new Array();
  37246. var normals = new Array();
  37247. var uvs = new Array();
  37248. var colors = new Array();
  37249. var angle_step = Math.PI * 2 * arc / tessellation;
  37250. var angle;
  37251. var h;
  37252. var radius;
  37253. var tan = (diameterBottom - diameterTop) / 2 / height;
  37254. var ringVertex = BABYLON.Vector3.Zero();
  37255. var ringNormal = BABYLON.Vector3.Zero();
  37256. var ringFirstVertex = BABYLON.Vector3.Zero();
  37257. var ringFirstNormal = BABYLON.Vector3.Zero();
  37258. var quadNormal = BABYLON.Vector3.Zero();
  37259. var Y = BABYLON.Axis.Y;
  37260. // positions, normals, uvs
  37261. var i;
  37262. var j;
  37263. var r;
  37264. var ringIdx = 1;
  37265. var s = 1; // surface index
  37266. var cs = 0;
  37267. var v = 0;
  37268. for (i = 0; i <= subdivisions; i++) {
  37269. h = i / subdivisions;
  37270. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37271. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37272. for (r = 0; r < ringIdx; r++) {
  37273. if (hasRings) {
  37274. s += r;
  37275. }
  37276. if (enclose) {
  37277. s += 2 * r;
  37278. }
  37279. for (j = 0; j <= tessellation; j++) {
  37280. angle = j * angle_step;
  37281. // position
  37282. ringVertex.x = Math.cos(-angle) * radius;
  37283. ringVertex.y = -height / 2 + h * height;
  37284. ringVertex.z = Math.sin(-angle) * radius;
  37285. // normal
  37286. if (diameterTop === 0 && i === subdivisions) {
  37287. // if no top cap, reuse former normals
  37288. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37289. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37290. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37291. }
  37292. else {
  37293. ringNormal.x = ringVertex.x;
  37294. ringNormal.z = ringVertex.z;
  37295. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37296. ringNormal.normalize();
  37297. }
  37298. // keep first ring vertex values for enclose
  37299. if (j === 0) {
  37300. ringFirstVertex.copyFrom(ringVertex);
  37301. ringFirstNormal.copyFrom(ringNormal);
  37302. }
  37303. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37304. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37305. if (hasRings) {
  37306. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37307. }
  37308. else {
  37309. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37310. }
  37311. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37312. if (faceColors) {
  37313. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37314. }
  37315. }
  37316. // if enclose, add four vertices and their dedicated normals
  37317. if (arc !== 1 && enclose) {
  37318. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37319. positions.push(0, ringVertex.y, 0);
  37320. positions.push(0, ringVertex.y, 0);
  37321. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37322. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37323. quadNormal.normalize();
  37324. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37325. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37326. quadNormal.normalize();
  37327. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37328. if (hasRings) {
  37329. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37330. }
  37331. else {
  37332. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37333. }
  37334. uvs.push(faceUV[s + 1].x, v);
  37335. uvs.push(faceUV[s + 1].z, v);
  37336. if (hasRings) {
  37337. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37338. }
  37339. else {
  37340. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37341. }
  37342. uvs.push(faceUV[s + 2].x, v);
  37343. uvs.push(faceUV[s + 2].z, v);
  37344. if (faceColors) {
  37345. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37346. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37347. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37348. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37349. }
  37350. }
  37351. if (cs !== s) {
  37352. cs = s;
  37353. }
  37354. }
  37355. }
  37356. // indices
  37357. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37358. var s;
  37359. i = 0;
  37360. for (s = 0; s < subdivisions; s++) {
  37361. var i0 = 0;
  37362. var i1 = 0;
  37363. var i2 = 0;
  37364. var i3 = 0;
  37365. for (j = 0; j < tessellation; j++) {
  37366. i0 = i * (e + 1) + j;
  37367. i1 = (i + 1) * (e + 1) + j;
  37368. i2 = i * (e + 1) + (j + 1);
  37369. i3 = (i + 1) * (e + 1) + (j + 1);
  37370. indices.push(i0, i1, i2);
  37371. indices.push(i3, i2, i1);
  37372. }
  37373. if (arc !== 1 && enclose) { // if enclose, add two quads
  37374. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37375. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37376. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37377. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37378. }
  37379. i = (hasRings) ? (i + 2) : (i + 1);
  37380. }
  37381. // Caps
  37382. var createCylinderCap = function (isTop) {
  37383. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37384. if (radius === 0) {
  37385. return;
  37386. }
  37387. // Cap positions, normals & uvs
  37388. var angle;
  37389. var circleVector;
  37390. var i;
  37391. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37392. var c = null;
  37393. if (faceColors) {
  37394. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37395. }
  37396. // cap center
  37397. var vbase = positions.length / 3;
  37398. var offset = isTop ? height / 2 : -height / 2;
  37399. var center = new BABYLON.Vector3(0, offset, 0);
  37400. positions.push(center.x, center.y, center.z);
  37401. normals.push(0, isTop ? 1 : -1, 0);
  37402. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37403. if (c) {
  37404. colors.push(c.r, c.g, c.b, c.a);
  37405. }
  37406. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37407. for (i = 0; i <= tessellation; i++) {
  37408. angle = Math.PI * 2 * i * arc / tessellation;
  37409. var cos = Math.cos(-angle);
  37410. var sin = Math.sin(-angle);
  37411. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37412. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37413. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37414. normals.push(0, isTop ? 1 : -1, 0);
  37415. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37416. if (c) {
  37417. colors.push(c.r, c.g, c.b, c.a);
  37418. }
  37419. }
  37420. // Cap indices
  37421. for (i = 0; i < tessellation; i++) {
  37422. if (!isTop) {
  37423. indices.push(vbase);
  37424. indices.push(vbase + (i + 1));
  37425. indices.push(vbase + (i + 2));
  37426. }
  37427. else {
  37428. indices.push(vbase);
  37429. indices.push(vbase + (i + 2));
  37430. indices.push(vbase + (i + 1));
  37431. }
  37432. }
  37433. };
  37434. // add caps to geometry
  37435. createCylinderCap(false);
  37436. createCylinderCap(true);
  37437. // Sides
  37438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37439. var vertexData = new VertexData();
  37440. vertexData.indices = indices;
  37441. vertexData.positions = positions;
  37442. vertexData.normals = normals;
  37443. vertexData.uvs = uvs;
  37444. if (faceColors) {
  37445. vertexData.colors = colors;
  37446. }
  37447. return vertexData;
  37448. };
  37449. /**
  37450. * Creates the VertexData for a torus
  37451. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37452. * * diameter the diameter of the torus, optional default 1
  37453. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37454. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37455. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37456. * * 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)
  37457. * * 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)
  37458. * @returns the VertexData of the torus
  37459. */
  37460. VertexData.CreateTorus = function (options) {
  37461. var indices = [];
  37462. var positions = [];
  37463. var normals = [];
  37464. var uvs = [];
  37465. var diameter = options.diameter || 1;
  37466. var thickness = options.thickness || 0.5;
  37467. var tessellation = options.tessellation || 16;
  37468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37469. var stride = tessellation + 1;
  37470. for (var i = 0; i <= tessellation; i++) {
  37471. var u = i / tessellation;
  37472. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37473. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37474. for (var j = 0; j <= tessellation; j++) {
  37475. var v = 1 - j / tessellation;
  37476. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37477. var dx = Math.cos(innerAngle);
  37478. var dy = Math.sin(innerAngle);
  37479. // Create a vertex.
  37480. var normal = new BABYLON.Vector3(dx, dy, 0);
  37481. var position = normal.scale(thickness / 2);
  37482. var textureCoordinate = new BABYLON.Vector2(u, v);
  37483. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37484. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37485. positions.push(position.x, position.y, position.z);
  37486. normals.push(normal.x, normal.y, normal.z);
  37487. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37488. // And create indices for two triangles.
  37489. var nextI = (i + 1) % stride;
  37490. var nextJ = (j + 1) % stride;
  37491. indices.push(i * stride + j);
  37492. indices.push(i * stride + nextJ);
  37493. indices.push(nextI * stride + j);
  37494. indices.push(i * stride + nextJ);
  37495. indices.push(nextI * stride + nextJ);
  37496. indices.push(nextI * stride + j);
  37497. }
  37498. }
  37499. // Sides
  37500. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37501. // Result
  37502. var vertexData = new VertexData();
  37503. vertexData.indices = indices;
  37504. vertexData.positions = positions;
  37505. vertexData.normals = normals;
  37506. vertexData.uvs = uvs;
  37507. return vertexData;
  37508. };
  37509. /**
  37510. * Creates the VertexData of the LineSystem
  37511. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37512. * - lines an array of lines, each line being an array of successive Vector3
  37513. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37514. * @returns the VertexData of the LineSystem
  37515. */
  37516. VertexData.CreateLineSystem = function (options) {
  37517. var indices = [];
  37518. var positions = [];
  37519. var lines = options.lines;
  37520. var colors = options.colors;
  37521. var vertexColors = [];
  37522. var idx = 0;
  37523. for (var l = 0; l < lines.length; l++) {
  37524. var points = lines[l];
  37525. for (var index = 0; index < points.length; index++) {
  37526. positions.push(points[index].x, points[index].y, points[index].z);
  37527. if (colors) {
  37528. var color = colors[l];
  37529. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37530. }
  37531. if (index > 0) {
  37532. indices.push(idx - 1);
  37533. indices.push(idx);
  37534. }
  37535. idx++;
  37536. }
  37537. }
  37538. var vertexData = new VertexData();
  37539. vertexData.indices = indices;
  37540. vertexData.positions = positions;
  37541. if (colors) {
  37542. vertexData.colors = vertexColors;
  37543. }
  37544. return vertexData;
  37545. };
  37546. /**
  37547. * Create the VertexData for a DashedLines
  37548. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37549. * - points an array successive Vector3
  37550. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37551. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37552. * - dashNb the intended total number of dashes, optional, default 200
  37553. * @returns the VertexData for the DashedLines
  37554. */
  37555. VertexData.CreateDashedLines = function (options) {
  37556. var dashSize = options.dashSize || 3;
  37557. var gapSize = options.gapSize || 1;
  37558. var dashNb = options.dashNb || 200;
  37559. var points = options.points;
  37560. var positions = new Array();
  37561. var indices = new Array();
  37562. var curvect = BABYLON.Vector3.Zero();
  37563. var lg = 0;
  37564. var nb = 0;
  37565. var shft = 0;
  37566. var dashshft = 0;
  37567. var curshft = 0;
  37568. var idx = 0;
  37569. var i = 0;
  37570. for (i = 0; i < points.length - 1; i++) {
  37571. points[i + 1].subtractToRef(points[i], curvect);
  37572. lg += curvect.length();
  37573. }
  37574. shft = lg / dashNb;
  37575. dashshft = dashSize * shft / (dashSize + gapSize);
  37576. for (i = 0; i < points.length - 1; i++) {
  37577. points[i + 1].subtractToRef(points[i], curvect);
  37578. nb = Math.floor(curvect.length() / shft);
  37579. curvect.normalize();
  37580. for (var j = 0; j < nb; j++) {
  37581. curshft = shft * j;
  37582. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37583. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37584. indices.push(idx, idx + 1);
  37585. idx += 2;
  37586. }
  37587. }
  37588. // Result
  37589. var vertexData = new VertexData();
  37590. vertexData.positions = positions;
  37591. vertexData.indices = indices;
  37592. return vertexData;
  37593. };
  37594. /**
  37595. * Creates the VertexData for a Ground
  37596. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37597. * - width the width (x direction) of the ground, optional, default 1
  37598. * - height the height (z direction) of the ground, optional, default 1
  37599. * - subdivisions the number of subdivisions per side, optional, default 1
  37600. * @returns the VertexData of the Ground
  37601. */
  37602. VertexData.CreateGround = function (options) {
  37603. var indices = [];
  37604. var positions = [];
  37605. var normals = [];
  37606. var uvs = [];
  37607. var row, col;
  37608. var width = options.width || 1;
  37609. var height = options.height || 1;
  37610. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37611. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37612. for (row = 0; row <= subdivisionsY; row++) {
  37613. for (col = 0; col <= subdivisionsX; col++) {
  37614. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37615. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37616. positions.push(position.x, position.y, position.z);
  37617. normals.push(normal.x, normal.y, normal.z);
  37618. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37619. }
  37620. }
  37621. for (row = 0; row < subdivisionsY; row++) {
  37622. for (col = 0; col < subdivisionsX; col++) {
  37623. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37624. indices.push(col + 1 + row * (subdivisionsX + 1));
  37625. indices.push(col + row * (subdivisionsX + 1));
  37626. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37627. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37628. indices.push(col + row * (subdivisionsX + 1));
  37629. }
  37630. }
  37631. // Result
  37632. var vertexData = new VertexData();
  37633. vertexData.indices = indices;
  37634. vertexData.positions = positions;
  37635. vertexData.normals = normals;
  37636. vertexData.uvs = uvs;
  37637. return vertexData;
  37638. };
  37639. /**
  37640. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37641. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37642. * * xmin the ground minimum X coordinate, optional, default -1
  37643. * * zmin the ground minimum Z coordinate, optional, default -1
  37644. * * xmax the ground maximum X coordinate, optional, default 1
  37645. * * zmax the ground maximum Z coordinate, optional, default 1
  37646. * * 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}
  37647. * * 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}
  37648. * @returns the VertexData of the TiledGround
  37649. */
  37650. VertexData.CreateTiledGround = function (options) {
  37651. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37652. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37653. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37654. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37655. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37656. var precision = options.precision || { w: 1, h: 1 };
  37657. var indices = new Array();
  37658. var positions = new Array();
  37659. var normals = new Array();
  37660. var uvs = new Array();
  37661. var row, col, tileRow, tileCol;
  37662. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37663. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37664. precision.w = (precision.w < 1) ? 1 : precision.w;
  37665. precision.h = (precision.h < 1) ? 1 : precision.h;
  37666. var tileSize = {
  37667. 'w': (xmax - xmin) / subdivisions.w,
  37668. 'h': (zmax - zmin) / subdivisions.h
  37669. };
  37670. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37671. // Indices
  37672. var base = positions.length / 3;
  37673. var rowLength = precision.w + 1;
  37674. for (row = 0; row < precision.h; row++) {
  37675. for (col = 0; col < precision.w; col++) {
  37676. var square = [
  37677. base + col + row * rowLength,
  37678. base + (col + 1) + row * rowLength,
  37679. base + (col + 1) + (row + 1) * rowLength,
  37680. base + col + (row + 1) * rowLength
  37681. ];
  37682. indices.push(square[1]);
  37683. indices.push(square[2]);
  37684. indices.push(square[3]);
  37685. indices.push(square[0]);
  37686. indices.push(square[1]);
  37687. indices.push(square[3]);
  37688. }
  37689. }
  37690. // Position, normals and uvs
  37691. var position = BABYLON.Vector3.Zero();
  37692. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37693. for (row = 0; row <= precision.h; row++) {
  37694. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37695. for (col = 0; col <= precision.w; col++) {
  37696. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37697. position.y = 0;
  37698. positions.push(position.x, position.y, position.z);
  37699. normals.push(normal.x, normal.y, normal.z);
  37700. uvs.push(col / precision.w, row / precision.h);
  37701. }
  37702. }
  37703. }
  37704. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37705. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37706. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37707. }
  37708. }
  37709. // Result
  37710. var vertexData = new VertexData();
  37711. vertexData.indices = indices;
  37712. vertexData.positions = positions;
  37713. vertexData.normals = normals;
  37714. vertexData.uvs = uvs;
  37715. return vertexData;
  37716. };
  37717. /**
  37718. * Creates the VertexData of the Ground designed from a heightmap
  37719. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37720. * * width the width (x direction) of the ground
  37721. * * height the height (z direction) of the ground
  37722. * * subdivisions the number of subdivisions per side
  37723. * * minHeight the minimum altitude on the ground, optional, default 0
  37724. * * maxHeight the maximum altitude on the ground, optional default 1
  37725. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37726. * * buffer the array holding the image color data
  37727. * * bufferWidth the width of image
  37728. * * bufferHeight the height of image
  37729. * @returns the VertexData of the Ground designed from a heightmap
  37730. */
  37731. VertexData.CreateGroundFromHeightMap = function (options) {
  37732. var indices = [];
  37733. var positions = [];
  37734. var normals = [];
  37735. var uvs = [];
  37736. var row, col;
  37737. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37738. // Vertices
  37739. for (row = 0; row <= options.subdivisions; row++) {
  37740. for (col = 0; col <= options.subdivisions; col++) {
  37741. 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));
  37742. // Compute height
  37743. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37744. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37745. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37746. var r = options.buffer[pos] / 255.0;
  37747. var g = options.buffer[pos + 1] / 255.0;
  37748. var b = options.buffer[pos + 2] / 255.0;
  37749. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37750. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37751. // Add vertex
  37752. positions.push(position.x, position.y, position.z);
  37753. normals.push(0, 0, 0);
  37754. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37755. }
  37756. }
  37757. // Indices
  37758. for (row = 0; row < options.subdivisions; row++) {
  37759. for (col = 0; col < options.subdivisions; col++) {
  37760. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37761. indices.push(col + 1 + row * (options.subdivisions + 1));
  37762. indices.push(col + row * (options.subdivisions + 1));
  37763. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37764. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37765. indices.push(col + row * (options.subdivisions + 1));
  37766. }
  37767. }
  37768. // Normals
  37769. VertexData.ComputeNormals(positions, indices, normals);
  37770. // Result
  37771. var vertexData = new VertexData();
  37772. vertexData.indices = indices;
  37773. vertexData.positions = positions;
  37774. vertexData.normals = normals;
  37775. vertexData.uvs = uvs;
  37776. return vertexData;
  37777. };
  37778. /**
  37779. * Creates the VertexData for a Plane
  37780. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37781. * * size sets the width and height of the plane to the value of size, optional default 1
  37782. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37783. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37784. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37785. * * 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)
  37786. * * 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)
  37787. * @returns the VertexData of the box
  37788. */
  37789. VertexData.CreatePlane = function (options) {
  37790. var indices = [];
  37791. var positions = [];
  37792. var normals = [];
  37793. var uvs = [];
  37794. var width = options.width || options.size || 1;
  37795. var height = options.height || options.size || 1;
  37796. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37797. // Vertices
  37798. var halfWidth = width / 2.0;
  37799. var halfHeight = height / 2.0;
  37800. positions.push(-halfWidth, -halfHeight, 0);
  37801. normals.push(0, 0, -1.0);
  37802. uvs.push(0.0, 0.0);
  37803. positions.push(halfWidth, -halfHeight, 0);
  37804. normals.push(0, 0, -1.0);
  37805. uvs.push(1.0, 0.0);
  37806. positions.push(halfWidth, halfHeight, 0);
  37807. normals.push(0, 0, -1.0);
  37808. uvs.push(1.0, 1.0);
  37809. positions.push(-halfWidth, halfHeight, 0);
  37810. normals.push(0, 0, -1.0);
  37811. uvs.push(0.0, 1.0);
  37812. // Indices
  37813. indices.push(0);
  37814. indices.push(1);
  37815. indices.push(2);
  37816. indices.push(0);
  37817. indices.push(2);
  37818. indices.push(3);
  37819. // Sides
  37820. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37821. // Result
  37822. var vertexData = new VertexData();
  37823. vertexData.indices = indices;
  37824. vertexData.positions = positions;
  37825. vertexData.normals = normals;
  37826. vertexData.uvs = uvs;
  37827. return vertexData;
  37828. };
  37829. /**
  37830. * Creates the VertexData of the Disc or regular Polygon
  37831. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37832. * * radius the radius of the disc, optional default 0.5
  37833. * * tessellation the number of polygon sides, optional, default 64
  37834. * * 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
  37835. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37836. * * 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)
  37837. * * 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)
  37838. * @returns the VertexData of the box
  37839. */
  37840. VertexData.CreateDisc = function (options) {
  37841. var positions = new Array();
  37842. var indices = new Array();
  37843. var normals = new Array();
  37844. var uvs = new Array();
  37845. var radius = options.radius || 0.5;
  37846. var tessellation = options.tessellation || 64;
  37847. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37849. // positions and uvs
  37850. positions.push(0, 0, 0); // disc center first
  37851. uvs.push(0.5, 0.5);
  37852. var theta = Math.PI * 2 * arc;
  37853. var step = theta / tessellation;
  37854. for (var a = 0; a < theta; a += step) {
  37855. var x = Math.cos(a);
  37856. var y = Math.sin(a);
  37857. var u = (x + 1) / 2;
  37858. var v = (1 - y) / 2;
  37859. positions.push(radius * x, radius * y, 0);
  37860. uvs.push(u, v);
  37861. }
  37862. if (arc === 1) {
  37863. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37864. uvs.push(uvs[2], uvs[3]);
  37865. }
  37866. //indices
  37867. var vertexNb = positions.length / 3;
  37868. for (var i = 1; i < vertexNb - 1; i++) {
  37869. indices.push(i + 1, 0, i);
  37870. }
  37871. // result
  37872. VertexData.ComputeNormals(positions, indices, normals);
  37873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37874. var vertexData = new VertexData();
  37875. vertexData.indices = indices;
  37876. vertexData.positions = positions;
  37877. vertexData.normals = normals;
  37878. vertexData.uvs = uvs;
  37879. return vertexData;
  37880. };
  37881. /**
  37882. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37883. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37884. * @param polygon a mesh built from polygonTriangulation.build()
  37885. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37886. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37887. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37888. * @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)
  37889. * @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)
  37890. * @returns the VertexData of the Polygon
  37891. */
  37892. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37893. var faceUV = fUV || new Array(3);
  37894. var faceColors = fColors;
  37895. var colors = [];
  37896. // default face colors and UV if undefined
  37897. for (var f = 0; f < 3; f++) {
  37898. if (faceUV[f] === undefined) {
  37899. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37900. }
  37901. if (faceColors && faceColors[f] === undefined) {
  37902. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37903. }
  37904. }
  37905. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37906. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37907. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37908. var indices = polygon.getIndices();
  37909. // set face colours and textures
  37910. var idx = 0;
  37911. var face = 0;
  37912. for (var index = 0; index < normals.length; index += 3) {
  37913. //Edge Face no. 1
  37914. if (Math.abs(normals[index + 1]) < 0.001) {
  37915. face = 1;
  37916. }
  37917. //Top Face no. 0
  37918. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37919. face = 0;
  37920. }
  37921. //Bottom Face no. 2
  37922. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37923. face = 2;
  37924. }
  37925. idx = index / 3;
  37926. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37927. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37928. if (faceColors) {
  37929. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37930. }
  37931. }
  37932. // sides
  37933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37934. // Result
  37935. var vertexData = new VertexData();
  37936. vertexData.indices = indices;
  37937. vertexData.positions = positions;
  37938. vertexData.normals = normals;
  37939. vertexData.uvs = uvs;
  37940. if (faceColors) {
  37941. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37942. vertexData.colors = totalColors;
  37943. }
  37944. return vertexData;
  37945. };
  37946. /**
  37947. * Creates the VertexData of the IcoSphere
  37948. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37949. * * radius the radius of the IcoSphere, optional default 1
  37950. * * radiusX allows stretching in the x direction, optional, default radius
  37951. * * radiusY allows stretching in the y direction, optional, default radius
  37952. * * radiusZ allows stretching in the z direction, optional, default radius
  37953. * * flat when true creates a flat shaded mesh, optional, default true
  37954. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37955. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37956. * * 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)
  37957. * * 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)
  37958. * @returns the VertexData of the IcoSphere
  37959. */
  37960. VertexData.CreateIcoSphere = function (options) {
  37961. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37962. var radius = options.radius || 1;
  37963. var flat = (options.flat === undefined) ? true : options.flat;
  37964. var subdivisions = options.subdivisions || 4;
  37965. var radiusX = options.radiusX || radius;
  37966. var radiusY = options.radiusY || radius;
  37967. var radiusZ = options.radiusZ || radius;
  37968. var t = (1 + Math.sqrt(5)) / 2;
  37969. // 12 vertex x,y,z
  37970. var ico_vertices = [
  37971. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37972. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37973. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37974. ];
  37975. // index of 3 vertex makes a face of icopshere
  37976. var ico_indices = [
  37977. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37978. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37979. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37980. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37981. ];
  37982. // vertex for uv have aliased position, not for UV
  37983. var vertices_unalias_id = [
  37984. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37985. // vertex alias
  37986. 0,
  37987. 2,
  37988. 3,
  37989. 3,
  37990. 3,
  37991. 4,
  37992. 7,
  37993. 8,
  37994. 9,
  37995. 9,
  37996. 10,
  37997. 11 // 23: B + 12
  37998. ];
  37999. // uv as integer step (not pixels !)
  38000. var ico_vertexuv = [
  38001. 5, 1, 3, 1, 6, 4, 0, 0,
  38002. 5, 3, 4, 2, 2, 2, 4, 0,
  38003. 2, 0, 1, 1, 6, 0, 6, 2,
  38004. // vertex alias (for same vertex on different faces)
  38005. 0, 4,
  38006. 3, 3,
  38007. 4, 4,
  38008. 3, 1,
  38009. 4, 2,
  38010. 4, 4,
  38011. 0, 2,
  38012. 1, 1,
  38013. 2, 2,
  38014. 3, 3,
  38015. 1, 3,
  38016. 2, 4 // 23: B + 12
  38017. ];
  38018. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38019. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38020. // First island of uv mapping
  38021. // v = 4h 3+ 2
  38022. // v = 3h 9+ 4
  38023. // v = 2h 9+ 5 B
  38024. // v = 1h 9 1 0
  38025. // v = 0h 3 8 7 A
  38026. // u = 0 1 2 3 4 5 6 *a
  38027. // Second island of uv mapping
  38028. // v = 4h 0+ B+ 4+
  38029. // v = 3h A+ 2+
  38030. // v = 2h 7+ 6 3+
  38031. // v = 1h 8+ 3+
  38032. // v = 0h
  38033. // u = 0 1 2 3 4 5 6 *a
  38034. // Face layout on texture UV mapping
  38035. // ============
  38036. // \ 4 /\ 16 / ======
  38037. // \ / \ / /\ 11 /
  38038. // \/ 7 \/ / \ /
  38039. // ======= / 10 \/
  38040. // /\ 17 /\ =======
  38041. // / \ / \ \ 15 /\
  38042. // / 8 \/ 12 \ \ / \
  38043. // ============ \/ 6 \
  38044. // \ 18 /\ ============
  38045. // \ / \ \ 5 /\ 0 /
  38046. // \/ 13 \ \ / \ /
  38047. // ======= \/ 1 \/
  38048. // =============
  38049. // /\ 19 /\ 2 /\
  38050. // / \ / \ / \
  38051. // / 14 \/ 9 \/ 3 \
  38052. // ===================
  38053. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38054. var ustep = 138 / 1024;
  38055. var vstep = 239 / 1024;
  38056. var uoffset = 60 / 1024;
  38057. var voffset = 26 / 1024;
  38058. // Second island should have margin, not to touch the first island
  38059. // avoid any borderline artefact in pixel rounding
  38060. var island_u_offset = -40 / 1024;
  38061. var island_v_offset = +20 / 1024;
  38062. // face is either island 0 or 1 :
  38063. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38064. var island = [
  38065. 0, 0, 0, 0, 1,
  38066. 0, 0, 1, 1, 0,
  38067. 0, 0, 1, 1, 0,
  38068. 0, 1, 1, 1, 0 // 15 - 19
  38069. ];
  38070. var indices = new Array();
  38071. var positions = new Array();
  38072. var normals = new Array();
  38073. var uvs = new Array();
  38074. var current_indice = 0;
  38075. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38076. var face_vertex_pos = new Array(3);
  38077. var face_vertex_uv = new Array(3);
  38078. var v012;
  38079. for (v012 = 0; v012 < 3; v012++) {
  38080. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38081. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38082. }
  38083. // create all with normals
  38084. for (var face = 0; face < 20; face++) {
  38085. // 3 vertex per face
  38086. for (v012 = 0; v012 < 3; v012++) {
  38087. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38088. var v_id = ico_indices[3 * face + v012];
  38089. // vertex have 3D position (x,y,z)
  38090. 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]);
  38091. // Normalize to get normal, then scale to radius
  38092. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38093. // uv Coordinates from vertex ID
  38094. 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);
  38095. }
  38096. // Subdivide the face (interpolate pos, norm, uv)
  38097. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38098. // - norm is linear interpolation of vertex corner normal
  38099. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38100. // - uv is linear interpolation
  38101. //
  38102. // Topology is as below for sub-divide by 2
  38103. // vertex shown as v0,v1,v2
  38104. // interp index is i1 to progress in range [v0,v1[
  38105. // interp index is i2 to progress in range [v0,v2[
  38106. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38107. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38108. //
  38109. //
  38110. // i2 v2
  38111. // ^ ^
  38112. // / / \
  38113. // / / \
  38114. // / / \
  38115. // / / (0,1) \
  38116. // / #---------\
  38117. // / / \ (0,0)'/ \
  38118. // / / \ / \
  38119. // / / \ / \
  38120. // / / (0,0) \ / (1,0) \
  38121. // / #---------#---------\
  38122. // v0 v1
  38123. //
  38124. // --------------------> i1
  38125. //
  38126. // interp of (i1,i2):
  38127. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38128. // along i1 : lerp(x0,x1, i1/(S-i2))
  38129. //
  38130. // centroid of triangle is needed to get help normal computation
  38131. // (c1,c2) are used for centroid location
  38132. var interp_vertex = function (i1, i2, c1, c2) {
  38133. // vertex is interpolated from
  38134. // - face_vertex_pos[0..2]
  38135. // - face_vertex_uv[0..2]
  38136. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38137. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38138. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38139. pos_interp.normalize();
  38140. var vertex_normal;
  38141. if (flat) {
  38142. // in flat mode, recalculate normal as face centroid normal
  38143. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38144. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38145. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38146. }
  38147. else {
  38148. // in smooth mode, recalculate normal from each single vertex position
  38149. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38150. }
  38151. // Vertex normal need correction due to X,Y,Z radius scaling
  38152. vertex_normal.x /= radiusX;
  38153. vertex_normal.y /= radiusY;
  38154. vertex_normal.z /= radiusZ;
  38155. vertex_normal.normalize();
  38156. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38157. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38158. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38159. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38160. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38161. uvs.push(uv_interp.x, uv_interp.y);
  38162. // push each vertex has member of a face
  38163. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38164. indices.push(current_indice);
  38165. current_indice++;
  38166. };
  38167. for (var i2 = 0; i2 < subdivisions; i2++) {
  38168. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38169. // face : (i1,i2) for /\ :
  38170. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38171. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38172. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38173. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38174. if (i1 + i2 + 1 < subdivisions) {
  38175. // face : (i1,i2)' for \/ :
  38176. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38177. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38178. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38179. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38180. }
  38181. }
  38182. }
  38183. }
  38184. // Sides
  38185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38186. // Result
  38187. var vertexData = new VertexData();
  38188. vertexData.indices = indices;
  38189. vertexData.positions = positions;
  38190. vertexData.normals = normals;
  38191. vertexData.uvs = uvs;
  38192. return vertexData;
  38193. };
  38194. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38195. /**
  38196. * Creates the VertexData for a Polyhedron
  38197. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38198. * * type provided types are:
  38199. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38200. * * 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)
  38201. * * size the size of the IcoSphere, optional default 1
  38202. * * sizeX allows stretching in the x direction, optional, default size
  38203. * * sizeY allows stretching in the y direction, optional, default size
  38204. * * sizeZ allows stretching in the z direction, optional, default size
  38205. * * 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
  38206. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38207. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38208. * * flat when true creates a flat shaded mesh, optional, default true
  38209. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38210. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38211. * * 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)
  38212. * * 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)
  38213. * @returns the VertexData of the Polyhedron
  38214. */
  38215. VertexData.CreatePolyhedron = function (options) {
  38216. // provided polyhedron types :
  38217. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38218. // 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)
  38219. var polyhedra = [];
  38220. 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]] };
  38221. 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]] };
  38222. polyhedra[2] = {
  38223. 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]],
  38224. 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]]
  38225. };
  38226. polyhedra[3] = {
  38227. 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]],
  38228. 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]]
  38229. };
  38230. polyhedra[4] = {
  38231. 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]],
  38232. 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]]
  38233. };
  38234. 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]] };
  38235. 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]] };
  38236. 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]] };
  38237. 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]] };
  38238. 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]] };
  38239. 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]] };
  38240. 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]] };
  38241. 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]] };
  38242. 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]] };
  38243. polyhedra[14] = {
  38244. 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]],
  38245. 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]]
  38246. };
  38247. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38248. var size = options.size;
  38249. var sizeX = options.sizeX || size || 1;
  38250. var sizeY = options.sizeY || size || 1;
  38251. var sizeZ = options.sizeZ || size || 1;
  38252. var data = options.custom || polyhedra[type];
  38253. var nbfaces = data.face.length;
  38254. var faceUV = options.faceUV || new Array(nbfaces);
  38255. var faceColors = options.faceColors;
  38256. var flat = (options.flat === undefined) ? true : options.flat;
  38257. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38258. var positions = new Array();
  38259. var indices = new Array();
  38260. var normals = new Array();
  38261. var uvs = new Array();
  38262. var colors = new Array();
  38263. var index = 0;
  38264. var faceIdx = 0; // face cursor in the array "indexes"
  38265. var indexes = new Array();
  38266. var i = 0;
  38267. var f = 0;
  38268. var u, v, ang, x, y, tmp;
  38269. // default face colors and UV if undefined
  38270. if (flat) {
  38271. for (f = 0; f < nbfaces; f++) {
  38272. if (faceColors && faceColors[f] === undefined) {
  38273. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38274. }
  38275. if (faceUV && faceUV[f] === undefined) {
  38276. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38277. }
  38278. }
  38279. }
  38280. if (!flat) {
  38281. for (i = 0; i < data.vertex.length; i++) {
  38282. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38283. uvs.push(0, 0);
  38284. }
  38285. for (f = 0; f < nbfaces; f++) {
  38286. for (i = 0; i < data.face[f].length - 2; i++) {
  38287. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38288. }
  38289. }
  38290. }
  38291. else {
  38292. for (f = 0; f < nbfaces; f++) {
  38293. var fl = data.face[f].length; // number of vertices of the current face
  38294. ang = 2 * Math.PI / fl;
  38295. x = 0.5 * Math.tan(ang / 2);
  38296. y = 0.5;
  38297. // positions, uvs, colors
  38298. for (i = 0; i < fl; i++) {
  38299. // positions
  38300. 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);
  38301. indexes.push(index);
  38302. index++;
  38303. // uvs
  38304. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38305. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38306. uvs.push(u, v);
  38307. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38308. y = x * Math.sin(ang) + y * Math.cos(ang);
  38309. x = tmp;
  38310. // colors
  38311. if (faceColors) {
  38312. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38313. }
  38314. }
  38315. // indices from indexes
  38316. for (i = 0; i < fl - 2; i++) {
  38317. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38318. }
  38319. faceIdx += fl;
  38320. }
  38321. }
  38322. VertexData.ComputeNormals(positions, indices, normals);
  38323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38324. var vertexData = new VertexData();
  38325. vertexData.positions = positions;
  38326. vertexData.indices = indices;
  38327. vertexData.normals = normals;
  38328. vertexData.uvs = uvs;
  38329. if (faceColors && flat) {
  38330. vertexData.colors = colors;
  38331. }
  38332. return vertexData;
  38333. };
  38334. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38335. /**
  38336. * Creates the VertexData for a TorusKnot
  38337. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38338. * * radius the radius of the torus knot, optional, default 2
  38339. * * tube the thickness of the tube, optional, default 0.5
  38340. * * radialSegments the number of sides on each tube segments, optional, default 32
  38341. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38342. * * p the number of windings around the z axis, optional, default 2
  38343. * * q the number of windings around the x axis, optional, default 3
  38344. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38345. * * 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)
  38346. * * 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)
  38347. * @returns the VertexData of the Torus Knot
  38348. */
  38349. VertexData.CreateTorusKnot = function (options) {
  38350. var indices = new Array();
  38351. var positions = new Array();
  38352. var normals = new Array();
  38353. var uvs = new Array();
  38354. var radius = options.radius || 2;
  38355. var tube = options.tube || 0.5;
  38356. var radialSegments = options.radialSegments || 32;
  38357. var tubularSegments = options.tubularSegments || 32;
  38358. var p = options.p || 2;
  38359. var q = options.q || 3;
  38360. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38361. // Helper
  38362. var getPos = function (angle) {
  38363. var cu = Math.cos(angle);
  38364. var su = Math.sin(angle);
  38365. var quOverP = q / p * angle;
  38366. var cs = Math.cos(quOverP);
  38367. var tx = radius * (2 + cs) * 0.5 * cu;
  38368. var ty = radius * (2 + cs) * su * 0.5;
  38369. var tz = radius * Math.sin(quOverP) * 0.5;
  38370. return new BABYLON.Vector3(tx, ty, tz);
  38371. };
  38372. // Vertices
  38373. var i;
  38374. var j;
  38375. for (i = 0; i <= radialSegments; i++) {
  38376. var modI = i % radialSegments;
  38377. var u = modI / radialSegments * 2 * p * Math.PI;
  38378. var p1 = getPos(u);
  38379. var p2 = getPos(u + 0.01);
  38380. var tang = p2.subtract(p1);
  38381. var n = p2.add(p1);
  38382. var bitan = BABYLON.Vector3.Cross(tang, n);
  38383. n = BABYLON.Vector3.Cross(bitan, tang);
  38384. bitan.normalize();
  38385. n.normalize();
  38386. for (j = 0; j < tubularSegments; j++) {
  38387. var modJ = j % tubularSegments;
  38388. var v = modJ / tubularSegments * 2 * Math.PI;
  38389. var cx = -tube * Math.cos(v);
  38390. var cy = tube * Math.sin(v);
  38391. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38392. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38393. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38394. uvs.push(i / radialSegments);
  38395. uvs.push(j / tubularSegments);
  38396. }
  38397. }
  38398. for (i = 0; i < radialSegments; i++) {
  38399. for (j = 0; j < tubularSegments; j++) {
  38400. var jNext = (j + 1) % tubularSegments;
  38401. var a = i * tubularSegments + j;
  38402. var b = (i + 1) * tubularSegments + j;
  38403. var c = (i + 1) * tubularSegments + jNext;
  38404. var d = i * tubularSegments + jNext;
  38405. indices.push(d);
  38406. indices.push(b);
  38407. indices.push(a);
  38408. indices.push(d);
  38409. indices.push(c);
  38410. indices.push(b);
  38411. }
  38412. }
  38413. // Normals
  38414. VertexData.ComputeNormals(positions, indices, normals);
  38415. // Sides
  38416. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38417. // Result
  38418. var vertexData = new VertexData();
  38419. vertexData.indices = indices;
  38420. vertexData.positions = positions;
  38421. vertexData.normals = normals;
  38422. vertexData.uvs = uvs;
  38423. return vertexData;
  38424. };
  38425. // Tools
  38426. /**
  38427. * Compute normals for given positions and indices
  38428. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38429. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38430. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38431. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38432. * * facetNormals : optional array of facet normals (vector3)
  38433. * * facetPositions : optional array of facet positions (vector3)
  38434. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38435. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38436. * * bInfo : optional bounding info, required for facetPartitioning computation
  38437. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38438. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38439. * * useRightHandedSystem: optional boolean to for right handed system computation
  38440. * * depthSort : optional boolean to enable the facet depth sort computation
  38441. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38442. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38443. */
  38444. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38445. // temporary scalar variables
  38446. var index = 0; // facet index
  38447. var p1p2x = 0.0; // p1p2 vector x coordinate
  38448. var p1p2y = 0.0; // p1p2 vector y coordinate
  38449. var p1p2z = 0.0; // p1p2 vector z coordinate
  38450. var p3p2x = 0.0; // p3p2 vector x coordinate
  38451. var p3p2y = 0.0; // p3p2 vector y coordinate
  38452. var p3p2z = 0.0; // p3p2 vector z coordinate
  38453. var faceNormalx = 0.0; // facet normal x coordinate
  38454. var faceNormaly = 0.0; // facet normal y coordinate
  38455. var faceNormalz = 0.0; // facet normal z coordinate
  38456. var length = 0.0; // facet normal length before normalization
  38457. var v1x = 0; // vector1 x index in the positions array
  38458. var v1y = 0; // vector1 y index in the positions array
  38459. var v1z = 0; // vector1 z index in the positions array
  38460. var v2x = 0; // vector2 x index in the positions array
  38461. var v2y = 0; // vector2 y index in the positions array
  38462. var v2z = 0; // vector2 z index in the positions array
  38463. var v3x = 0; // vector3 x index in the positions array
  38464. var v3y = 0; // vector3 y index in the positions array
  38465. var v3z = 0; // vector3 z index in the positions array
  38466. var computeFacetNormals = false;
  38467. var computeFacetPositions = false;
  38468. var computeFacetPartitioning = false;
  38469. var computeDepthSort = false;
  38470. var faceNormalSign = 1;
  38471. var ratio = 0;
  38472. var distanceTo = null;
  38473. if (options) {
  38474. computeFacetNormals = (options.facetNormals) ? true : false;
  38475. computeFacetPositions = (options.facetPositions) ? true : false;
  38476. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38477. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38478. ratio = options.ratio || 0;
  38479. computeDepthSort = (options.depthSort) ? true : false;
  38480. distanceTo = (options.distanceTo);
  38481. if (computeDepthSort) {
  38482. if (distanceTo === undefined) {
  38483. distanceTo = BABYLON.Vector3.Zero();
  38484. }
  38485. var depthSortedFacets = options.depthSortedFacets;
  38486. }
  38487. }
  38488. // facetPartitioning reinit if needed
  38489. var xSubRatio = 0;
  38490. var ySubRatio = 0;
  38491. var zSubRatio = 0;
  38492. var subSq = 0;
  38493. if (computeFacetPartitioning && options && options.bbSize) {
  38494. var ox = 0; // X partitioning index for facet position
  38495. var oy = 0; // Y partinioning index for facet position
  38496. var oz = 0; // Z partinioning index for facet position
  38497. var b1x = 0; // X partitioning index for facet v1 vertex
  38498. var b1y = 0; // Y partitioning index for facet v1 vertex
  38499. var b1z = 0; // z partitioning index for facet v1 vertex
  38500. var b2x = 0; // X partitioning index for facet v2 vertex
  38501. var b2y = 0; // Y partitioning index for facet v2 vertex
  38502. var b2z = 0; // Z partitioning index for facet v2 vertex
  38503. var b3x = 0; // X partitioning index for facet v3 vertex
  38504. var b3y = 0; // Y partitioning index for facet v3 vertex
  38505. var b3z = 0; // Z partitioning index for facet v3 vertex
  38506. var block_idx_o = 0; // facet barycenter block index
  38507. var block_idx_v1 = 0; // v1 vertex block index
  38508. var block_idx_v2 = 0; // v2 vertex block index
  38509. var block_idx_v3 = 0; // v3 vertex block index
  38510. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38511. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38512. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38513. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38514. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38515. subSq = options.subDiv.max * options.subDiv.max;
  38516. options.facetPartitioning.length = 0;
  38517. }
  38518. // reset the normals
  38519. for (index = 0; index < positions.length; index++) {
  38520. normals[index] = 0.0;
  38521. }
  38522. // Loop : 1 indice triplet = 1 facet
  38523. var nbFaces = (indices.length / 3) | 0;
  38524. for (index = 0; index < nbFaces; index++) {
  38525. // get the indexes of the coordinates of each vertex of the facet
  38526. v1x = indices[index * 3] * 3;
  38527. v1y = v1x + 1;
  38528. v1z = v1x + 2;
  38529. v2x = indices[index * 3 + 1] * 3;
  38530. v2y = v2x + 1;
  38531. v2z = v2x + 2;
  38532. v3x = indices[index * 3 + 2] * 3;
  38533. v3y = v3x + 1;
  38534. v3z = v3x + 2;
  38535. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38536. p1p2y = positions[v1y] - positions[v2y];
  38537. p1p2z = positions[v1z] - positions[v2z];
  38538. p3p2x = positions[v3x] - positions[v2x];
  38539. p3p2y = positions[v3y] - positions[v2y];
  38540. p3p2z = positions[v3z] - positions[v2z];
  38541. // compute the face normal with the cross product
  38542. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38543. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38544. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38545. // normalize this normal and store it in the array facetData
  38546. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38547. length = (length === 0) ? 1.0 : length;
  38548. faceNormalx /= length;
  38549. faceNormaly /= length;
  38550. faceNormalz /= length;
  38551. if (computeFacetNormals && options) {
  38552. options.facetNormals[index].x = faceNormalx;
  38553. options.facetNormals[index].y = faceNormaly;
  38554. options.facetNormals[index].z = faceNormalz;
  38555. }
  38556. if (computeFacetPositions && options) {
  38557. // compute and the facet barycenter coordinates in the array facetPositions
  38558. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38559. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38560. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38561. }
  38562. if (computeFacetPartitioning && options) {
  38563. // store the facet indexes in arrays in the main facetPartitioning array :
  38564. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38565. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38566. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38567. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38568. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38569. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38570. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38571. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38572. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38573. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38574. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38575. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38576. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38577. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38578. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38579. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38580. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38581. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38582. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38583. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38584. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38585. // push each facet index in each block containing the vertex
  38586. options.facetPartitioning[block_idx_v1].push(index);
  38587. if (block_idx_v2 != block_idx_v1) {
  38588. options.facetPartitioning[block_idx_v2].push(index);
  38589. }
  38590. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38591. options.facetPartitioning[block_idx_v3].push(index);
  38592. }
  38593. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38594. options.facetPartitioning[block_idx_o].push(index);
  38595. }
  38596. }
  38597. if (computeDepthSort && options && options.facetPositions) {
  38598. var dsf = depthSortedFacets[index];
  38599. dsf.ind = index * 3;
  38600. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38601. }
  38602. // compute the normals anyway
  38603. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38604. normals[v1y] += faceNormaly;
  38605. normals[v1z] += faceNormalz;
  38606. normals[v2x] += faceNormalx;
  38607. normals[v2y] += faceNormaly;
  38608. normals[v2z] += faceNormalz;
  38609. normals[v3x] += faceNormalx;
  38610. normals[v3y] += faceNormaly;
  38611. normals[v3z] += faceNormalz;
  38612. }
  38613. // last normalization of each normal
  38614. for (index = 0; index < normals.length / 3; index++) {
  38615. faceNormalx = normals[index * 3];
  38616. faceNormaly = normals[index * 3 + 1];
  38617. faceNormalz = normals[index * 3 + 2];
  38618. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38619. length = (length === 0) ? 1.0 : length;
  38620. faceNormalx /= length;
  38621. faceNormaly /= length;
  38622. faceNormalz /= length;
  38623. normals[index * 3] = faceNormalx;
  38624. normals[index * 3 + 1] = faceNormaly;
  38625. normals[index * 3 + 2] = faceNormalz;
  38626. }
  38627. };
  38628. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38629. var li = indices.length;
  38630. var ln = normals.length;
  38631. var i;
  38632. var n;
  38633. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38634. switch (sideOrientation) {
  38635. case BABYLON.Mesh.FRONTSIDE:
  38636. // nothing changed
  38637. break;
  38638. case BABYLON.Mesh.BACKSIDE:
  38639. var tmp;
  38640. // indices
  38641. for (i = 0; i < li; i += 3) {
  38642. tmp = indices[i];
  38643. indices[i] = indices[i + 2];
  38644. indices[i + 2] = tmp;
  38645. }
  38646. // normals
  38647. for (n = 0; n < ln; n++) {
  38648. normals[n] = -normals[n];
  38649. }
  38650. break;
  38651. case BABYLON.Mesh.DOUBLESIDE:
  38652. // positions
  38653. var lp = positions.length;
  38654. var l = lp / 3;
  38655. for (var p = 0; p < lp; p++) {
  38656. positions[lp + p] = positions[p];
  38657. }
  38658. // indices
  38659. for (i = 0; i < li; i += 3) {
  38660. indices[i + li] = indices[i + 2] + l;
  38661. indices[i + 1 + li] = indices[i + 1] + l;
  38662. indices[i + 2 + li] = indices[i] + l;
  38663. }
  38664. // normals
  38665. for (n = 0; n < ln; n++) {
  38666. normals[ln + n] = -normals[n];
  38667. }
  38668. // uvs
  38669. var lu = uvs.length;
  38670. var u = 0;
  38671. for (u = 0; u < lu; u++) {
  38672. uvs[u + lu] = uvs[u];
  38673. }
  38674. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38675. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38676. u = 0;
  38677. for (i = 0; i < lu / 2; i++) {
  38678. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38679. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38680. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38681. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38682. u += 2;
  38683. }
  38684. break;
  38685. }
  38686. };
  38687. /**
  38688. * Applies VertexData created from the imported parameters to the geometry
  38689. * @param parsedVertexData the parsed data from an imported file
  38690. * @param geometry the geometry to apply the VertexData to
  38691. */
  38692. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38693. var vertexData = new VertexData();
  38694. // positions
  38695. var positions = parsedVertexData.positions;
  38696. if (positions) {
  38697. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38698. }
  38699. // normals
  38700. var normals = parsedVertexData.normals;
  38701. if (normals) {
  38702. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38703. }
  38704. // tangents
  38705. var tangents = parsedVertexData.tangents;
  38706. if (tangents) {
  38707. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38708. }
  38709. // uvs
  38710. var uvs = parsedVertexData.uvs;
  38711. if (uvs) {
  38712. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38713. }
  38714. // uv2s
  38715. var uv2s = parsedVertexData.uv2s;
  38716. if (uv2s) {
  38717. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38718. }
  38719. // uv3s
  38720. var uv3s = parsedVertexData.uv3s;
  38721. if (uv3s) {
  38722. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38723. }
  38724. // uv4s
  38725. var uv4s = parsedVertexData.uv4s;
  38726. if (uv4s) {
  38727. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38728. }
  38729. // uv5s
  38730. var uv5s = parsedVertexData.uv5s;
  38731. if (uv5s) {
  38732. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38733. }
  38734. // uv6s
  38735. var uv6s = parsedVertexData.uv6s;
  38736. if (uv6s) {
  38737. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38738. }
  38739. // colors
  38740. var colors = parsedVertexData.colors;
  38741. if (colors) {
  38742. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38743. }
  38744. // matricesIndices
  38745. var matricesIndices = parsedVertexData.matricesIndices;
  38746. if (matricesIndices) {
  38747. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38748. }
  38749. // matricesWeights
  38750. var matricesWeights = parsedVertexData.matricesWeights;
  38751. if (matricesWeights) {
  38752. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38753. }
  38754. // indices
  38755. var indices = parsedVertexData.indices;
  38756. if (indices) {
  38757. vertexData.indices = indices;
  38758. }
  38759. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38760. };
  38761. return VertexData;
  38762. }());
  38763. BABYLON.VertexData = VertexData;
  38764. })(BABYLON || (BABYLON = {}));
  38765. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38766. var BABYLON;
  38767. (function (BABYLON) {
  38768. /**
  38769. * Class used to store geometry data (vertex buffers + index buffer)
  38770. */
  38771. var Geometry = /** @class */ (function () {
  38772. /**
  38773. * Creates a new geometry
  38774. * @param id defines the unique ID
  38775. * @param scene defines the hosting scene
  38776. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38777. * @param updatable defines if geometry must be updatable (false by default)
  38778. * @param mesh defines the mesh that will be associated with the geometry
  38779. */
  38780. function Geometry(id, scene, vertexData, updatable, mesh) {
  38781. if (updatable === void 0) { updatable = false; }
  38782. if (mesh === void 0) { mesh = null; }
  38783. /**
  38784. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38785. */
  38786. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38787. this._totalVertices = 0;
  38788. this._isDisposed = false;
  38789. this._indexBufferIsUpdatable = false;
  38790. this.id = id;
  38791. this._engine = scene.getEngine();
  38792. this._meshes = [];
  38793. this._scene = scene;
  38794. //Init vertex buffer cache
  38795. this._vertexBuffers = {};
  38796. this._indices = [];
  38797. this._updatable = updatable;
  38798. // vertexData
  38799. if (vertexData) {
  38800. this.setAllVerticesData(vertexData, updatable);
  38801. }
  38802. else {
  38803. this._totalVertices = 0;
  38804. this._indices = [];
  38805. }
  38806. if (this._engine.getCaps().vertexArrayObject) {
  38807. this._vertexArrayObjects = {};
  38808. }
  38809. // applyToMesh
  38810. if (mesh) {
  38811. if (mesh.getClassName() === "LinesMesh") {
  38812. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38813. this._updateExtend();
  38814. }
  38815. this.applyToMesh(mesh);
  38816. mesh.computeWorldMatrix(true);
  38817. }
  38818. }
  38819. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38820. /**
  38821. * 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
  38822. */
  38823. get: function () {
  38824. return this._boundingBias;
  38825. },
  38826. /**
  38827. * 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
  38828. */
  38829. set: function (value) {
  38830. if (this._boundingBias && this._boundingBias.equals(value)) {
  38831. return;
  38832. }
  38833. this._boundingBias = value.clone();
  38834. this._updateBoundingInfo(true, null);
  38835. },
  38836. enumerable: true,
  38837. configurable: true
  38838. });
  38839. /**
  38840. * Static function used to attach a new empty geometry to a mesh
  38841. * @param mesh defines the mesh to attach the geometry to
  38842. * @returns the new {BABYLON.Geometry}
  38843. */
  38844. Geometry.CreateGeometryForMesh = function (mesh) {
  38845. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38846. geometry.applyToMesh(mesh);
  38847. return geometry;
  38848. };
  38849. Object.defineProperty(Geometry.prototype, "extend", {
  38850. /**
  38851. * Gets the current extend of the geometry
  38852. */
  38853. get: function () {
  38854. return this._extend;
  38855. },
  38856. enumerable: true,
  38857. configurable: true
  38858. });
  38859. /**
  38860. * Gets the hosting scene
  38861. * @returns the hosting {BABYLON.Scene}
  38862. */
  38863. Geometry.prototype.getScene = function () {
  38864. return this._scene;
  38865. };
  38866. /**
  38867. * Gets the hosting engine
  38868. * @returns the hosting {BABYLON.Engine}
  38869. */
  38870. Geometry.prototype.getEngine = function () {
  38871. return this._engine;
  38872. };
  38873. /**
  38874. * Defines if the geometry is ready to use
  38875. * @returns true if the geometry is ready to be used
  38876. */
  38877. Geometry.prototype.isReady = function () {
  38878. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38879. };
  38880. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38881. /**
  38882. * Gets a value indicating that the geometry should not be serialized
  38883. */
  38884. get: function () {
  38885. for (var index = 0; index < this._meshes.length; index++) {
  38886. if (!this._meshes[index].doNotSerialize) {
  38887. return false;
  38888. }
  38889. }
  38890. return true;
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. /** @hidden */
  38896. Geometry.prototype._rebuild = function () {
  38897. if (this._vertexArrayObjects) {
  38898. this._vertexArrayObjects = {};
  38899. }
  38900. // Index buffer
  38901. if (this._meshes.length !== 0 && this._indices) {
  38902. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38903. }
  38904. // Vertex buffers
  38905. for (var key in this._vertexBuffers) {
  38906. var vertexBuffer = this._vertexBuffers[key];
  38907. vertexBuffer._rebuild();
  38908. }
  38909. };
  38910. /**
  38911. * Affects all gemetry data in one call
  38912. * @param vertexData defines the geometry data
  38913. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38914. */
  38915. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38916. vertexData.applyToGeometry(this, updatable);
  38917. this.notifyUpdate();
  38918. };
  38919. /**
  38920. * Set specific vertex data
  38921. * @param kind defines the data kind (Position, normal, etc...)
  38922. * @param data defines the vertex data to use
  38923. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38924. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38925. */
  38926. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38927. if (updatable === void 0) { updatable = false; }
  38928. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38929. this.setVerticesBuffer(buffer);
  38930. };
  38931. /**
  38932. * Removes a specific vertex data
  38933. * @param kind defines the data kind (Position, normal, etc...)
  38934. */
  38935. Geometry.prototype.removeVerticesData = function (kind) {
  38936. if (this._vertexBuffers[kind]) {
  38937. this._vertexBuffers[kind].dispose();
  38938. delete this._vertexBuffers[kind];
  38939. }
  38940. };
  38941. /**
  38942. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38943. * @param buffer defines the vertex buffer to use
  38944. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38945. */
  38946. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38947. if (totalVertices === void 0) { totalVertices = null; }
  38948. var kind = buffer.getKind();
  38949. if (this._vertexBuffers[kind]) {
  38950. this._vertexBuffers[kind].dispose();
  38951. }
  38952. this._vertexBuffers[kind] = buffer;
  38953. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38954. var data = buffer.getData();
  38955. if (totalVertices != null) {
  38956. this._totalVertices = totalVertices;
  38957. }
  38958. else {
  38959. if (data != null) {
  38960. this._totalVertices = data.length / (buffer.byteStride / 4);
  38961. }
  38962. }
  38963. this._updateExtend(data);
  38964. this._resetPointsArrayCache();
  38965. var meshes = this._meshes;
  38966. var numOfMeshes = meshes.length;
  38967. for (var index = 0; index < numOfMeshes; index++) {
  38968. var mesh = meshes[index];
  38969. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38970. mesh._createGlobalSubMesh(false);
  38971. mesh.computeWorldMatrix(true);
  38972. }
  38973. }
  38974. this.notifyUpdate(kind);
  38975. if (this._vertexArrayObjects) {
  38976. this._disposeVertexArrayObjects();
  38977. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38978. }
  38979. };
  38980. /**
  38981. * Update a specific vertex buffer
  38982. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38983. * It will do nothing if the buffer is not updatable
  38984. * @param kind defines the data kind (Position, normal, etc...)
  38985. * @param data defines the data to use
  38986. * @param offset defines the offset in the target buffer where to store the data
  38987. * @param useBytes set to true if the offset is in bytes
  38988. */
  38989. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38990. if (useBytes === void 0) { useBytes = false; }
  38991. var vertexBuffer = this.getVertexBuffer(kind);
  38992. if (!vertexBuffer) {
  38993. return;
  38994. }
  38995. vertexBuffer.updateDirectly(data, offset, useBytes);
  38996. this.notifyUpdate(kind);
  38997. };
  38998. /**
  38999. * Update a specific vertex buffer
  39000. * This function will create a new buffer if the current one is not updatable
  39001. * @param kind defines the data kind (Position, normal, etc...)
  39002. * @param data defines the data to use
  39003. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39004. */
  39005. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39006. if (updateExtends === void 0) { updateExtends = false; }
  39007. var vertexBuffer = this.getVertexBuffer(kind);
  39008. if (!vertexBuffer) {
  39009. return;
  39010. }
  39011. vertexBuffer.update(data);
  39012. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39013. this._updateBoundingInfo(updateExtends, data);
  39014. }
  39015. this.notifyUpdate(kind);
  39016. };
  39017. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39018. if (updateExtends) {
  39019. this._updateExtend(data);
  39020. }
  39021. var meshes = this._meshes;
  39022. var numOfMeshes = meshes.length;
  39023. this._resetPointsArrayCache();
  39024. for (var index = 0; index < numOfMeshes; index++) {
  39025. var mesh = meshes[index];
  39026. if (updateExtends) {
  39027. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39028. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39029. var subMesh = mesh.subMeshes[subIndex];
  39030. subMesh.refreshBoundingInfo();
  39031. }
  39032. }
  39033. }
  39034. };
  39035. /** @hidden */
  39036. Geometry.prototype._bind = function (effect, indexToBind) {
  39037. if (!effect) {
  39038. return;
  39039. }
  39040. if (indexToBind === undefined) {
  39041. indexToBind = this._indexBuffer;
  39042. }
  39043. var vbs = this.getVertexBuffers();
  39044. if (!vbs) {
  39045. return;
  39046. }
  39047. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39048. this._engine.bindBuffers(vbs, indexToBind, effect);
  39049. return;
  39050. }
  39051. // Using VAO
  39052. if (!this._vertexArrayObjects[effect.key]) {
  39053. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39054. }
  39055. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39056. };
  39057. /**
  39058. * Gets total number of vertices
  39059. * @returns the total number of vertices
  39060. */
  39061. Geometry.prototype.getTotalVertices = function () {
  39062. if (!this.isReady()) {
  39063. return 0;
  39064. }
  39065. return this._totalVertices;
  39066. };
  39067. /**
  39068. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39069. * @param kind defines the data kind (Position, normal, etc...)
  39070. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39071. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39072. * @returns a float array containing vertex data
  39073. */
  39074. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39075. var vertexBuffer = this.getVertexBuffer(kind);
  39076. if (!vertexBuffer) {
  39077. return null;
  39078. }
  39079. var data = vertexBuffer.getData();
  39080. if (!data) {
  39081. return null;
  39082. }
  39083. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39084. var count = this._totalVertices * vertexBuffer.getSize();
  39085. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39086. var copy_1 = new Array(count);
  39087. vertexBuffer.forEach(count, function (value, index) {
  39088. copy_1[index] = value;
  39089. });
  39090. return copy_1;
  39091. }
  39092. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39093. if (data instanceof Array) {
  39094. var offset = vertexBuffer.byteOffset / 4;
  39095. return BABYLON.Tools.Slice(data, offset, offset + count);
  39096. }
  39097. else if (data instanceof ArrayBuffer) {
  39098. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39099. }
  39100. else {
  39101. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39102. }
  39103. }
  39104. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39105. return BABYLON.Tools.Slice(data);
  39106. }
  39107. return data;
  39108. };
  39109. /**
  39110. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39111. * @param kind defines the data kind (Position, normal, etc...)
  39112. * @returns true if the vertex buffer with the specified kind is updatable
  39113. */
  39114. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39115. var vb = this._vertexBuffers[kind];
  39116. if (!vb) {
  39117. return false;
  39118. }
  39119. return vb.isUpdatable();
  39120. };
  39121. /**
  39122. * Gets a specific vertex buffer
  39123. * @param kind defines the data kind (Position, normal, etc...)
  39124. * @returns a {BABYLON.VertexBuffer}
  39125. */
  39126. Geometry.prototype.getVertexBuffer = function (kind) {
  39127. if (!this.isReady()) {
  39128. return null;
  39129. }
  39130. return this._vertexBuffers[kind];
  39131. };
  39132. /**
  39133. * Returns all vertex buffers
  39134. * @return an object holding all vertex buffers indexed by kind
  39135. */
  39136. Geometry.prototype.getVertexBuffers = function () {
  39137. if (!this.isReady()) {
  39138. return null;
  39139. }
  39140. return this._vertexBuffers;
  39141. };
  39142. /**
  39143. * Gets a boolean indicating if specific vertex buffer is present
  39144. * @param kind defines the data kind (Position, normal, etc...)
  39145. * @returns true if data is present
  39146. */
  39147. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39148. if (!this._vertexBuffers) {
  39149. if (this._delayInfo) {
  39150. return this._delayInfo.indexOf(kind) !== -1;
  39151. }
  39152. return false;
  39153. }
  39154. return this._vertexBuffers[kind] !== undefined;
  39155. };
  39156. /**
  39157. * Gets a list of all attached data kinds (Position, normal, etc...)
  39158. * @returns a list of string containing all kinds
  39159. */
  39160. Geometry.prototype.getVerticesDataKinds = function () {
  39161. var result = [];
  39162. var kind;
  39163. if (!this._vertexBuffers && this._delayInfo) {
  39164. for (kind in this._delayInfo) {
  39165. result.push(kind);
  39166. }
  39167. }
  39168. else {
  39169. for (kind in this._vertexBuffers) {
  39170. result.push(kind);
  39171. }
  39172. }
  39173. return result;
  39174. };
  39175. /**
  39176. * Update index buffer
  39177. * @param indices defines the indices to store in the index buffer
  39178. * @param offset defines the offset in the target buffer where to store the data
  39179. */
  39180. Geometry.prototype.updateIndices = function (indices, offset) {
  39181. if (!this._indexBuffer) {
  39182. return;
  39183. }
  39184. if (!this._indexBufferIsUpdatable) {
  39185. this.setIndices(indices, null, true);
  39186. }
  39187. else {
  39188. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39189. }
  39190. };
  39191. /**
  39192. * Creates a new index buffer
  39193. * @param indices defines the indices to store in the index buffer
  39194. * @param totalVertices defines the total number of vertices (could be null)
  39195. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39196. */
  39197. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39198. if (totalVertices === void 0) { totalVertices = null; }
  39199. if (updatable === void 0) { updatable = false; }
  39200. if (this._indexBuffer) {
  39201. this._engine._releaseBuffer(this._indexBuffer);
  39202. }
  39203. this._disposeVertexArrayObjects();
  39204. this._indices = indices;
  39205. this._indexBufferIsUpdatable = updatable;
  39206. if (this._meshes.length !== 0 && this._indices) {
  39207. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39208. }
  39209. if (totalVertices != undefined) { // including null and undefined
  39210. this._totalVertices = totalVertices;
  39211. }
  39212. var meshes = this._meshes;
  39213. var numOfMeshes = meshes.length;
  39214. for (var index = 0; index < numOfMeshes; index++) {
  39215. meshes[index]._createGlobalSubMesh(true);
  39216. }
  39217. this.notifyUpdate();
  39218. };
  39219. /**
  39220. * Return the total number of indices
  39221. * @returns the total number of indices
  39222. */
  39223. Geometry.prototype.getTotalIndices = function () {
  39224. if (!this.isReady()) {
  39225. return 0;
  39226. }
  39227. return this._indices.length;
  39228. };
  39229. /**
  39230. * Gets the index buffer array
  39231. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39232. * @returns the index buffer array
  39233. */
  39234. Geometry.prototype.getIndices = function (copyWhenShared) {
  39235. if (!this.isReady()) {
  39236. return null;
  39237. }
  39238. var orig = this._indices;
  39239. if (!copyWhenShared || this._meshes.length === 1) {
  39240. return orig;
  39241. }
  39242. else {
  39243. var len = orig.length;
  39244. var copy = [];
  39245. for (var i = 0; i < len; i++) {
  39246. copy.push(orig[i]);
  39247. }
  39248. return copy;
  39249. }
  39250. };
  39251. /**
  39252. * Gets the index buffer
  39253. * @return the index buffer
  39254. */
  39255. Geometry.prototype.getIndexBuffer = function () {
  39256. if (!this.isReady()) {
  39257. return null;
  39258. }
  39259. return this._indexBuffer;
  39260. };
  39261. /** @hidden */
  39262. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39263. if (effect === void 0) { effect = null; }
  39264. if (!effect || !this._vertexArrayObjects) {
  39265. return;
  39266. }
  39267. if (this._vertexArrayObjects[effect.key]) {
  39268. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39269. delete this._vertexArrayObjects[effect.key];
  39270. }
  39271. };
  39272. /**
  39273. * Release the associated resources for a specific mesh
  39274. * @param mesh defines the source mesh
  39275. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39276. */
  39277. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39278. var meshes = this._meshes;
  39279. var index = meshes.indexOf(mesh);
  39280. if (index === -1) {
  39281. return;
  39282. }
  39283. meshes.splice(index, 1);
  39284. mesh._geometry = null;
  39285. if (meshes.length === 0 && shouldDispose) {
  39286. this.dispose();
  39287. }
  39288. };
  39289. /**
  39290. * Apply current geometry to a given mesh
  39291. * @param mesh defines the mesh to apply geometry to
  39292. */
  39293. Geometry.prototype.applyToMesh = function (mesh) {
  39294. if (mesh._geometry === this) {
  39295. return;
  39296. }
  39297. var previousGeometry = mesh._geometry;
  39298. if (previousGeometry) {
  39299. previousGeometry.releaseForMesh(mesh);
  39300. }
  39301. var meshes = this._meshes;
  39302. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39303. mesh._geometry = this;
  39304. this._scene.pushGeometry(this);
  39305. meshes.push(mesh);
  39306. if (this.isReady()) {
  39307. this._applyToMesh(mesh);
  39308. }
  39309. else {
  39310. mesh._boundingInfo = this._boundingInfo;
  39311. }
  39312. };
  39313. Geometry.prototype._updateExtend = function (data) {
  39314. if (data === void 0) { data = null; }
  39315. if (!data) {
  39316. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39317. }
  39318. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39319. };
  39320. Geometry.prototype._applyToMesh = function (mesh) {
  39321. var numOfMeshes = this._meshes.length;
  39322. // vertexBuffers
  39323. for (var kind in this._vertexBuffers) {
  39324. if (numOfMeshes === 1) {
  39325. this._vertexBuffers[kind].create();
  39326. }
  39327. var buffer = this._vertexBuffers[kind].getBuffer();
  39328. if (buffer)
  39329. buffer.references = numOfMeshes;
  39330. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39331. if (!this._extend) {
  39332. this._updateExtend();
  39333. }
  39334. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39335. mesh._createGlobalSubMesh(false);
  39336. //bounding info was just created again, world matrix should be applied again.
  39337. mesh._updateBoundingInfo();
  39338. }
  39339. }
  39340. // indexBuffer
  39341. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39342. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39343. }
  39344. if (this._indexBuffer) {
  39345. this._indexBuffer.references = numOfMeshes;
  39346. }
  39347. };
  39348. Geometry.prototype.notifyUpdate = function (kind) {
  39349. if (this.onGeometryUpdated) {
  39350. this.onGeometryUpdated(this, kind);
  39351. }
  39352. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39353. var mesh = _a[_i];
  39354. mesh._markSubMeshesAsAttributesDirty();
  39355. }
  39356. };
  39357. /**
  39358. * Load the geometry if it was flagged as delay loaded
  39359. * @param scene defines the hosting scene
  39360. * @param onLoaded defines a callback called when the geometry is loaded
  39361. */
  39362. Geometry.prototype.load = function (scene, onLoaded) {
  39363. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39364. return;
  39365. }
  39366. if (this.isReady()) {
  39367. if (onLoaded) {
  39368. onLoaded();
  39369. }
  39370. return;
  39371. }
  39372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39373. this._queueLoad(scene, onLoaded);
  39374. };
  39375. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39376. var _this = this;
  39377. if (!this.delayLoadingFile) {
  39378. return;
  39379. }
  39380. scene._addPendingData(this);
  39381. scene._loadFile(this.delayLoadingFile, function (data) {
  39382. if (!_this._delayLoadingFunction) {
  39383. return;
  39384. }
  39385. _this._delayLoadingFunction(JSON.parse(data), _this);
  39386. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39387. _this._delayInfo = [];
  39388. scene._removePendingData(_this);
  39389. var meshes = _this._meshes;
  39390. var numOfMeshes = meshes.length;
  39391. for (var index = 0; index < numOfMeshes; index++) {
  39392. _this._applyToMesh(meshes[index]);
  39393. }
  39394. if (onLoaded) {
  39395. onLoaded();
  39396. }
  39397. }, undefined, true);
  39398. };
  39399. /**
  39400. * Invert the geometry to move from a right handed system to a left handed one.
  39401. */
  39402. Geometry.prototype.toLeftHanded = function () {
  39403. // Flip faces
  39404. var tIndices = this.getIndices(false);
  39405. if (tIndices != null && tIndices.length > 0) {
  39406. for (var i = 0; i < tIndices.length; i += 3) {
  39407. var tTemp = tIndices[i + 0];
  39408. tIndices[i + 0] = tIndices[i + 2];
  39409. tIndices[i + 2] = tTemp;
  39410. }
  39411. this.setIndices(tIndices);
  39412. }
  39413. // Negate position.z
  39414. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39415. if (tPositions != null && tPositions.length > 0) {
  39416. for (var i = 0; i < tPositions.length; i += 3) {
  39417. tPositions[i + 2] = -tPositions[i + 2];
  39418. }
  39419. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39420. }
  39421. // Negate normal.z
  39422. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39423. if (tNormals != null && tNormals.length > 0) {
  39424. for (var i = 0; i < tNormals.length; i += 3) {
  39425. tNormals[i + 2] = -tNormals[i + 2];
  39426. }
  39427. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39428. }
  39429. };
  39430. // Cache
  39431. /** @hidden */
  39432. Geometry.prototype._resetPointsArrayCache = function () {
  39433. this._positions = null;
  39434. };
  39435. /** @hidden */
  39436. Geometry.prototype._generatePointsArray = function () {
  39437. if (this._positions)
  39438. return true;
  39439. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39440. if (!data || data.length === 0) {
  39441. return false;
  39442. }
  39443. this._positions = [];
  39444. for (var index = 0; index < data.length; index += 3) {
  39445. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39446. }
  39447. return true;
  39448. };
  39449. /**
  39450. * Gets a value indicating if the geometry is disposed
  39451. * @returns true if the geometry was disposed
  39452. */
  39453. Geometry.prototype.isDisposed = function () {
  39454. return this._isDisposed;
  39455. };
  39456. Geometry.prototype._disposeVertexArrayObjects = function () {
  39457. if (this._vertexArrayObjects) {
  39458. for (var kind in this._vertexArrayObjects) {
  39459. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39460. }
  39461. this._vertexArrayObjects = {};
  39462. }
  39463. };
  39464. /**
  39465. * Free all associated resources
  39466. */
  39467. Geometry.prototype.dispose = function () {
  39468. var meshes = this._meshes;
  39469. var numOfMeshes = meshes.length;
  39470. var index;
  39471. for (index = 0; index < numOfMeshes; index++) {
  39472. this.releaseForMesh(meshes[index]);
  39473. }
  39474. this._meshes = [];
  39475. this._disposeVertexArrayObjects();
  39476. for (var kind in this._vertexBuffers) {
  39477. this._vertexBuffers[kind].dispose();
  39478. }
  39479. this._vertexBuffers = {};
  39480. this._totalVertices = 0;
  39481. if (this._indexBuffer) {
  39482. this._engine._releaseBuffer(this._indexBuffer);
  39483. }
  39484. this._indexBuffer = null;
  39485. this._indices = [];
  39486. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39487. this.delayLoadingFile = null;
  39488. this._delayLoadingFunction = null;
  39489. this._delayInfo = [];
  39490. this._boundingInfo = null;
  39491. this._scene.removeGeometry(this);
  39492. this._isDisposed = true;
  39493. };
  39494. /**
  39495. * Clone the current geometry into a new geometry
  39496. * @param id defines the unique ID of the new geometry
  39497. * @returns a new geometry object
  39498. */
  39499. Geometry.prototype.copy = function (id) {
  39500. var vertexData = new BABYLON.VertexData();
  39501. vertexData.indices = [];
  39502. var indices = this.getIndices();
  39503. if (indices) {
  39504. for (var index = 0; index < indices.length; index++) {
  39505. vertexData.indices.push(indices[index]);
  39506. }
  39507. }
  39508. var updatable = false;
  39509. var stopChecking = false;
  39510. var kind;
  39511. for (kind in this._vertexBuffers) {
  39512. // using slice() to make a copy of the array and not just reference it
  39513. var data = this.getVerticesData(kind);
  39514. if (data instanceof Float32Array) {
  39515. vertexData.set(new Float32Array(data), kind);
  39516. }
  39517. else {
  39518. vertexData.set(data.slice(0), kind);
  39519. }
  39520. if (!stopChecking) {
  39521. var vb = this.getVertexBuffer(kind);
  39522. if (vb) {
  39523. updatable = vb.isUpdatable();
  39524. stopChecking = !updatable;
  39525. }
  39526. }
  39527. }
  39528. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39529. geometry.delayLoadState = this.delayLoadState;
  39530. geometry.delayLoadingFile = this.delayLoadingFile;
  39531. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39532. for (kind in this._delayInfo) {
  39533. geometry._delayInfo = geometry._delayInfo || [];
  39534. geometry._delayInfo.push(kind);
  39535. }
  39536. // Bounding info
  39537. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39538. return geometry;
  39539. };
  39540. /**
  39541. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39542. * @return a JSON representation of the current geometry data (without the vertices data)
  39543. */
  39544. Geometry.prototype.serialize = function () {
  39545. var serializationObject = {};
  39546. serializationObject.id = this.id;
  39547. serializationObject.updatable = this._updatable;
  39548. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39549. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39550. }
  39551. return serializationObject;
  39552. };
  39553. Geometry.prototype.toNumberArray = function (origin) {
  39554. if (Array.isArray(origin)) {
  39555. return origin;
  39556. }
  39557. else {
  39558. return Array.prototype.slice.call(origin);
  39559. }
  39560. };
  39561. /**
  39562. * Serialize all vertices data into a JSON oject
  39563. * @returns a JSON representation of the current geometry data
  39564. */
  39565. Geometry.prototype.serializeVerticeData = function () {
  39566. var serializationObject = this.serialize();
  39567. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39568. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39569. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39570. serializationObject.positions._updatable = true;
  39571. }
  39572. }
  39573. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39574. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39575. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39576. serializationObject.normals._updatable = true;
  39577. }
  39578. }
  39579. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39580. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39581. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39582. serializationObject.tangets._updatable = true;
  39583. }
  39584. }
  39585. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39586. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39587. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39588. serializationObject.uvs._updatable = true;
  39589. }
  39590. }
  39591. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39592. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39593. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39594. serializationObject.uv2s._updatable = true;
  39595. }
  39596. }
  39597. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39598. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39599. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39600. serializationObject.uv3s._updatable = true;
  39601. }
  39602. }
  39603. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39604. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39605. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39606. serializationObject.uv4s._updatable = true;
  39607. }
  39608. }
  39609. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39610. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39611. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39612. serializationObject.uv5s._updatable = true;
  39613. }
  39614. }
  39615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39616. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39617. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39618. serializationObject.uv6s._updatable = true;
  39619. }
  39620. }
  39621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39622. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39623. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39624. serializationObject.colors._updatable = true;
  39625. }
  39626. }
  39627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39628. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39629. serializationObject.matricesIndices._isExpanded = true;
  39630. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39631. serializationObject.matricesIndices._updatable = true;
  39632. }
  39633. }
  39634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39635. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39636. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39637. serializationObject.matricesWeights._updatable = true;
  39638. }
  39639. }
  39640. serializationObject.indices = this.toNumberArray(this.getIndices());
  39641. return serializationObject;
  39642. };
  39643. // Statics
  39644. /**
  39645. * Extracts a clone of a mesh geometry
  39646. * @param mesh defines the source mesh
  39647. * @param id defines the unique ID of the new geometry object
  39648. * @returns the new geometry object
  39649. */
  39650. Geometry.ExtractFromMesh = function (mesh, id) {
  39651. var geometry = mesh._geometry;
  39652. if (!geometry) {
  39653. return null;
  39654. }
  39655. return geometry.copy(id);
  39656. };
  39657. /**
  39658. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39659. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39660. * Be aware Math.random() could cause collisions, but:
  39661. * "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"
  39662. * @returns a string containing a new GUID
  39663. */
  39664. Geometry.RandomId = function () {
  39665. return BABYLON.Tools.RandomId();
  39666. };
  39667. /** @hidden */
  39668. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39669. var scene = mesh.getScene();
  39670. // Geometry
  39671. var geometryId = parsedGeometry.geometryId;
  39672. if (geometryId) {
  39673. var geometry = scene.getGeometryByID(geometryId);
  39674. if (geometry) {
  39675. geometry.applyToMesh(mesh);
  39676. }
  39677. }
  39678. else if (parsedGeometry instanceof ArrayBuffer) {
  39679. var binaryInfo = mesh._binaryInfo;
  39680. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39681. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39683. }
  39684. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39685. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39686. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39687. }
  39688. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39689. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39690. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39691. }
  39692. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39693. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39695. }
  39696. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39697. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39698. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39699. }
  39700. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39701. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39702. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39703. }
  39704. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39705. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39707. }
  39708. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39709. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39711. }
  39712. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39713. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39714. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39715. }
  39716. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39717. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39718. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39719. }
  39720. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39721. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39723. }
  39724. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39725. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39727. }
  39728. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39729. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39730. mesh.setIndices(indicesData, null);
  39731. }
  39732. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39733. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39734. mesh.subMeshes = [];
  39735. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39736. var materialIndex = subMeshesData[(i * 5) + 0];
  39737. var verticesStart = subMeshesData[(i * 5) + 1];
  39738. var verticesCount = subMeshesData[(i * 5) + 2];
  39739. var indexStart = subMeshesData[(i * 5) + 3];
  39740. var indexCount = subMeshesData[(i * 5) + 4];
  39741. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39742. }
  39743. }
  39744. }
  39745. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39746. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39747. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39748. if (parsedGeometry.tangents) {
  39749. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39750. }
  39751. if (parsedGeometry.uvs) {
  39752. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39753. }
  39754. if (parsedGeometry.uvs2) {
  39755. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39756. }
  39757. if (parsedGeometry.uvs3) {
  39758. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39759. }
  39760. if (parsedGeometry.uvs4) {
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39762. }
  39763. if (parsedGeometry.uvs5) {
  39764. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39765. }
  39766. if (parsedGeometry.uvs6) {
  39767. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39768. }
  39769. if (parsedGeometry.colors) {
  39770. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39771. }
  39772. if (parsedGeometry.matricesIndices) {
  39773. if (!parsedGeometry.matricesIndices._isExpanded) {
  39774. var floatIndices = [];
  39775. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39776. var matricesIndex = parsedGeometry.matricesIndices[i];
  39777. floatIndices.push(matricesIndex & 0x000000FF);
  39778. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39779. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39780. floatIndices.push(matricesIndex >> 24);
  39781. }
  39782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39783. }
  39784. else {
  39785. delete parsedGeometry.matricesIndices._isExpanded;
  39786. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39787. }
  39788. }
  39789. if (parsedGeometry.matricesIndicesExtra) {
  39790. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39791. var floatIndices = [];
  39792. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39793. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39794. floatIndices.push(matricesIndex & 0x000000FF);
  39795. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39796. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39797. floatIndices.push(matricesIndex >> 24);
  39798. }
  39799. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39800. }
  39801. else {
  39802. delete parsedGeometry.matricesIndices._isExpanded;
  39803. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39804. }
  39805. }
  39806. if (parsedGeometry.matricesWeights) {
  39807. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39809. }
  39810. if (parsedGeometry.matricesWeightsExtra) {
  39811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39812. }
  39813. mesh.setIndices(parsedGeometry.indices, null);
  39814. }
  39815. // SubMeshes
  39816. if (parsedGeometry.subMeshes) {
  39817. mesh.subMeshes = [];
  39818. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39819. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39820. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39821. }
  39822. }
  39823. // Flat shading
  39824. if (mesh._shouldGenerateFlatShading) {
  39825. mesh.convertToFlatShadedMesh();
  39826. delete mesh._shouldGenerateFlatShading;
  39827. }
  39828. // Update
  39829. mesh.computeWorldMatrix(true);
  39830. // Octree
  39831. var sceneOctree = scene.selectionOctree;
  39832. if (sceneOctree !== undefined && sceneOctree !== null) {
  39833. sceneOctree.addMesh(mesh);
  39834. }
  39835. };
  39836. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39837. var epsilon = 1e-3;
  39838. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39839. return;
  39840. }
  39841. var noInfluenceBoneIndex = 0.0;
  39842. if (parsedGeometry.skeletonId > -1) {
  39843. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39844. if (!skeleton) {
  39845. return;
  39846. }
  39847. noInfluenceBoneIndex = skeleton.bones.length;
  39848. }
  39849. else {
  39850. return;
  39851. }
  39852. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39853. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39854. var matricesWeights = parsedGeometry.matricesWeights;
  39855. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39856. var influencers = parsedGeometry.numBoneInfluencer;
  39857. var size = matricesWeights.length;
  39858. for (var i = 0; i < size; i += 4) {
  39859. var weight = 0.0;
  39860. var firstZeroWeight = -1;
  39861. for (var j = 0; j < 4; j++) {
  39862. var w = matricesWeights[i + j];
  39863. weight += w;
  39864. if (w < epsilon && firstZeroWeight < 0) {
  39865. firstZeroWeight = j;
  39866. }
  39867. }
  39868. if (matricesWeightsExtra) {
  39869. for (var j = 0; j < 4; j++) {
  39870. var w = matricesWeightsExtra[i + j];
  39871. weight += w;
  39872. if (w < epsilon && firstZeroWeight < 0) {
  39873. firstZeroWeight = j + 4;
  39874. }
  39875. }
  39876. }
  39877. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39878. firstZeroWeight = influencers - 1;
  39879. }
  39880. if (weight > epsilon) {
  39881. var mweight = 1.0 / weight;
  39882. for (var j = 0; j < 4; j++) {
  39883. matricesWeights[i + j] *= mweight;
  39884. }
  39885. if (matricesWeightsExtra) {
  39886. for (var j = 0; j < 4; j++) {
  39887. matricesWeightsExtra[i + j] *= mweight;
  39888. }
  39889. }
  39890. }
  39891. else {
  39892. if (firstZeroWeight >= 4) {
  39893. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39894. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39895. }
  39896. else {
  39897. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39898. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39899. }
  39900. }
  39901. }
  39902. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39903. if (parsedGeometry.matricesWeightsExtra) {
  39904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39905. }
  39906. };
  39907. /**
  39908. * Create a new geometry from persisted data (Using .babylon file format)
  39909. * @param parsedVertexData defines the persisted data
  39910. * @param scene defines the hosting scene
  39911. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39912. * @returns the new geometry object
  39913. */
  39914. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39915. if (scene.getGeometryByID(parsedVertexData.id)) {
  39916. return null; // null since geometry could be something else than a box...
  39917. }
  39918. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39919. if (BABYLON.Tags) {
  39920. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39921. }
  39922. if (parsedVertexData.delayLoadingFile) {
  39923. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39924. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39925. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39926. geometry._delayInfo = [];
  39927. if (parsedVertexData.hasUVs) {
  39928. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39929. }
  39930. if (parsedVertexData.hasUVs2) {
  39931. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39932. }
  39933. if (parsedVertexData.hasUVs3) {
  39934. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39935. }
  39936. if (parsedVertexData.hasUVs4) {
  39937. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39938. }
  39939. if (parsedVertexData.hasUVs5) {
  39940. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39941. }
  39942. if (parsedVertexData.hasUVs6) {
  39943. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39944. }
  39945. if (parsedVertexData.hasColors) {
  39946. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39947. }
  39948. if (parsedVertexData.hasMatricesIndices) {
  39949. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39950. }
  39951. if (parsedVertexData.hasMatricesWeights) {
  39952. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39953. }
  39954. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39955. }
  39956. else {
  39957. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39958. }
  39959. scene.pushGeometry(geometry, true);
  39960. return geometry;
  39961. };
  39962. return Geometry;
  39963. }());
  39964. BABYLON.Geometry = Geometry;
  39965. // Primitives
  39966. /// Abstract class
  39967. /**
  39968. * Abstract class used to provide common services for all typed geometries
  39969. * @hidden
  39970. */
  39971. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39972. __extends(_PrimitiveGeometry, _super);
  39973. /**
  39974. * Creates a new typed geometry
  39975. * @param id defines the unique ID of the geometry
  39976. * @param scene defines the hosting scene
  39977. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39978. * @param mesh defines the hosting mesh (can be null)
  39979. */
  39980. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39981. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39982. if (mesh === void 0) { mesh = null; }
  39983. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39984. _this._canBeRegenerated = _canBeRegenerated;
  39985. _this._beingRegenerated = true;
  39986. _this.regenerate();
  39987. _this._beingRegenerated = false;
  39988. return _this;
  39989. }
  39990. /**
  39991. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39992. * @returns true if the geometry can be regenerated
  39993. */
  39994. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39995. return this._canBeRegenerated;
  39996. };
  39997. /**
  39998. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39999. */
  40000. _PrimitiveGeometry.prototype.regenerate = function () {
  40001. if (!this._canBeRegenerated) {
  40002. return;
  40003. }
  40004. this._beingRegenerated = true;
  40005. this.setAllVerticesData(this._regenerateVertexData(), false);
  40006. this._beingRegenerated = false;
  40007. };
  40008. /**
  40009. * Clone the geometry
  40010. * @param id defines the unique ID of the new geometry
  40011. * @returns the new geometry
  40012. */
  40013. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40014. return _super.prototype.copy.call(this, id);
  40015. };
  40016. // overrides
  40017. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40018. if (!this._beingRegenerated) {
  40019. return;
  40020. }
  40021. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40022. };
  40023. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40024. if (!this._beingRegenerated) {
  40025. return;
  40026. }
  40027. _super.prototype.setVerticesData.call(this, kind, data, false);
  40028. };
  40029. // to override
  40030. /** @hidden */
  40031. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40032. throw new Error("Abstract method");
  40033. };
  40034. _PrimitiveGeometry.prototype.copy = function (id) {
  40035. throw new Error("Must be overriden in sub-classes.");
  40036. };
  40037. _PrimitiveGeometry.prototype.serialize = function () {
  40038. var serializationObject = _super.prototype.serialize.call(this);
  40039. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40040. return serializationObject;
  40041. };
  40042. return _PrimitiveGeometry;
  40043. }(Geometry));
  40044. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40045. /**
  40046. * Creates a ribbon geometry
  40047. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40048. */
  40049. var RibbonGeometry = /** @class */ (function (_super) {
  40050. __extends(RibbonGeometry, _super);
  40051. /**
  40052. * Creates a ribbon geometry
  40053. * @param id defines the unique ID of the geometry
  40054. * @param scene defines the hosting scene
  40055. * @param pathArray defines the array of paths to use
  40056. * @param closeArray defines if the last path and the first path must be joined
  40057. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40058. * @param offset defines the offset between points
  40059. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40060. * @param mesh defines the hosting mesh (can be null)
  40061. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40062. */
  40063. function RibbonGeometry(id, scene,
  40064. /**
  40065. * Defines the array of paths to use
  40066. */
  40067. pathArray,
  40068. /**
  40069. * Defines if the last and first points of each path in your pathArray must be joined
  40070. */
  40071. closeArray,
  40072. /**
  40073. * Defines if the last and first points of each path in your pathArray must be joined
  40074. */
  40075. closePath,
  40076. /**
  40077. * Defines the offset between points
  40078. */
  40079. offset, canBeRegenerated, mesh,
  40080. /**
  40081. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40082. */
  40083. side) {
  40084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40086. _this.pathArray = pathArray;
  40087. _this.closeArray = closeArray;
  40088. _this.closePath = closePath;
  40089. _this.offset = offset;
  40090. _this.side = side;
  40091. return _this;
  40092. }
  40093. /** @hidden */
  40094. RibbonGeometry.prototype._regenerateVertexData = function () {
  40095. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40096. };
  40097. RibbonGeometry.prototype.copy = function (id) {
  40098. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40099. };
  40100. return RibbonGeometry;
  40101. }(_PrimitiveGeometry));
  40102. BABYLON.RibbonGeometry = RibbonGeometry;
  40103. /**
  40104. * Creates a box geometry
  40105. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40106. */
  40107. var BoxGeometry = /** @class */ (function (_super) {
  40108. __extends(BoxGeometry, _super);
  40109. /**
  40110. * Creates a box geometry
  40111. * @param id defines the unique ID of the geometry
  40112. * @param scene defines the hosting scene
  40113. * @param size defines the zise of the box (width, height and depth are the same)
  40114. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40115. * @param mesh defines the hosting mesh (can be null)
  40116. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40117. */
  40118. function BoxGeometry(id, scene,
  40119. /**
  40120. * Defines the zise of the box (width, height and depth are the same)
  40121. */
  40122. size, canBeRegenerated, mesh,
  40123. /**
  40124. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40125. */
  40126. side) {
  40127. if (mesh === void 0) { mesh = null; }
  40128. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40129. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40130. _this.size = size;
  40131. _this.side = side;
  40132. return _this;
  40133. }
  40134. BoxGeometry.prototype._regenerateVertexData = function () {
  40135. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40136. };
  40137. BoxGeometry.prototype.copy = function (id) {
  40138. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40139. };
  40140. BoxGeometry.prototype.serialize = function () {
  40141. var serializationObject = _super.prototype.serialize.call(this);
  40142. serializationObject.size = this.size;
  40143. return serializationObject;
  40144. };
  40145. BoxGeometry.Parse = function (parsedBox, scene) {
  40146. if (scene.getGeometryByID(parsedBox.id)) {
  40147. return null; // null since geometry could be something else than a box...
  40148. }
  40149. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40150. if (BABYLON.Tags) {
  40151. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40152. }
  40153. scene.pushGeometry(box, true);
  40154. return box;
  40155. };
  40156. return BoxGeometry;
  40157. }(_PrimitiveGeometry));
  40158. BABYLON.BoxGeometry = BoxGeometry;
  40159. /**
  40160. * Creates a sphere geometry
  40161. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40162. */
  40163. var SphereGeometry = /** @class */ (function (_super) {
  40164. __extends(SphereGeometry, _super);
  40165. /**
  40166. * Create a new sphere geometry
  40167. * @param id defines the unique ID of the geometry
  40168. * @param scene defines the hosting scene
  40169. * @param segments defines the number of segments to use to create the sphere
  40170. * @param diameter defines the diameter of the sphere
  40171. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40172. * @param mesh defines the hosting mesh (can be null)
  40173. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40174. */
  40175. function SphereGeometry(id, scene,
  40176. /**
  40177. * Defines the number of segments to use to create the sphere
  40178. */
  40179. segments,
  40180. /**
  40181. * Defines the diameter of the sphere
  40182. */
  40183. diameter, canBeRegenerated, mesh,
  40184. /**
  40185. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40186. */
  40187. side) {
  40188. if (mesh === void 0) { mesh = null; }
  40189. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40190. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40191. _this.segments = segments;
  40192. _this.diameter = diameter;
  40193. _this.side = side;
  40194. return _this;
  40195. }
  40196. SphereGeometry.prototype._regenerateVertexData = function () {
  40197. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40198. };
  40199. SphereGeometry.prototype.copy = function (id) {
  40200. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40201. };
  40202. SphereGeometry.prototype.serialize = function () {
  40203. var serializationObject = _super.prototype.serialize.call(this);
  40204. serializationObject.segments = this.segments;
  40205. serializationObject.diameter = this.diameter;
  40206. return serializationObject;
  40207. };
  40208. SphereGeometry.Parse = function (parsedSphere, scene) {
  40209. if (scene.getGeometryByID(parsedSphere.id)) {
  40210. return null; // null since geometry could be something else than a sphere...
  40211. }
  40212. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40213. if (BABYLON.Tags) {
  40214. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40215. }
  40216. scene.pushGeometry(sphere, true);
  40217. return sphere;
  40218. };
  40219. return SphereGeometry;
  40220. }(_PrimitiveGeometry));
  40221. BABYLON.SphereGeometry = SphereGeometry;
  40222. /**
  40223. * Creates a disc geometry
  40224. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40225. */
  40226. var DiscGeometry = /** @class */ (function (_super) {
  40227. __extends(DiscGeometry, _super);
  40228. /**
  40229. * Creates a new disc geometry
  40230. * @param id defines the unique ID of the geometry
  40231. * @param scene defines the hosting scene
  40232. * @param radius defines the radius of the disc
  40233. * @param tessellation defines the tesselation factor to apply to the disc
  40234. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40235. * @param mesh defines the hosting mesh (can be null)
  40236. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40237. */
  40238. function DiscGeometry(id, scene,
  40239. /**
  40240. * Defines the radius of the disc
  40241. */
  40242. radius,
  40243. /**
  40244. * Defines the tesselation factor to apply to the disc
  40245. */
  40246. tessellation, canBeRegenerated, mesh,
  40247. /**
  40248. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40249. */
  40250. side) {
  40251. if (mesh === void 0) { mesh = null; }
  40252. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40253. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40254. _this.radius = radius;
  40255. _this.tessellation = tessellation;
  40256. _this.side = side;
  40257. return _this;
  40258. }
  40259. DiscGeometry.prototype._regenerateVertexData = function () {
  40260. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40261. };
  40262. DiscGeometry.prototype.copy = function (id) {
  40263. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40264. };
  40265. return DiscGeometry;
  40266. }(_PrimitiveGeometry));
  40267. BABYLON.DiscGeometry = DiscGeometry;
  40268. /**
  40269. * Creates a new cylinder geometry
  40270. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40271. */
  40272. var CylinderGeometry = /** @class */ (function (_super) {
  40273. __extends(CylinderGeometry, _super);
  40274. /**
  40275. * Creates a new cylinder geometry
  40276. * @param id defines the unique ID of the geometry
  40277. * @param scene defines the hosting scene
  40278. * @param height defines the height of the cylinder
  40279. * @param diameterTop defines the diameter of the cylinder's top cap
  40280. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40281. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40282. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40283. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40284. * @param mesh defines the hosting mesh (can be null)
  40285. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40286. */
  40287. function CylinderGeometry(id, scene,
  40288. /**
  40289. * Defines the height of the cylinder
  40290. */
  40291. height,
  40292. /**
  40293. * Defines the diameter of the cylinder's top cap
  40294. */
  40295. diameterTop,
  40296. /**
  40297. * Defines the diameter of the cylinder's bottom cap
  40298. */
  40299. diameterBottom,
  40300. /**
  40301. * Defines the tessellation factor to apply to the cylinder
  40302. */
  40303. tessellation,
  40304. /**
  40305. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40306. */
  40307. subdivisions, canBeRegenerated, mesh,
  40308. /**
  40309. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40310. */
  40311. side) {
  40312. if (subdivisions === void 0) { subdivisions = 1; }
  40313. if (mesh === void 0) { mesh = null; }
  40314. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40315. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40316. _this.height = height;
  40317. _this.diameterTop = diameterTop;
  40318. _this.diameterBottom = diameterBottom;
  40319. _this.tessellation = tessellation;
  40320. _this.subdivisions = subdivisions;
  40321. _this.side = side;
  40322. return _this;
  40323. }
  40324. CylinderGeometry.prototype._regenerateVertexData = function () {
  40325. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40326. };
  40327. CylinderGeometry.prototype.copy = function (id) {
  40328. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40329. };
  40330. CylinderGeometry.prototype.serialize = function () {
  40331. var serializationObject = _super.prototype.serialize.call(this);
  40332. serializationObject.height = this.height;
  40333. serializationObject.diameterTop = this.diameterTop;
  40334. serializationObject.diameterBottom = this.diameterBottom;
  40335. serializationObject.tessellation = this.tessellation;
  40336. return serializationObject;
  40337. };
  40338. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40339. if (scene.getGeometryByID(parsedCylinder.id)) {
  40340. return null; // null since geometry could be something else than a cylinder...
  40341. }
  40342. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40343. if (BABYLON.Tags) {
  40344. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40345. }
  40346. scene.pushGeometry(cylinder, true);
  40347. return cylinder;
  40348. };
  40349. return CylinderGeometry;
  40350. }(_PrimitiveGeometry));
  40351. BABYLON.CylinderGeometry = CylinderGeometry;
  40352. /**
  40353. * Creates a new torus geometry
  40354. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40355. */
  40356. var TorusGeometry = /** @class */ (function (_super) {
  40357. __extends(TorusGeometry, _super);
  40358. /**
  40359. * Creates a new torus geometry
  40360. * @param id defines the unique ID of the geometry
  40361. * @param scene defines the hosting scene
  40362. * @param diameter defines the diameter of the torus
  40363. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40364. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40365. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40366. * @param mesh defines the hosting mesh (can be null)
  40367. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40368. */
  40369. function TorusGeometry(id, scene,
  40370. /**
  40371. * Defines the diameter of the torus
  40372. */
  40373. diameter,
  40374. /**
  40375. * Defines the thickness of the torus (ie. internal diameter)
  40376. */
  40377. thickness,
  40378. /**
  40379. * Defines the tesselation factor to apply to the torus
  40380. */
  40381. tessellation, canBeRegenerated, mesh,
  40382. /**
  40383. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40384. */
  40385. side) {
  40386. if (mesh === void 0) { mesh = null; }
  40387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40389. _this.diameter = diameter;
  40390. _this.thickness = thickness;
  40391. _this.tessellation = tessellation;
  40392. _this.side = side;
  40393. return _this;
  40394. }
  40395. TorusGeometry.prototype._regenerateVertexData = function () {
  40396. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40397. };
  40398. TorusGeometry.prototype.copy = function (id) {
  40399. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40400. };
  40401. TorusGeometry.prototype.serialize = function () {
  40402. var serializationObject = _super.prototype.serialize.call(this);
  40403. serializationObject.diameter = this.diameter;
  40404. serializationObject.thickness = this.thickness;
  40405. serializationObject.tessellation = this.tessellation;
  40406. return serializationObject;
  40407. };
  40408. TorusGeometry.Parse = function (parsedTorus, scene) {
  40409. if (scene.getGeometryByID(parsedTorus.id)) {
  40410. return null; // null since geometry could be something else than a torus...
  40411. }
  40412. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40413. if (BABYLON.Tags) {
  40414. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40415. }
  40416. scene.pushGeometry(torus, true);
  40417. return torus;
  40418. };
  40419. return TorusGeometry;
  40420. }(_PrimitiveGeometry));
  40421. BABYLON.TorusGeometry = TorusGeometry;
  40422. /**
  40423. * Creates a new ground geometry
  40424. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40425. */
  40426. var GroundGeometry = /** @class */ (function (_super) {
  40427. __extends(GroundGeometry, _super);
  40428. /**
  40429. * Creates a new ground geometry
  40430. * @param id defines the unique ID of the geometry
  40431. * @param scene defines the hosting scene
  40432. * @param width defines the width of the ground
  40433. * @param height defines the height of the ground
  40434. * @param subdivisions defines the subdivisions to apply to the ground
  40435. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40436. * @param mesh defines the hosting mesh (can be null)
  40437. */
  40438. function GroundGeometry(id, scene,
  40439. /**
  40440. * Defines the width of the ground
  40441. */
  40442. width,
  40443. /**
  40444. * Defines the height of the ground
  40445. */
  40446. height,
  40447. /**
  40448. * Defines the subdivisions to apply to the ground
  40449. */
  40450. subdivisions, canBeRegenerated, mesh) {
  40451. if (mesh === void 0) { mesh = null; }
  40452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40453. _this.width = width;
  40454. _this.height = height;
  40455. _this.subdivisions = subdivisions;
  40456. return _this;
  40457. }
  40458. GroundGeometry.prototype._regenerateVertexData = function () {
  40459. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40460. };
  40461. GroundGeometry.prototype.copy = function (id) {
  40462. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40463. };
  40464. GroundGeometry.prototype.serialize = function () {
  40465. var serializationObject = _super.prototype.serialize.call(this);
  40466. serializationObject.width = this.width;
  40467. serializationObject.height = this.height;
  40468. serializationObject.subdivisions = this.subdivisions;
  40469. return serializationObject;
  40470. };
  40471. GroundGeometry.Parse = function (parsedGround, scene) {
  40472. if (scene.getGeometryByID(parsedGround.id)) {
  40473. return null; // null since geometry could be something else than a ground...
  40474. }
  40475. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40476. if (BABYLON.Tags) {
  40477. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40478. }
  40479. scene.pushGeometry(ground, true);
  40480. return ground;
  40481. };
  40482. return GroundGeometry;
  40483. }(_PrimitiveGeometry));
  40484. BABYLON.GroundGeometry = GroundGeometry;
  40485. /**
  40486. * Creates a tiled ground geometry
  40487. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40488. */
  40489. var TiledGroundGeometry = /** @class */ (function (_super) {
  40490. __extends(TiledGroundGeometry, _super);
  40491. /**
  40492. * Creates a tiled ground geometry
  40493. * @param id defines the unique ID of the geometry
  40494. * @param scene defines the hosting scene
  40495. * @param xmin defines the minimum value on X axis
  40496. * @param zmin defines the minimum value on Z axis
  40497. * @param xmax defines the maximum value on X axis
  40498. * @param zmax defines the maximum value on Z axis
  40499. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40500. * @param precision defines the precision to use when computing the tiles
  40501. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40502. * @param mesh defines the hosting mesh (can be null)
  40503. */
  40504. function TiledGroundGeometry(id, scene,
  40505. /**
  40506. * Defines the minimum value on X axis
  40507. */
  40508. xmin,
  40509. /**
  40510. * Defines the minimum value on Z axis
  40511. */
  40512. zmin,
  40513. /**
  40514. * Defines the maximum value on X axis
  40515. */
  40516. xmax,
  40517. /**
  40518. * Defines the maximum value on Z axis
  40519. */
  40520. zmax,
  40521. /**
  40522. * Defines the subdivisions to apply to the ground
  40523. */
  40524. subdivisions,
  40525. /**
  40526. * Defines the precision to use when computing the tiles
  40527. */
  40528. precision, canBeRegenerated, mesh) {
  40529. if (mesh === void 0) { mesh = null; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.xmin = xmin;
  40532. _this.zmin = zmin;
  40533. _this.xmax = xmax;
  40534. _this.zmax = zmax;
  40535. _this.subdivisions = subdivisions;
  40536. _this.precision = precision;
  40537. return _this;
  40538. }
  40539. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40540. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40541. };
  40542. TiledGroundGeometry.prototype.copy = function (id) {
  40543. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40544. };
  40545. return TiledGroundGeometry;
  40546. }(_PrimitiveGeometry));
  40547. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40548. /**
  40549. * Creates a plane geometry
  40550. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40551. */
  40552. var PlaneGeometry = /** @class */ (function (_super) {
  40553. __extends(PlaneGeometry, _super);
  40554. /**
  40555. * Creates a plane geometry
  40556. * @param id defines the unique ID of the geometry
  40557. * @param scene defines the hosting scene
  40558. * @param size defines the size of the plane (width === height)
  40559. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40560. * @param mesh defines the hosting mesh (can be null)
  40561. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40562. */
  40563. function PlaneGeometry(id, scene,
  40564. /**
  40565. * Defines the size of the plane (width === height)
  40566. */
  40567. size, canBeRegenerated, mesh,
  40568. /**
  40569. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40570. */
  40571. side) {
  40572. if (mesh === void 0) { mesh = null; }
  40573. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40574. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40575. _this.size = size;
  40576. _this.side = side;
  40577. return _this;
  40578. }
  40579. PlaneGeometry.prototype._regenerateVertexData = function () {
  40580. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40581. };
  40582. PlaneGeometry.prototype.copy = function (id) {
  40583. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40584. };
  40585. PlaneGeometry.prototype.serialize = function () {
  40586. var serializationObject = _super.prototype.serialize.call(this);
  40587. serializationObject.size = this.size;
  40588. return serializationObject;
  40589. };
  40590. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40591. if (scene.getGeometryByID(parsedPlane.id)) {
  40592. return null; // null since geometry could be something else than a ground...
  40593. }
  40594. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40595. if (BABYLON.Tags) {
  40596. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40597. }
  40598. scene.pushGeometry(plane, true);
  40599. return plane;
  40600. };
  40601. return PlaneGeometry;
  40602. }(_PrimitiveGeometry));
  40603. BABYLON.PlaneGeometry = PlaneGeometry;
  40604. /**
  40605. * Creates a torus knot geometry
  40606. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40607. */
  40608. var TorusKnotGeometry = /** @class */ (function (_super) {
  40609. __extends(TorusKnotGeometry, _super);
  40610. /**
  40611. * Creates a torus knot geometry
  40612. * @param id defines the unique ID of the geometry
  40613. * @param scene defines the hosting scene
  40614. * @param radius defines the radius of the torus knot
  40615. * @param tube defines the thickness of the torus knot tube
  40616. * @param radialSegments defines the number of radial segments
  40617. * @param tubularSegments defines the number of tubular segments
  40618. * @param p defines the first number of windings
  40619. * @param q defines the second number of windings
  40620. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40621. * @param mesh defines the hosting mesh (can be null)
  40622. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40623. */
  40624. function TorusKnotGeometry(id, scene,
  40625. /**
  40626. * Defines the radius of the torus knot
  40627. */
  40628. radius,
  40629. /**
  40630. * Defines the thickness of the torus knot tube
  40631. */
  40632. tube,
  40633. /**
  40634. * Defines the number of radial segments
  40635. */
  40636. radialSegments,
  40637. /**
  40638. * Defines the number of tubular segments
  40639. */
  40640. tubularSegments,
  40641. /**
  40642. * Defines the first number of windings
  40643. */
  40644. p,
  40645. /**
  40646. * Defines the second number of windings
  40647. */
  40648. q, canBeRegenerated, mesh,
  40649. /**
  40650. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40651. */
  40652. side) {
  40653. if (mesh === void 0) { mesh = null; }
  40654. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40655. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40656. _this.radius = radius;
  40657. _this.tube = tube;
  40658. _this.radialSegments = radialSegments;
  40659. _this.tubularSegments = tubularSegments;
  40660. _this.p = p;
  40661. _this.q = q;
  40662. _this.side = side;
  40663. return _this;
  40664. }
  40665. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40666. 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 });
  40667. };
  40668. TorusKnotGeometry.prototype.copy = function (id) {
  40669. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40670. };
  40671. TorusKnotGeometry.prototype.serialize = function () {
  40672. var serializationObject = _super.prototype.serialize.call(this);
  40673. serializationObject.radius = this.radius;
  40674. serializationObject.tube = this.tube;
  40675. serializationObject.radialSegments = this.radialSegments;
  40676. serializationObject.tubularSegments = this.tubularSegments;
  40677. serializationObject.p = this.p;
  40678. serializationObject.q = this.q;
  40679. return serializationObject;
  40680. };
  40681. ;
  40682. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40683. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40684. return null; // null since geometry could be something else than a ground...
  40685. }
  40686. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40687. if (BABYLON.Tags) {
  40688. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40689. }
  40690. scene.pushGeometry(torusKnot, true);
  40691. return torusKnot;
  40692. };
  40693. return TorusKnotGeometry;
  40694. }(_PrimitiveGeometry));
  40695. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40696. //}
  40697. })(BABYLON || (BABYLON = {}));
  40698. //# sourceMappingURL=babylon.geometry.js.map
  40699. var BABYLON;
  40700. (function (BABYLON) {
  40701. /**
  40702. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40703. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40704. */
  40705. var PostProcessManager = /** @class */ (function () {
  40706. /**
  40707. * Creates a new instance PostProcess
  40708. * @param scene The scene that the post process is associated with.
  40709. */
  40710. function PostProcessManager(scene) {
  40711. this._vertexBuffers = {};
  40712. this._scene = scene;
  40713. }
  40714. PostProcessManager.prototype._prepareBuffers = function () {
  40715. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40716. return;
  40717. }
  40718. // VBO
  40719. var vertices = [];
  40720. vertices.push(1, 1);
  40721. vertices.push(-1, 1);
  40722. vertices.push(-1, -1);
  40723. vertices.push(1, -1);
  40724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40725. this._buildIndexBuffer();
  40726. };
  40727. PostProcessManager.prototype._buildIndexBuffer = function () {
  40728. // Indices
  40729. var indices = [];
  40730. indices.push(0);
  40731. indices.push(1);
  40732. indices.push(2);
  40733. indices.push(0);
  40734. indices.push(2);
  40735. indices.push(3);
  40736. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40737. };
  40738. /**
  40739. * Rebuilds the vertex buffers of the manager.
  40740. */
  40741. PostProcessManager.prototype._rebuild = function () {
  40742. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40743. if (!vb) {
  40744. return;
  40745. }
  40746. vb._rebuild();
  40747. this._buildIndexBuffer();
  40748. };
  40749. // Methods
  40750. /**
  40751. * Prepares a frame to be run through a post process.
  40752. * @param sourceTexture The input texture to the post procesess. (default: null)
  40753. * @param postProcesses An array of post processes to be run. (default: null)
  40754. * @returns True if the post processes were able to be run.
  40755. */
  40756. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40757. if (sourceTexture === void 0) { sourceTexture = null; }
  40758. if (postProcesses === void 0) { postProcesses = null; }
  40759. var camera = this._scene.activeCamera;
  40760. if (!camera) {
  40761. return false;
  40762. }
  40763. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40764. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40765. return false;
  40766. }
  40767. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40768. return true;
  40769. };
  40770. /**
  40771. * Manually render a set of post processes to a texture.
  40772. * @param postProcesses An array of post processes to be run.
  40773. * @param targetTexture The target texture to render to.
  40774. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40775. */
  40776. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40777. if (targetTexture === void 0) { targetTexture = null; }
  40778. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40779. var engine = this._scene.getEngine();
  40780. for (var index = 0; index < postProcesses.length; index++) {
  40781. if (index < postProcesses.length - 1) {
  40782. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40783. }
  40784. else {
  40785. if (targetTexture) {
  40786. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40787. }
  40788. else {
  40789. engine.restoreDefaultFramebuffer();
  40790. }
  40791. }
  40792. var pp = postProcesses[index];
  40793. var effect = pp.apply();
  40794. if (effect) {
  40795. pp.onBeforeRenderObservable.notifyObservers(effect);
  40796. // VBOs
  40797. this._prepareBuffers();
  40798. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40799. // Draw order
  40800. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40801. pp.onAfterRenderObservable.notifyObservers(effect);
  40802. }
  40803. }
  40804. // Restore depth buffer
  40805. engine.setDepthBuffer(true);
  40806. engine.setDepthWrite(true);
  40807. };
  40808. /**
  40809. * Finalize the result of the output of the postprocesses.
  40810. * @param doNotPresent If true the result will not be displayed to the screen.
  40811. * @param targetTexture The target texture to render to.
  40812. * @param faceIndex The index of the face to bind the target texture to.
  40813. * @param postProcesses The array of post processes to render.
  40814. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40815. */
  40816. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40817. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40818. var camera = this._scene.activeCamera;
  40819. if (!camera) {
  40820. return;
  40821. }
  40822. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40823. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40824. return;
  40825. }
  40826. var engine = this._scene.getEngine();
  40827. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40828. var pp = postProcesses[index];
  40829. if (index < len - 1) {
  40830. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40831. }
  40832. else {
  40833. if (targetTexture) {
  40834. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40835. pp._outputTexture = targetTexture;
  40836. }
  40837. else {
  40838. engine.restoreDefaultFramebuffer();
  40839. pp._outputTexture = null;
  40840. }
  40841. }
  40842. if (doNotPresent) {
  40843. break;
  40844. }
  40845. var effect = pp.apply();
  40846. if (effect) {
  40847. pp.onBeforeRenderObservable.notifyObservers(effect);
  40848. // VBOs
  40849. this._prepareBuffers();
  40850. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40851. // Draw order
  40852. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40853. pp.onAfterRenderObservable.notifyObservers(effect);
  40854. }
  40855. }
  40856. // Restore states
  40857. engine.setDepthBuffer(true);
  40858. engine.setDepthWrite(true);
  40859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40860. };
  40861. /**
  40862. * Disposes of the post process manager.
  40863. */
  40864. PostProcessManager.prototype.dispose = function () {
  40865. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40866. if (buffer) {
  40867. buffer.dispose();
  40868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40869. }
  40870. if (this._indexBuffer) {
  40871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40872. this._indexBuffer = null;
  40873. }
  40874. };
  40875. return PostProcessManager;
  40876. }());
  40877. BABYLON.PostProcessManager = PostProcessManager;
  40878. })(BABYLON || (BABYLON = {}));
  40879. //# sourceMappingURL=babylon.postProcessManager.js.map
  40880. var BABYLON;
  40881. (function (BABYLON) {
  40882. /**
  40883. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40884. */
  40885. var PerformanceMonitor = /** @class */ (function () {
  40886. /**
  40887. * constructor
  40888. * @param frameSampleSize The number of samples required to saturate the sliding window
  40889. */
  40890. function PerformanceMonitor(frameSampleSize) {
  40891. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40892. this._enabled = true;
  40893. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40894. }
  40895. /**
  40896. * Samples current frame
  40897. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40898. */
  40899. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40900. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40901. if (!this._enabled)
  40902. return;
  40903. if (this._lastFrameTimeMs != null) {
  40904. var dt = timeMs - this._lastFrameTimeMs;
  40905. this._rollingFrameTime.add(dt);
  40906. }
  40907. this._lastFrameTimeMs = timeMs;
  40908. };
  40909. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40910. /**
  40911. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40912. * @return Average frame time in milliseconds
  40913. */
  40914. get: function () {
  40915. return this._rollingFrameTime.average;
  40916. },
  40917. enumerable: true,
  40918. configurable: true
  40919. });
  40920. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40921. /**
  40922. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40923. * @return Frame time variance in milliseconds squared
  40924. */
  40925. get: function () {
  40926. return this._rollingFrameTime.variance;
  40927. },
  40928. enumerable: true,
  40929. configurable: true
  40930. });
  40931. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40932. /**
  40933. * Returns the frame time of the most recent frame
  40934. * @return Frame time in milliseconds
  40935. */
  40936. get: function () {
  40937. return this._rollingFrameTime.history(0);
  40938. },
  40939. enumerable: true,
  40940. configurable: true
  40941. });
  40942. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40943. /**
  40944. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40945. * @return Framerate in frames per second
  40946. */
  40947. get: function () {
  40948. return 1000.0 / this._rollingFrameTime.average;
  40949. },
  40950. enumerable: true,
  40951. configurable: true
  40952. });
  40953. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40954. /**
  40955. * Returns the average framerate in frames per second using the most recent frame time
  40956. * @return Framerate in frames per second
  40957. */
  40958. get: function () {
  40959. var history = this._rollingFrameTime.history(0);
  40960. if (history === 0) {
  40961. return 0;
  40962. }
  40963. return 1000.0 / history;
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40969. /**
  40970. * Returns true if enough samples have been taken to completely fill the sliding window
  40971. * @return true if saturated
  40972. */
  40973. get: function () {
  40974. return this._rollingFrameTime.isSaturated();
  40975. },
  40976. enumerable: true,
  40977. configurable: true
  40978. });
  40979. /**
  40980. * Enables contributions to the sliding window sample set
  40981. */
  40982. PerformanceMonitor.prototype.enable = function () {
  40983. this._enabled = true;
  40984. };
  40985. /**
  40986. * Disables contributions to the sliding window sample set
  40987. * Samples will not be interpolated over the disabled period
  40988. */
  40989. PerformanceMonitor.prototype.disable = function () {
  40990. this._enabled = false;
  40991. //clear last sample to avoid interpolating over the disabled period when next enabled
  40992. this._lastFrameTimeMs = null;
  40993. };
  40994. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40995. /**
  40996. * Returns true if sampling is enabled
  40997. * @return true if enabled
  40998. */
  40999. get: function () {
  41000. return this._enabled;
  41001. },
  41002. enumerable: true,
  41003. configurable: true
  41004. });
  41005. /**
  41006. * Resets performance monitor
  41007. */
  41008. PerformanceMonitor.prototype.reset = function () {
  41009. //clear last sample to avoid interpolating over the disabled period when next enabled
  41010. this._lastFrameTimeMs = null;
  41011. //wipe record
  41012. this._rollingFrameTime.reset();
  41013. };
  41014. return PerformanceMonitor;
  41015. }());
  41016. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41017. /**
  41018. * RollingAverage
  41019. *
  41020. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41021. */
  41022. var RollingAverage = /** @class */ (function () {
  41023. /**
  41024. * constructor
  41025. * @param length The number of samples required to saturate the sliding window
  41026. */
  41027. function RollingAverage(length) {
  41028. this._samples = new Array(length);
  41029. this.reset();
  41030. }
  41031. /**
  41032. * Adds a sample to the sample set
  41033. * @param v The sample value
  41034. */
  41035. RollingAverage.prototype.add = function (v) {
  41036. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41037. var delta;
  41038. //we need to check if we've already wrapped round
  41039. if (this.isSaturated()) {
  41040. //remove bottom of stack from mean
  41041. var bottomValue = this._samples[this._pos];
  41042. delta = bottomValue - this.average;
  41043. this.average -= delta / (this._sampleCount - 1);
  41044. this._m2 -= delta * (bottomValue - this.average);
  41045. }
  41046. else {
  41047. this._sampleCount++;
  41048. }
  41049. //add new value to mean
  41050. delta = v - this.average;
  41051. this.average += delta / (this._sampleCount);
  41052. this._m2 += delta * (v - this.average);
  41053. //set the new variance
  41054. this.variance = this._m2 / (this._sampleCount - 1);
  41055. this._samples[this._pos] = v;
  41056. this._pos++;
  41057. this._pos %= this._samples.length; //positive wrap around
  41058. };
  41059. /**
  41060. * Returns previously added values or null if outside of history or outside the sliding window domain
  41061. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41062. * @return Value previously recorded with add() or null if outside of range
  41063. */
  41064. RollingAverage.prototype.history = function (i) {
  41065. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41066. return 0;
  41067. }
  41068. var i0 = this._wrapPosition(this._pos - 1.0);
  41069. return this._samples[this._wrapPosition(i0 - i)];
  41070. };
  41071. /**
  41072. * Returns true if enough samples have been taken to completely fill the sliding window
  41073. * @return true if sample-set saturated
  41074. */
  41075. RollingAverage.prototype.isSaturated = function () {
  41076. return this._sampleCount >= this._samples.length;
  41077. };
  41078. /**
  41079. * Resets the rolling average (equivalent to 0 samples taken so far)
  41080. */
  41081. RollingAverage.prototype.reset = function () {
  41082. this.average = 0;
  41083. this.variance = 0;
  41084. this._sampleCount = 0;
  41085. this._pos = 0;
  41086. this._m2 = 0;
  41087. };
  41088. /**
  41089. * Wraps a value around the sample range boundaries
  41090. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41091. * @return Wrapped position in sample range
  41092. */
  41093. RollingAverage.prototype._wrapPosition = function (i) {
  41094. var max = this._samples.length;
  41095. return ((i % max) + max) % max;
  41096. };
  41097. return RollingAverage;
  41098. }());
  41099. BABYLON.RollingAverage = RollingAverage;
  41100. })(BABYLON || (BABYLON = {}));
  41101. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41102. var BABYLON;
  41103. (function (BABYLON) {
  41104. /**
  41105. * This groups together the common properties used for image processing either in direct forward pass
  41106. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41107. * or not.
  41108. */
  41109. var ImageProcessingConfiguration = /** @class */ (function () {
  41110. function ImageProcessingConfiguration() {
  41111. /**
  41112. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41113. */
  41114. this.colorCurves = new BABYLON.ColorCurves();
  41115. this._colorCurvesEnabled = false;
  41116. this._colorGradingEnabled = false;
  41117. this._colorGradingWithGreenDepth = true;
  41118. this._colorGradingBGR = true;
  41119. this._exposure = 1.0;
  41120. this._toneMappingEnabled = false;
  41121. this._contrast = 1.0;
  41122. /**
  41123. * Vignette stretch size.
  41124. */
  41125. this.vignetteStretch = 0;
  41126. /**
  41127. * Vignette centre X Offset.
  41128. */
  41129. this.vignetteCentreX = 0;
  41130. /**
  41131. * Vignette centre Y Offset.
  41132. */
  41133. this.vignetteCentreY = 0;
  41134. /**
  41135. * Vignette weight or intensity of the vignette effect.
  41136. */
  41137. this.vignetteWeight = 1.5;
  41138. /**
  41139. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41140. * if vignetteEnabled is set to true.
  41141. */
  41142. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41143. /**
  41144. * Camera field of view used by the Vignette effect.
  41145. */
  41146. this.vignetteCameraFov = 0.5;
  41147. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41148. this._vignetteEnabled = false;
  41149. this._applyByPostProcess = false;
  41150. this._isEnabled = true;
  41151. /**
  41152. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41153. */
  41154. this.onUpdateParameters = new BABYLON.Observable();
  41155. }
  41156. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41157. /**
  41158. * Gets wether the color curves effect is enabled.
  41159. */
  41160. get: function () {
  41161. return this._colorCurvesEnabled;
  41162. },
  41163. /**
  41164. * Sets wether the color curves effect is enabled.
  41165. */
  41166. set: function (value) {
  41167. if (this._colorCurvesEnabled === value) {
  41168. return;
  41169. }
  41170. this._colorCurvesEnabled = value;
  41171. this._updateParameters();
  41172. },
  41173. enumerable: true,
  41174. configurable: true
  41175. });
  41176. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41177. /**
  41178. * Gets wether the color grading effect is enabled.
  41179. */
  41180. get: function () {
  41181. return this._colorGradingEnabled;
  41182. },
  41183. /**
  41184. * Sets wether the color grading effect is enabled.
  41185. */
  41186. set: function (value) {
  41187. if (this._colorGradingEnabled === value) {
  41188. return;
  41189. }
  41190. this._colorGradingEnabled = value;
  41191. this._updateParameters();
  41192. },
  41193. enumerable: true,
  41194. configurable: true
  41195. });
  41196. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41197. /**
  41198. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41199. */
  41200. get: function () {
  41201. return this._colorGradingWithGreenDepth;
  41202. },
  41203. /**
  41204. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41205. */
  41206. set: function (value) {
  41207. if (this._colorGradingWithGreenDepth === value) {
  41208. return;
  41209. }
  41210. this._colorGradingWithGreenDepth = value;
  41211. this._updateParameters();
  41212. },
  41213. enumerable: true,
  41214. configurable: true
  41215. });
  41216. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41217. /**
  41218. * Gets wether the color grading texture contains BGR values.
  41219. */
  41220. get: function () {
  41221. return this._colorGradingBGR;
  41222. },
  41223. /**
  41224. * Sets wether the color grading texture contains BGR values.
  41225. */
  41226. set: function (value) {
  41227. if (this._colorGradingBGR === value) {
  41228. return;
  41229. }
  41230. this._colorGradingBGR = value;
  41231. this._updateParameters();
  41232. },
  41233. enumerable: true,
  41234. configurable: true
  41235. });
  41236. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41237. /**
  41238. * Gets the Exposure used in the effect.
  41239. */
  41240. get: function () {
  41241. return this._exposure;
  41242. },
  41243. /**
  41244. * Sets the Exposure used in the effect.
  41245. */
  41246. set: function (value) {
  41247. if (this._exposure === value) {
  41248. return;
  41249. }
  41250. this._exposure = value;
  41251. this._updateParameters();
  41252. },
  41253. enumerable: true,
  41254. configurable: true
  41255. });
  41256. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41257. /**
  41258. * Gets wether the tone mapping effect is enabled.
  41259. */
  41260. get: function () {
  41261. return this._toneMappingEnabled;
  41262. },
  41263. /**
  41264. * Sets wether the tone mapping effect is enabled.
  41265. */
  41266. set: function (value) {
  41267. if (this._toneMappingEnabled === value) {
  41268. return;
  41269. }
  41270. this._toneMappingEnabled = value;
  41271. this._updateParameters();
  41272. },
  41273. enumerable: true,
  41274. configurable: true
  41275. });
  41276. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41277. /**
  41278. * Gets the contrast used in the effect.
  41279. */
  41280. get: function () {
  41281. return this._contrast;
  41282. },
  41283. /**
  41284. * Sets the contrast used in the effect.
  41285. */
  41286. set: function (value) {
  41287. if (this._contrast === value) {
  41288. return;
  41289. }
  41290. this._contrast = value;
  41291. this._updateParameters();
  41292. },
  41293. enumerable: true,
  41294. configurable: true
  41295. });
  41296. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41297. /**
  41298. * Gets the vignette blend mode allowing different kind of effect.
  41299. */
  41300. get: function () {
  41301. return this._vignetteBlendMode;
  41302. },
  41303. /**
  41304. * Sets the vignette blend mode allowing different kind of effect.
  41305. */
  41306. set: function (value) {
  41307. if (this._vignetteBlendMode === value) {
  41308. return;
  41309. }
  41310. this._vignetteBlendMode = value;
  41311. this._updateParameters();
  41312. },
  41313. enumerable: true,
  41314. configurable: true
  41315. });
  41316. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41317. /**
  41318. * Gets wether the vignette effect is enabled.
  41319. */
  41320. get: function () {
  41321. return this._vignetteEnabled;
  41322. },
  41323. /**
  41324. * Sets wether the vignette effect is enabled.
  41325. */
  41326. set: function (value) {
  41327. if (this._vignetteEnabled === value) {
  41328. return;
  41329. }
  41330. this._vignetteEnabled = value;
  41331. this._updateParameters();
  41332. },
  41333. enumerable: true,
  41334. configurable: true
  41335. });
  41336. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41337. /**
  41338. * Gets wether the image processing is applied through a post process or not.
  41339. */
  41340. get: function () {
  41341. return this._applyByPostProcess;
  41342. },
  41343. /**
  41344. * Sets wether the image processing is applied through a post process or not.
  41345. */
  41346. set: function (value) {
  41347. if (this._applyByPostProcess === value) {
  41348. return;
  41349. }
  41350. this._applyByPostProcess = value;
  41351. this._updateParameters();
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41357. /**
  41358. * Gets wether the image processing is enabled or not.
  41359. */
  41360. get: function () {
  41361. return this._isEnabled;
  41362. },
  41363. /**
  41364. * Sets wether the image processing is enabled or not.
  41365. */
  41366. set: function (value) {
  41367. if (this._isEnabled === value) {
  41368. return;
  41369. }
  41370. this._isEnabled = value;
  41371. this._updateParameters();
  41372. },
  41373. enumerable: true,
  41374. configurable: true
  41375. });
  41376. /**
  41377. * Method called each time the image processing information changes requires to recompile the effect.
  41378. */
  41379. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41380. this.onUpdateParameters.notifyObservers(this);
  41381. };
  41382. ImageProcessingConfiguration.prototype.getClassName = function () {
  41383. return "ImageProcessingConfiguration";
  41384. };
  41385. /**
  41386. * Prepare the list of uniforms associated with the Image Processing effects.
  41387. * @param uniformsList The list of uniforms used in the effect
  41388. * @param defines the list of defines currently in use
  41389. */
  41390. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41391. if (defines.EXPOSURE) {
  41392. uniforms.push("exposureLinear");
  41393. }
  41394. if (defines.CONTRAST) {
  41395. uniforms.push("contrast");
  41396. }
  41397. if (defines.COLORGRADING) {
  41398. uniforms.push("colorTransformSettings");
  41399. }
  41400. if (defines.VIGNETTE) {
  41401. uniforms.push("vInverseScreenSize");
  41402. uniforms.push("vignetteSettings1");
  41403. uniforms.push("vignetteSettings2");
  41404. }
  41405. if (defines.COLORCURVES) {
  41406. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41407. }
  41408. };
  41409. /**
  41410. * Prepare the list of samplers associated with the Image Processing effects.
  41411. * @param uniformsList The list of uniforms used in the effect
  41412. * @param defines the list of defines currently in use
  41413. */
  41414. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41415. if (defines.COLORGRADING) {
  41416. samplersList.push("txColorTransform");
  41417. }
  41418. };
  41419. /**
  41420. * Prepare the list of defines associated to the shader.
  41421. * @param defines the list of defines to complete
  41422. */
  41423. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41424. if (forPostProcess === void 0) { forPostProcess = false; }
  41425. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41426. defines.VIGNETTE = false;
  41427. defines.TONEMAPPING = false;
  41428. defines.CONTRAST = false;
  41429. defines.EXPOSURE = false;
  41430. defines.COLORCURVES = false;
  41431. defines.COLORGRADING = false;
  41432. defines.COLORGRADING3D = false;
  41433. defines.IMAGEPROCESSING = false;
  41434. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41435. return;
  41436. }
  41437. defines.VIGNETTE = this.vignetteEnabled;
  41438. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41439. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41440. defines.TONEMAPPING = this.toneMappingEnabled;
  41441. defines.CONTRAST = (this.contrast !== 1.0);
  41442. defines.EXPOSURE = (this.exposure !== 1.0);
  41443. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41444. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41445. if (defines.COLORGRADING) {
  41446. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41447. }
  41448. else {
  41449. defines.COLORGRADING3D = false;
  41450. }
  41451. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41452. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41453. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41454. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41455. };
  41456. /**
  41457. * Returns true if all the image processing information are ready.
  41458. */
  41459. ImageProcessingConfiguration.prototype.isReady = function () {
  41460. // Color Grading texure can not be none blocking.
  41461. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41462. };
  41463. /**
  41464. * Binds the image processing to the shader.
  41465. * @param effect The effect to bind to
  41466. */
  41467. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41468. if (aspectRatio === void 0) { aspectRatio = 1; }
  41469. // Color Curves
  41470. if (this._colorCurvesEnabled && this.colorCurves) {
  41471. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41472. }
  41473. // Vignette
  41474. if (this._vignetteEnabled) {
  41475. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41476. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41477. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41478. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41479. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41480. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41481. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41482. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41483. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41484. var vignettePower = -2.0 * this.vignetteWeight;
  41485. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41486. }
  41487. // Exposure
  41488. effect.setFloat("exposureLinear", this.exposure);
  41489. // Contrast
  41490. effect.setFloat("contrast", this.contrast);
  41491. // Color transform settings
  41492. if (this.colorGradingTexture) {
  41493. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41494. var textureSize = this.colorGradingTexture.getSize().height;
  41495. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41496. 0.5 / textureSize, // textureOffset
  41497. textureSize, // textureSize
  41498. this.colorGradingTexture.level // weight
  41499. );
  41500. }
  41501. };
  41502. /**
  41503. * Clones the current image processing instance.
  41504. * @return The cloned image processing
  41505. */
  41506. ImageProcessingConfiguration.prototype.clone = function () {
  41507. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41508. };
  41509. /**
  41510. * Serializes the current image processing instance to a json representation.
  41511. * @return a JSON representation
  41512. */
  41513. ImageProcessingConfiguration.prototype.serialize = function () {
  41514. return BABYLON.SerializationHelper.Serialize(this);
  41515. };
  41516. /**
  41517. * Parses the image processing from a json representation.
  41518. * @param source the JSON source to parse
  41519. * @return The parsed image processing
  41520. */
  41521. ImageProcessingConfiguration.Parse = function (source) {
  41522. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41523. };
  41524. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41525. /**
  41526. * Used to apply the vignette as a mix with the pixel color.
  41527. */
  41528. get: function () {
  41529. return this._VIGNETTEMODE_MULTIPLY;
  41530. },
  41531. enumerable: true,
  41532. configurable: true
  41533. });
  41534. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41535. /**
  41536. * Used to apply the vignette as a replacement of the pixel color.
  41537. */
  41538. get: function () {
  41539. return this._VIGNETTEMODE_OPAQUE;
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. // Static constants associated to the image processing.
  41545. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41546. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41547. __decorate([
  41548. BABYLON.serializeAsColorCurves()
  41549. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41550. __decorate([
  41551. BABYLON.serialize()
  41552. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41553. __decorate([
  41554. BABYLON.serializeAsTexture()
  41555. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41556. __decorate([
  41557. BABYLON.serialize()
  41558. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41559. __decorate([
  41560. BABYLON.serialize()
  41561. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41562. __decorate([
  41563. BABYLON.serialize()
  41564. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41565. __decorate([
  41566. BABYLON.serialize()
  41567. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41568. __decorate([
  41569. BABYLON.serialize()
  41570. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41571. __decorate([
  41572. BABYLON.serialize()
  41573. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41574. __decorate([
  41575. BABYLON.serialize()
  41576. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41577. __decorate([
  41578. BABYLON.serialize()
  41579. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41580. __decorate([
  41581. BABYLON.serialize()
  41582. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41583. __decorate([
  41584. BABYLON.serialize()
  41585. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41586. __decorate([
  41587. BABYLON.serializeAsColor4()
  41588. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41589. __decorate([
  41590. BABYLON.serialize()
  41591. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41592. __decorate([
  41593. BABYLON.serialize()
  41594. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41595. __decorate([
  41596. BABYLON.serialize()
  41597. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41598. __decorate([
  41599. BABYLON.serialize()
  41600. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41601. __decorate([
  41602. BABYLON.serialize()
  41603. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41604. return ImageProcessingConfiguration;
  41605. }());
  41606. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41607. })(BABYLON || (BABYLON = {}));
  41608. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41609. var BABYLON;
  41610. (function (BABYLON) {
  41611. /**
  41612. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41613. * It can help converting any input color in a desired output one. This can then be used to create effects
  41614. * from sepia, black and white to sixties or futuristic rendering...
  41615. *
  41616. * The only supported format is currently 3dl.
  41617. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41618. */
  41619. var ColorGradingTexture = /** @class */ (function (_super) {
  41620. __extends(ColorGradingTexture, _super);
  41621. /**
  41622. * Instantiates a ColorGradingTexture from the following parameters.
  41623. *
  41624. * @param url The location of the color gradind data (currently only supporting 3dl)
  41625. * @param scene The scene the texture will be used in
  41626. */
  41627. function ColorGradingTexture(url, scene) {
  41628. var _this = _super.call(this, scene) || this;
  41629. if (!url) {
  41630. return _this;
  41631. }
  41632. _this._engine = scene.getEngine();
  41633. _this._textureMatrix = BABYLON.Matrix.Identity();
  41634. _this.name = url;
  41635. _this.url = url;
  41636. _this.hasAlpha = false;
  41637. _this.isCube = false;
  41638. _this.is3D = _this._engine.webGLVersion > 1;
  41639. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41640. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41641. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41642. _this.anisotropicFilteringLevel = 1;
  41643. _this._texture = _this._getFromCache(url, true);
  41644. if (!_this._texture) {
  41645. if (!scene.useDelayedTextureLoading) {
  41646. _this.loadTexture();
  41647. }
  41648. else {
  41649. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41650. }
  41651. }
  41652. return _this;
  41653. }
  41654. /**
  41655. * Returns the texture matrix used in most of the material.
  41656. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41657. */
  41658. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41659. return this._textureMatrix;
  41660. };
  41661. /**
  41662. * Occurs when the file being loaded is a .3dl LUT file.
  41663. */
  41664. ColorGradingTexture.prototype.load3dlTexture = function () {
  41665. var engine = this._engine;
  41666. var texture;
  41667. if (engine.webGLVersion === 1) {
  41668. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41669. }
  41670. else {
  41671. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41672. }
  41673. this._texture = texture;
  41674. var callback = function (text) {
  41675. if (typeof text !== "string") {
  41676. return;
  41677. }
  41678. var data = null;
  41679. var tempData = null;
  41680. var line;
  41681. var lines = text.split('\n');
  41682. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41683. var maxColor = 0;
  41684. for (var i = 0; i < lines.length; i++) {
  41685. line = lines[i];
  41686. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41687. continue;
  41688. if (line.indexOf('#') === 0)
  41689. continue;
  41690. var words = line.split(" ");
  41691. if (size === 0) {
  41692. // Number of space + one
  41693. size = words.length;
  41694. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41695. tempData = new Float32Array(size * size * size * 4);
  41696. continue;
  41697. }
  41698. if (size != 0) {
  41699. var r = Math.max(parseInt(words[0]), 0);
  41700. var g = Math.max(parseInt(words[1]), 0);
  41701. var b = Math.max(parseInt(words[2]), 0);
  41702. maxColor = Math.max(r, maxColor);
  41703. maxColor = Math.max(g, maxColor);
  41704. maxColor = Math.max(b, maxColor);
  41705. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41706. if (tempData) {
  41707. tempData[pixelStorageIndex + 0] = r;
  41708. tempData[pixelStorageIndex + 1] = g;
  41709. tempData[pixelStorageIndex + 2] = b;
  41710. }
  41711. pixelIndexSlice++;
  41712. if (pixelIndexSlice % size == 0) {
  41713. pixelIndexH++;
  41714. pixelIndexSlice = 0;
  41715. if (pixelIndexH % size == 0) {
  41716. pixelIndexW++;
  41717. pixelIndexH = 0;
  41718. }
  41719. }
  41720. }
  41721. }
  41722. if (tempData && data) {
  41723. for (var i = 0; i < tempData.length; i++) {
  41724. if (i > 0 && (i + 1) % 4 === 0) {
  41725. data[i] = 255;
  41726. }
  41727. else {
  41728. var value = tempData[i];
  41729. data[i] = (value / maxColor * 255);
  41730. }
  41731. }
  41732. }
  41733. if (texture.is3D) {
  41734. texture.updateSize(size, size, size);
  41735. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41736. }
  41737. else {
  41738. texture.updateSize(size * size, size);
  41739. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41740. }
  41741. };
  41742. var scene = this.getScene();
  41743. if (scene) {
  41744. scene._loadFile(this.url, callback);
  41745. }
  41746. else {
  41747. this._engine._loadFile(this.url, callback);
  41748. }
  41749. return this._texture;
  41750. };
  41751. /**
  41752. * Starts the loading process of the texture.
  41753. */
  41754. ColorGradingTexture.prototype.loadTexture = function () {
  41755. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41756. this.load3dlTexture();
  41757. }
  41758. };
  41759. /**
  41760. * Clones the color gradind texture.
  41761. */
  41762. ColorGradingTexture.prototype.clone = function () {
  41763. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41764. // Base texture
  41765. newTexture.level = this.level;
  41766. return newTexture;
  41767. };
  41768. /**
  41769. * Called during delayed load for textures.
  41770. */
  41771. ColorGradingTexture.prototype.delayLoad = function () {
  41772. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41773. return;
  41774. }
  41775. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41776. this._texture = this._getFromCache(this.url, true);
  41777. if (!this._texture) {
  41778. this.loadTexture();
  41779. }
  41780. };
  41781. /**
  41782. * Parses a color grading texture serialized by Babylon.
  41783. * @param parsedTexture The texture information being parsedTexture
  41784. * @param scene The scene to load the texture in
  41785. * @param rootUrl The root url of the data assets to load
  41786. * @return A color gradind texture
  41787. */
  41788. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41789. var texture = null;
  41790. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41791. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41792. texture.name = parsedTexture.name;
  41793. texture.level = parsedTexture.level;
  41794. }
  41795. return texture;
  41796. };
  41797. /**
  41798. * Serializes the LUT texture to json format.
  41799. */
  41800. ColorGradingTexture.prototype.serialize = function () {
  41801. if (!this.name) {
  41802. return null;
  41803. }
  41804. var serializationObject = {};
  41805. serializationObject.name = this.name;
  41806. serializationObject.level = this.level;
  41807. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41808. return serializationObject;
  41809. };
  41810. /**
  41811. * Empty line regex stored for GC.
  41812. */
  41813. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41814. return ColorGradingTexture;
  41815. }(BABYLON.BaseTexture));
  41816. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41817. })(BABYLON || (BABYLON = {}));
  41818. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41819. var BABYLON;
  41820. (function (BABYLON) {
  41821. /**
  41822. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41823. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41824. * 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;
  41825. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41826. */
  41827. var ColorCurves = /** @class */ (function () {
  41828. function ColorCurves() {
  41829. this._dirty = true;
  41830. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41831. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41832. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41833. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41834. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41835. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41836. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41837. this._globalHue = 30;
  41838. this._globalDensity = 0;
  41839. this._globalSaturation = 0;
  41840. this._globalExposure = 0;
  41841. this._highlightsHue = 30;
  41842. this._highlightsDensity = 0;
  41843. this._highlightsSaturation = 0;
  41844. this._highlightsExposure = 0;
  41845. this._midtonesHue = 30;
  41846. this._midtonesDensity = 0;
  41847. this._midtonesSaturation = 0;
  41848. this._midtonesExposure = 0;
  41849. this._shadowsHue = 30;
  41850. this._shadowsDensity = 0;
  41851. this._shadowsSaturation = 0;
  41852. this._shadowsExposure = 0;
  41853. }
  41854. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41855. /**
  41856. * Gets the global Hue value.
  41857. * 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).
  41858. */
  41859. get: function () {
  41860. return this._globalHue;
  41861. },
  41862. /**
  41863. * Sets the global Hue value.
  41864. * 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).
  41865. */
  41866. set: function (value) {
  41867. this._globalHue = value;
  41868. this._dirty = true;
  41869. },
  41870. enumerable: true,
  41871. configurable: true
  41872. });
  41873. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41874. /**
  41875. * Gets the global Density value.
  41876. * 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.
  41877. * Values less than zero provide a filter of opposite hue.
  41878. */
  41879. get: function () {
  41880. return this._globalDensity;
  41881. },
  41882. /**
  41883. * Sets the global Density value.
  41884. * 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.
  41885. * Values less than zero provide a filter of opposite hue.
  41886. */
  41887. set: function (value) {
  41888. this._globalDensity = value;
  41889. this._dirty = true;
  41890. },
  41891. enumerable: true,
  41892. configurable: true
  41893. });
  41894. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41895. /**
  41896. * Gets the global Saturation value.
  41897. * 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.
  41898. */
  41899. get: function () {
  41900. return this._globalSaturation;
  41901. },
  41902. /**
  41903. * Sets the global Saturation value.
  41904. * 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.
  41905. */
  41906. set: function (value) {
  41907. this._globalSaturation = value;
  41908. this._dirty = true;
  41909. },
  41910. enumerable: true,
  41911. configurable: true
  41912. });
  41913. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41914. /**
  41915. * Gets the global Exposure value.
  41916. * 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.
  41917. */
  41918. get: function () {
  41919. return this._globalExposure;
  41920. },
  41921. /**
  41922. * Sets the global Exposure value.
  41923. * 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.
  41924. */
  41925. set: function (value) {
  41926. this._globalExposure = value;
  41927. this._dirty = true;
  41928. },
  41929. enumerable: true,
  41930. configurable: true
  41931. });
  41932. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41933. /**
  41934. * Gets the highlights Hue value.
  41935. * 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).
  41936. */
  41937. get: function () {
  41938. return this._highlightsHue;
  41939. },
  41940. /**
  41941. * Sets the highlights Hue value.
  41942. * 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).
  41943. */
  41944. set: function (value) {
  41945. this._highlightsHue = value;
  41946. this._dirty = true;
  41947. },
  41948. enumerable: true,
  41949. configurable: true
  41950. });
  41951. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41952. /**
  41953. * Gets the highlights Density value.
  41954. * 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.
  41955. * Values less than zero provide a filter of opposite hue.
  41956. */
  41957. get: function () {
  41958. return this._highlightsDensity;
  41959. },
  41960. /**
  41961. * Sets the highlights Density value.
  41962. * 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.
  41963. * Values less than zero provide a filter of opposite hue.
  41964. */
  41965. set: function (value) {
  41966. this._highlightsDensity = value;
  41967. this._dirty = true;
  41968. },
  41969. enumerable: true,
  41970. configurable: true
  41971. });
  41972. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41973. /**
  41974. * Gets the highlights Saturation value.
  41975. * 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.
  41976. */
  41977. get: function () {
  41978. return this._highlightsSaturation;
  41979. },
  41980. /**
  41981. * Sets the highlights Saturation value.
  41982. * 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.
  41983. */
  41984. set: function (value) {
  41985. this._highlightsSaturation = value;
  41986. this._dirty = true;
  41987. },
  41988. enumerable: true,
  41989. configurable: true
  41990. });
  41991. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41992. /**
  41993. * Gets the highlights Exposure value.
  41994. * 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.
  41995. */
  41996. get: function () {
  41997. return this._highlightsExposure;
  41998. },
  41999. /**
  42000. * Sets the highlights Exposure value.
  42001. * 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.
  42002. */
  42003. set: function (value) {
  42004. this._highlightsExposure = value;
  42005. this._dirty = true;
  42006. },
  42007. enumerable: true,
  42008. configurable: true
  42009. });
  42010. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42011. /**
  42012. * Gets the midtones Hue value.
  42013. * 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).
  42014. */
  42015. get: function () {
  42016. return this._midtonesHue;
  42017. },
  42018. /**
  42019. * Sets the midtones Hue value.
  42020. * 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).
  42021. */
  42022. set: function (value) {
  42023. this._midtonesHue = value;
  42024. this._dirty = true;
  42025. },
  42026. enumerable: true,
  42027. configurable: true
  42028. });
  42029. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42030. /**
  42031. * Gets the midtones Density value.
  42032. * 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.
  42033. * Values less than zero provide a filter of opposite hue.
  42034. */
  42035. get: function () {
  42036. return this._midtonesDensity;
  42037. },
  42038. /**
  42039. * Sets the midtones Density value.
  42040. * 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.
  42041. * Values less than zero provide a filter of opposite hue.
  42042. */
  42043. set: function (value) {
  42044. this._midtonesDensity = value;
  42045. this._dirty = true;
  42046. },
  42047. enumerable: true,
  42048. configurable: true
  42049. });
  42050. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42051. /**
  42052. * Gets the midtones Saturation value.
  42053. * 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.
  42054. */
  42055. get: function () {
  42056. return this._midtonesSaturation;
  42057. },
  42058. /**
  42059. * Sets the midtones Saturation value.
  42060. * 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.
  42061. */
  42062. set: function (value) {
  42063. this._midtonesSaturation = value;
  42064. this._dirty = true;
  42065. },
  42066. enumerable: true,
  42067. configurable: true
  42068. });
  42069. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42070. /**
  42071. * Gets the midtones Exposure value.
  42072. * 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.
  42073. */
  42074. get: function () {
  42075. return this._midtonesExposure;
  42076. },
  42077. /**
  42078. * Sets the midtones Exposure value.
  42079. * 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.
  42080. */
  42081. set: function (value) {
  42082. this._midtonesExposure = value;
  42083. this._dirty = true;
  42084. },
  42085. enumerable: true,
  42086. configurable: true
  42087. });
  42088. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42089. /**
  42090. * Gets the shadows Hue value.
  42091. * 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).
  42092. */
  42093. get: function () {
  42094. return this._shadowsHue;
  42095. },
  42096. /**
  42097. * Sets the shadows Hue value.
  42098. * 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).
  42099. */
  42100. set: function (value) {
  42101. this._shadowsHue = value;
  42102. this._dirty = true;
  42103. },
  42104. enumerable: true,
  42105. configurable: true
  42106. });
  42107. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42108. /**
  42109. * Gets the shadows Density value.
  42110. * 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.
  42111. * Values less than zero provide a filter of opposite hue.
  42112. */
  42113. get: function () {
  42114. return this._shadowsDensity;
  42115. },
  42116. /**
  42117. * Sets the shadows Density value.
  42118. * 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.
  42119. * Values less than zero provide a filter of opposite hue.
  42120. */
  42121. set: function (value) {
  42122. this._shadowsDensity = value;
  42123. this._dirty = true;
  42124. },
  42125. enumerable: true,
  42126. configurable: true
  42127. });
  42128. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42129. /**
  42130. * Gets the shadows Saturation value.
  42131. * 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.
  42132. */
  42133. get: function () {
  42134. return this._shadowsSaturation;
  42135. },
  42136. /**
  42137. * Sets the shadows Saturation value.
  42138. * 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.
  42139. */
  42140. set: function (value) {
  42141. this._shadowsSaturation = value;
  42142. this._dirty = true;
  42143. },
  42144. enumerable: true,
  42145. configurable: true
  42146. });
  42147. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42148. /**
  42149. * Gets the shadows Exposure value.
  42150. * 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.
  42151. */
  42152. get: function () {
  42153. return this._shadowsExposure;
  42154. },
  42155. /**
  42156. * Sets the shadows Exposure value.
  42157. * 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.
  42158. */
  42159. set: function (value) {
  42160. this._shadowsExposure = value;
  42161. this._dirty = true;
  42162. },
  42163. enumerable: true,
  42164. configurable: true
  42165. });
  42166. ColorCurves.prototype.getClassName = function () {
  42167. return "ColorCurves";
  42168. };
  42169. /**
  42170. * Binds the color curves to the shader.
  42171. * @param colorCurves The color curve to bind
  42172. * @param effect The effect to bind to
  42173. */
  42174. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42175. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42176. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42177. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42178. if (colorCurves._dirty) {
  42179. colorCurves._dirty = false;
  42180. // Fill in global info.
  42181. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42182. // Compute highlights info.
  42183. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42184. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42185. // Compute midtones info.
  42186. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42187. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42188. // Compute shadows info.
  42189. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42190. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42191. // Compute deltas (neutral is midtones).
  42192. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42193. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42194. }
  42195. if (effect) {
  42196. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42197. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42198. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42199. }
  42200. };
  42201. /**
  42202. * Prepare the list of uniforms associated with the ColorCurves effects.
  42203. * @param uniformsList The list of uniforms used in the effect
  42204. */
  42205. ColorCurves.PrepareUniforms = function (uniformsList) {
  42206. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42207. };
  42208. /**
  42209. * Returns color grading data based on a hue, density, saturation and exposure value.
  42210. * @param filterHue The hue of the color filter.
  42211. * @param filterDensity The density of the color filter.
  42212. * @param saturation The saturation.
  42213. * @param exposure The exposure.
  42214. * @param result The result data container.
  42215. */
  42216. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42217. if (hue == null) {
  42218. return;
  42219. }
  42220. hue = ColorCurves.clamp(hue, 0, 360);
  42221. density = ColorCurves.clamp(density, -100, 100);
  42222. saturation = ColorCurves.clamp(saturation, -100, 100);
  42223. exposure = ColorCurves.clamp(exposure, -100, 100);
  42224. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42225. // so that the maximum filter density is only 50% control. This provides fine control
  42226. // for small values and reasonable range.
  42227. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42228. density *= 0.5;
  42229. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42230. if (density < 0) {
  42231. density *= -1;
  42232. hue = (hue + 180) % 360;
  42233. }
  42234. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42235. result.scaleToRef(2, result);
  42236. result.a = 1 + 0.01 * saturation;
  42237. };
  42238. /**
  42239. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42240. * @param value The input slider value in range [-100,100].
  42241. * @returns Adjusted value.
  42242. */
  42243. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42244. value /= 100;
  42245. var x = Math.abs(value);
  42246. x = Math.pow(x, 2);
  42247. if (value < 0) {
  42248. x *= -1;
  42249. }
  42250. x *= 100;
  42251. return x;
  42252. };
  42253. /**
  42254. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42255. * @param hue The hue (H) input.
  42256. * @param saturation The saturation (S) input.
  42257. * @param brightness The brightness (B) input.
  42258. * @result An RGBA color represented as Vector4.
  42259. */
  42260. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42261. var h = ColorCurves.clamp(hue, 0, 360);
  42262. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42263. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42264. if (s === 0) {
  42265. result.r = v;
  42266. result.g = v;
  42267. result.b = v;
  42268. }
  42269. else {
  42270. // sector 0 to 5
  42271. h /= 60;
  42272. var i = Math.floor(h);
  42273. // fractional part of h
  42274. var f = h - i;
  42275. var p = v * (1 - s);
  42276. var q = v * (1 - s * f);
  42277. var t = v * (1 - s * (1 - f));
  42278. switch (i) {
  42279. case 0:
  42280. result.r = v;
  42281. result.g = t;
  42282. result.b = p;
  42283. break;
  42284. case 1:
  42285. result.r = q;
  42286. result.g = v;
  42287. result.b = p;
  42288. break;
  42289. case 2:
  42290. result.r = p;
  42291. result.g = v;
  42292. result.b = t;
  42293. break;
  42294. case 3:
  42295. result.r = p;
  42296. result.g = q;
  42297. result.b = v;
  42298. break;
  42299. case 4:
  42300. result.r = t;
  42301. result.g = p;
  42302. result.b = v;
  42303. break;
  42304. default: // case 5:
  42305. result.r = v;
  42306. result.g = p;
  42307. result.b = q;
  42308. break;
  42309. }
  42310. }
  42311. result.a = 1;
  42312. };
  42313. /**
  42314. * Returns a value clamped between min and max
  42315. * @param value The value to clamp
  42316. * @param min The minimum of value
  42317. * @param max The maximum of value
  42318. * @returns The clamped value.
  42319. */
  42320. ColorCurves.clamp = function (value, min, max) {
  42321. return Math.min(Math.max(value, min), max);
  42322. };
  42323. /**
  42324. * Clones the current color curve instance.
  42325. * @return The cloned curves
  42326. */
  42327. ColorCurves.prototype.clone = function () {
  42328. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42329. };
  42330. /**
  42331. * Serializes the current color curve instance to a json representation.
  42332. * @return a JSON representation
  42333. */
  42334. ColorCurves.prototype.serialize = function () {
  42335. return BABYLON.SerializationHelper.Serialize(this);
  42336. };
  42337. /**
  42338. * Parses the color curve from a json representation.
  42339. * @param source the JSON source to parse
  42340. * @return The parsed curves
  42341. */
  42342. ColorCurves.Parse = function (source) {
  42343. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42344. };
  42345. __decorate([
  42346. BABYLON.serialize()
  42347. ], ColorCurves.prototype, "_globalHue", void 0);
  42348. __decorate([
  42349. BABYLON.serialize()
  42350. ], ColorCurves.prototype, "_globalDensity", void 0);
  42351. __decorate([
  42352. BABYLON.serialize()
  42353. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42354. __decorate([
  42355. BABYLON.serialize()
  42356. ], ColorCurves.prototype, "_globalExposure", void 0);
  42357. __decorate([
  42358. BABYLON.serialize()
  42359. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42360. __decorate([
  42361. BABYLON.serialize()
  42362. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42363. __decorate([
  42364. BABYLON.serialize()
  42365. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42366. __decorate([
  42367. BABYLON.serialize()
  42368. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42369. __decorate([
  42370. BABYLON.serialize()
  42371. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42372. __decorate([
  42373. BABYLON.serialize()
  42374. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42375. __decorate([
  42376. BABYLON.serialize()
  42377. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42378. __decorate([
  42379. BABYLON.serialize()
  42380. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42381. return ColorCurves;
  42382. }());
  42383. BABYLON.ColorCurves = ColorCurves;
  42384. })(BABYLON || (BABYLON = {}));
  42385. //# sourceMappingURL=babylon.colorCurves.js.map
  42386. //# sourceMappingURL=babylon.behavior.js.map
  42387. var BABYLON;
  42388. (function (BABYLON) {
  42389. /**
  42390. * "Static Class" containing the most commonly used helper while dealing with material for
  42391. * rendering purpose.
  42392. *
  42393. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42394. *
  42395. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42396. */
  42397. var MaterialHelper = /** @class */ (function () {
  42398. function MaterialHelper() {
  42399. }
  42400. /**
  42401. * Bind the current view position to an effect.
  42402. * @param effect The effect to be bound
  42403. * @param scene The scene the eyes position is used from
  42404. */
  42405. MaterialHelper.BindEyePosition = function (effect, scene) {
  42406. if (scene._forcedViewPosition) {
  42407. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42408. return;
  42409. }
  42410. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42411. };
  42412. /**
  42413. * Helps preparing the defines values about the UVs in used in the effect.
  42414. * UVs are shared as much as we can accross chanels in the shaders.
  42415. * @param texture The texture we are preparing the UVs for
  42416. * @param defines The defines to update
  42417. * @param key The chanel key "diffuse", "specular"... used in the shader
  42418. */
  42419. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42420. defines._needUVs = true;
  42421. defines[key] = true;
  42422. if (texture.getTextureMatrix().isIdentity(true)) {
  42423. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42424. if (texture.coordinatesIndex === 0) {
  42425. defines["MAINUV1"] = true;
  42426. }
  42427. else {
  42428. defines["MAINUV2"] = true;
  42429. }
  42430. }
  42431. else {
  42432. defines[key + "DIRECTUV"] = 0;
  42433. }
  42434. };
  42435. /**
  42436. * Binds a texture matrix value to its corrsponding uniform
  42437. * @param texture The texture to bind the matrix for
  42438. * @param uniformBuffer The uniform buffer receivin the data
  42439. * @param key The chanel key "diffuse", "specular"... used in the shader
  42440. */
  42441. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42442. var matrix = texture.getTextureMatrix();
  42443. if (!matrix.isIdentity(true)) {
  42444. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42445. }
  42446. };
  42447. /**
  42448. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42449. * @param mesh defines the current mesh
  42450. * @param scene defines the current scene
  42451. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42452. * @param pointsCloud defines if point cloud rendering has to be turned on
  42453. * @param fogEnabled defines if fog has to be turned on
  42454. * @param alphaTest defines if alpha testing has to be turned on
  42455. * @param defines defines the current list of defines
  42456. */
  42457. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42458. if (defines._areMiscDirty) {
  42459. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42460. defines["POINTSIZE"] = pointsCloud;
  42461. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42462. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42463. defines["ALPHATEST"] = alphaTest;
  42464. }
  42465. };
  42466. /**
  42467. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42468. * @param scene defines the current scene
  42469. * @param engine defines the current engine
  42470. * @param defines specifies the list of active defines
  42471. * @param useInstances defines if instances have to be turned on
  42472. * @param useClipPlane defines if clip plane have to be turned on
  42473. */
  42474. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42475. if (useClipPlane === void 0) { useClipPlane = null; }
  42476. var changed = false;
  42477. if (useClipPlane == null) {
  42478. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42479. }
  42480. if (defines["CLIPPLANE"] !== useClipPlane) {
  42481. defines["CLIPPLANE"] = useClipPlane;
  42482. changed = true;
  42483. }
  42484. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42485. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42486. changed = true;
  42487. }
  42488. if (defines["INSTANCES"] !== useInstances) {
  42489. defines["INSTANCES"] = useInstances;
  42490. changed = true;
  42491. }
  42492. if (changed) {
  42493. defines.markAsUnprocessed();
  42494. }
  42495. };
  42496. /**
  42497. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42498. * @param mesh The mesh containing the geometry data we will draw
  42499. * @param defines The defines to update
  42500. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42501. * @param useBones Precise whether bones should be used or not (override mesh info)
  42502. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42503. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42504. * @returns false if defines are considered not dirty and have not been checked
  42505. */
  42506. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42507. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42508. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42509. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42510. return false;
  42511. }
  42512. defines._normals = defines._needNormals;
  42513. defines._uvs = defines._needUVs;
  42514. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42515. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42516. defines["TANGENT"] = true;
  42517. }
  42518. if (defines._needUVs) {
  42519. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42520. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42521. }
  42522. else {
  42523. defines["UV1"] = false;
  42524. defines["UV2"] = false;
  42525. }
  42526. if (useVertexColor) {
  42527. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42528. defines["VERTEXCOLOR"] = hasVertexColors;
  42529. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42530. }
  42531. if (useBones) {
  42532. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42533. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42534. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42535. }
  42536. else {
  42537. defines["NUM_BONE_INFLUENCERS"] = 0;
  42538. defines["BonesPerMesh"] = 0;
  42539. }
  42540. }
  42541. if (useMorphTargets) {
  42542. var manager = mesh.morphTargetManager;
  42543. if (manager) {
  42544. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42545. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42546. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42547. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42548. }
  42549. else {
  42550. defines["MORPHTARGETS_TANGENT"] = false;
  42551. defines["MORPHTARGETS_NORMAL"] = false;
  42552. defines["MORPHTARGETS"] = false;
  42553. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42554. }
  42555. }
  42556. return true;
  42557. };
  42558. /**
  42559. * Prepares the defines related to the light information passed in parameter
  42560. * @param scene The scene we are intending to draw
  42561. * @param mesh The mesh the effect is compiling for
  42562. * @param defines The defines to update
  42563. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42564. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42565. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42566. * @returns true if normals will be required for the rest of the effect
  42567. */
  42568. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42569. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42570. if (disableLighting === void 0) { disableLighting = false; }
  42571. if (!defines._areLightsDirty) {
  42572. return defines._needNormals;
  42573. }
  42574. var lightIndex = 0;
  42575. var needNormals = false;
  42576. var needRebuild = false;
  42577. var lightmapMode = false;
  42578. var shadowEnabled = false;
  42579. var specularEnabled = false;
  42580. if (scene.lightsEnabled && !disableLighting) {
  42581. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42582. var light = _a[_i];
  42583. needNormals = true;
  42584. if (defines["LIGHT" + lightIndex] === undefined) {
  42585. needRebuild = true;
  42586. }
  42587. defines["LIGHT" + lightIndex] = true;
  42588. defines["SPOTLIGHT" + lightIndex] = false;
  42589. defines["HEMILIGHT" + lightIndex] = false;
  42590. defines["POINTLIGHT" + lightIndex] = false;
  42591. defines["DIRLIGHT" + lightIndex] = false;
  42592. var type;
  42593. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42594. type = "SPOTLIGHT" + lightIndex;
  42595. var spotLight = light;
  42596. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42597. }
  42598. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42599. type = "HEMILIGHT" + lightIndex;
  42600. }
  42601. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42602. type = "POINTLIGHT" + lightIndex;
  42603. }
  42604. else {
  42605. type = "DIRLIGHT" + lightIndex;
  42606. }
  42607. defines[type] = true;
  42608. // Specular
  42609. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42610. specularEnabled = true;
  42611. }
  42612. // Shadows
  42613. defines["SHADOW" + lightIndex] = false;
  42614. defines["SHADOWPCF" + lightIndex] = false;
  42615. defines["SHADOWPCSS" + lightIndex] = false;
  42616. defines["SHADOWPOISSON" + lightIndex] = false;
  42617. defines["SHADOWESM" + lightIndex] = false;
  42618. defines["SHADOWCUBE" + lightIndex] = false;
  42619. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42620. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42621. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42622. var shadowGenerator = light.getShadowGenerator();
  42623. if (shadowGenerator) {
  42624. shadowEnabled = true;
  42625. shadowGenerator.prepareDefines(defines, lightIndex);
  42626. }
  42627. }
  42628. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42629. lightmapMode = true;
  42630. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42631. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42632. }
  42633. else {
  42634. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42635. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42636. }
  42637. lightIndex++;
  42638. if (lightIndex === maxSimultaneousLights)
  42639. break;
  42640. }
  42641. }
  42642. defines["SPECULARTERM"] = specularEnabled;
  42643. defines["SHADOWS"] = shadowEnabled;
  42644. // Resetting all other lights if any
  42645. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42646. if (defines["LIGHT" + index] !== undefined) {
  42647. defines["LIGHT" + index] = false;
  42648. defines["HEMILIGHT" + lightIndex] = false;
  42649. defines["POINTLIGHT" + lightIndex] = false;
  42650. defines["DIRLIGHT" + lightIndex] = false;
  42651. defines["SPOTLIGHT" + lightIndex] = false;
  42652. defines["SHADOW" + lightIndex] = false;
  42653. }
  42654. }
  42655. var caps = scene.getEngine().getCaps();
  42656. if (defines["SHADOWFLOAT"] === undefined) {
  42657. needRebuild = true;
  42658. }
  42659. defines["SHADOWFLOAT"] = shadowEnabled &&
  42660. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42661. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42662. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42663. if (needRebuild) {
  42664. defines.rebuild();
  42665. }
  42666. return needNormals;
  42667. };
  42668. /**
  42669. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42670. * that won t be acctive due to defines being turned off.
  42671. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42672. * @param samplersList The samplers list
  42673. * @param defines The defines helping in the list generation
  42674. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42675. */
  42676. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42677. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42678. var uniformsList;
  42679. var uniformBuffersList = null;
  42680. if (uniformsListOrOptions.uniformsNames) {
  42681. var options = uniformsListOrOptions;
  42682. uniformsList = options.uniformsNames;
  42683. uniformBuffersList = options.uniformBuffersNames;
  42684. samplersList = options.samplers;
  42685. defines = options.defines;
  42686. maxSimultaneousLights = options.maxSimultaneousLights;
  42687. }
  42688. else {
  42689. uniformsList = uniformsListOrOptions;
  42690. if (!samplersList) {
  42691. samplersList = [];
  42692. }
  42693. }
  42694. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42695. if (!defines["LIGHT" + lightIndex]) {
  42696. break;
  42697. }
  42698. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42699. if (uniformBuffersList) {
  42700. uniformBuffersList.push("Light" + lightIndex);
  42701. }
  42702. samplersList.push("shadowSampler" + lightIndex);
  42703. samplersList.push("depthSampler" + lightIndex);
  42704. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42705. samplersList.push("projectionLightSampler" + lightIndex);
  42706. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42707. }
  42708. }
  42709. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42710. uniformsList.push("morphTargetInfluences");
  42711. }
  42712. };
  42713. /**
  42714. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42715. * @param defines The defines to update while falling back
  42716. * @param fallbacks The authorized effect fallbacks
  42717. * @param maxSimultaneousLights The maximum number of lights allowed
  42718. * @param rank the current rank of the Effect
  42719. * @returns The newly affected rank
  42720. */
  42721. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42722. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42723. if (rank === void 0) { rank = 0; }
  42724. var lightFallbackRank = 0;
  42725. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42726. if (!defines["LIGHT" + lightIndex]) {
  42727. break;
  42728. }
  42729. if (lightIndex > 0) {
  42730. lightFallbackRank = rank + lightIndex;
  42731. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42732. }
  42733. if (!defines["SHADOWS"]) {
  42734. if (defines["SHADOW" + lightIndex]) {
  42735. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42736. }
  42737. if (defines["SHADOWPCF" + lightIndex]) {
  42738. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42739. }
  42740. if (defines["SHADOWPCSS" + lightIndex]) {
  42741. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42742. }
  42743. if (defines["SHADOWPOISSON" + lightIndex]) {
  42744. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42745. }
  42746. if (defines["SHADOWESM" + lightIndex]) {
  42747. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42748. }
  42749. }
  42750. }
  42751. return lightFallbackRank++;
  42752. };
  42753. /**
  42754. * Prepares the list of attributes required for morph targets according to the effect defines.
  42755. * @param attribs The current list of supported attribs
  42756. * @param mesh The mesh to prepare the morph targets attributes for
  42757. * @param defines The current Defines of the effect
  42758. */
  42759. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42760. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42761. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42762. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42763. var manager = mesh.morphTargetManager;
  42764. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42765. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42766. for (var index = 0; index < influencers; index++) {
  42767. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42768. if (normal) {
  42769. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42770. }
  42771. if (tangent) {
  42772. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42773. }
  42774. if (attribs.length > maxAttributesCount) {
  42775. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42776. }
  42777. }
  42778. }
  42779. };
  42780. /**
  42781. * Prepares the list of attributes required for bones according to the effect defines.
  42782. * @param attribs The current list of supported attribs
  42783. * @param mesh The mesh to prepare the bones attributes for
  42784. * @param defines The current Defines of the effect
  42785. * @param fallbacks The current efffect fallback strategy
  42786. */
  42787. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42788. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42789. fallbacks.addCPUSkinningFallback(0, mesh);
  42790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42792. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42795. }
  42796. }
  42797. };
  42798. /**
  42799. * Prepares the list of attributes required for instances according to the effect defines.
  42800. * @param attribs The current list of supported attribs
  42801. * @param defines The current Defines of the effect
  42802. */
  42803. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42804. if (defines["INSTANCES"]) {
  42805. attribs.push("world0");
  42806. attribs.push("world1");
  42807. attribs.push("world2");
  42808. attribs.push("world3");
  42809. }
  42810. };
  42811. /**
  42812. * Binds the light shadow information to the effect for the given mesh.
  42813. * @param light The light containing the generator
  42814. * @param scene The scene the lights belongs to
  42815. * @param mesh The mesh we are binding the information to render
  42816. * @param lightIndex The light index in the effect used to render the mesh
  42817. * @param effect The effect we are binding the data to
  42818. */
  42819. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42820. if (light.shadowEnabled && mesh.receiveShadows) {
  42821. var shadowGenerator = light.getShadowGenerator();
  42822. if (shadowGenerator) {
  42823. shadowGenerator.bindShadowLight(lightIndex, effect);
  42824. }
  42825. }
  42826. };
  42827. /**
  42828. * Binds the light information to the effect.
  42829. * @param light The light containing the generator
  42830. * @param effect The effect we are binding the data to
  42831. * @param lightIndex The light index in the effect used to render
  42832. */
  42833. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42834. light.transferToEffect(effect, lightIndex + "");
  42835. };
  42836. /**
  42837. * Binds the lights information from the scene to the effect for the given mesh.
  42838. * @param scene The scene the lights belongs to
  42839. * @param mesh The mesh we are binding the information to render
  42840. * @param effect The effect we are binding the data to
  42841. * @param defines The generated defines for the effect
  42842. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42843. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42844. */
  42845. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42846. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42847. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42848. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42849. for (var i = 0; i < len; i++) {
  42850. var light = mesh._lightSources[i];
  42851. var iAsString = i.toString();
  42852. var scaledIntensity = light.getScaledIntensity();
  42853. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42854. MaterialHelper.BindLightProperties(light, effect, i);
  42855. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42856. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42857. if (defines["SPECULARTERM"]) {
  42858. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42859. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42860. }
  42861. // Shadows
  42862. if (scene.shadowsEnabled) {
  42863. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42864. }
  42865. light._uniformBuffer.update();
  42866. }
  42867. };
  42868. /**
  42869. * Binds the fog information from the scene to the effect for the given mesh.
  42870. * @param scene The scene the lights belongs to
  42871. * @param mesh The mesh we are binding the information to render
  42872. * @param effect The effect we are binding the data to
  42873. */
  42874. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42875. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42876. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42877. effect.setColor3("vFogColor", scene.fogColor);
  42878. }
  42879. };
  42880. /**
  42881. * Binds the bones information from the mesh to the effect.
  42882. * @param mesh The mesh we are binding the information to render
  42883. * @param effect The effect we are binding the data to
  42884. */
  42885. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42886. if (!effect || !mesh) {
  42887. return;
  42888. }
  42889. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42890. mesh.computeBonesUsingShaders = false;
  42891. }
  42892. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42893. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42894. if (matrices) {
  42895. effect.setMatrices("mBones", matrices);
  42896. }
  42897. }
  42898. };
  42899. /**
  42900. * Binds the morph targets information from the mesh to the effect.
  42901. * @param abstractMesh The mesh we are binding the information to render
  42902. * @param effect The effect we are binding the data to
  42903. */
  42904. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42905. var manager = abstractMesh.morphTargetManager;
  42906. if (!abstractMesh || !manager) {
  42907. return;
  42908. }
  42909. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42910. };
  42911. /**
  42912. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42913. * @param defines The generated defines used in the effect
  42914. * @param effect The effect we are binding the data to
  42915. * @param scene The scene we are willing to render with logarithmic scale for
  42916. */
  42917. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42918. if (defines["LOGARITHMICDEPTH"]) {
  42919. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42920. }
  42921. };
  42922. /**
  42923. * Binds the clip plane information from the scene to the effect.
  42924. * @param scene The scene the clip plane information are extracted from
  42925. * @param effect The effect we are binding the data to
  42926. */
  42927. MaterialHelper.BindClipPlane = function (effect, scene) {
  42928. if (scene.clipPlane) {
  42929. var clipPlane = scene.clipPlane;
  42930. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42931. }
  42932. };
  42933. return MaterialHelper;
  42934. }());
  42935. BABYLON.MaterialHelper = MaterialHelper;
  42936. })(BABYLON || (BABYLON = {}));
  42937. //# sourceMappingURL=babylon.materialHelper.js.map
  42938. var BABYLON;
  42939. (function (BABYLON) {
  42940. var PushMaterial = /** @class */ (function (_super) {
  42941. __extends(PushMaterial, _super);
  42942. function PushMaterial(name, scene) {
  42943. var _this = _super.call(this, name, scene) || this;
  42944. _this._normalMatrix = new BABYLON.Matrix();
  42945. _this.storeEffectOnSubMeshes = true;
  42946. return _this;
  42947. }
  42948. PushMaterial.prototype.getEffect = function () {
  42949. return this._activeEffect;
  42950. };
  42951. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42952. if (!mesh) {
  42953. return false;
  42954. }
  42955. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42956. return true;
  42957. }
  42958. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42959. };
  42960. /**
  42961. * Binds the given world matrix to the active effect
  42962. *
  42963. * @param world the matrix to bind
  42964. */
  42965. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42966. this._activeEffect.setMatrix("world", world);
  42967. };
  42968. /**
  42969. * Binds the given normal matrix to the active effect
  42970. *
  42971. * @param normalMatrix the matrix to bind
  42972. */
  42973. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42974. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42975. };
  42976. PushMaterial.prototype.bind = function (world, mesh) {
  42977. if (!mesh) {
  42978. return;
  42979. }
  42980. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42981. };
  42982. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42983. if (effect === void 0) { effect = null; }
  42984. _super.prototype._afterBind.call(this, mesh);
  42985. this.getScene()._cachedEffect = effect;
  42986. };
  42987. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42988. if (visibility === void 0) { visibility = 1; }
  42989. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42990. };
  42991. return PushMaterial;
  42992. }(BABYLON.Material));
  42993. BABYLON.PushMaterial = PushMaterial;
  42994. })(BABYLON || (BABYLON = {}));
  42995. //# sourceMappingURL=babylon.pushMaterial.js.map
  42996. var BABYLON;
  42997. (function (BABYLON) {
  42998. /** @hidden */
  42999. var StandardMaterialDefines = /** @class */ (function (_super) {
  43000. __extends(StandardMaterialDefines, _super);
  43001. function StandardMaterialDefines() {
  43002. var _this = _super.call(this) || this;
  43003. _this.MAINUV1 = false;
  43004. _this.MAINUV2 = false;
  43005. _this.DIFFUSE = false;
  43006. _this.DIFFUSEDIRECTUV = 0;
  43007. _this.AMBIENT = false;
  43008. _this.AMBIENTDIRECTUV = 0;
  43009. _this.OPACITY = false;
  43010. _this.OPACITYDIRECTUV = 0;
  43011. _this.OPACITYRGB = false;
  43012. _this.REFLECTION = false;
  43013. _this.EMISSIVE = false;
  43014. _this.EMISSIVEDIRECTUV = 0;
  43015. _this.SPECULAR = false;
  43016. _this.SPECULARDIRECTUV = 0;
  43017. _this.BUMP = false;
  43018. _this.BUMPDIRECTUV = 0;
  43019. _this.PARALLAX = false;
  43020. _this.PARALLAXOCCLUSION = false;
  43021. _this.SPECULAROVERALPHA = false;
  43022. _this.CLIPPLANE = false;
  43023. _this.ALPHATEST = false;
  43024. _this.DEPTHPREPASS = false;
  43025. _this.ALPHAFROMDIFFUSE = false;
  43026. _this.POINTSIZE = false;
  43027. _this.FOG = false;
  43028. _this.SPECULARTERM = false;
  43029. _this.DIFFUSEFRESNEL = false;
  43030. _this.OPACITYFRESNEL = false;
  43031. _this.REFLECTIONFRESNEL = false;
  43032. _this.REFRACTIONFRESNEL = false;
  43033. _this.EMISSIVEFRESNEL = false;
  43034. _this.FRESNEL = false;
  43035. _this.NORMAL = false;
  43036. _this.UV1 = false;
  43037. _this.UV2 = false;
  43038. _this.VERTEXCOLOR = false;
  43039. _this.VERTEXALPHA = false;
  43040. _this.NUM_BONE_INFLUENCERS = 0;
  43041. _this.BonesPerMesh = 0;
  43042. _this.INSTANCES = false;
  43043. _this.GLOSSINESS = false;
  43044. _this.ROUGHNESS = false;
  43045. _this.EMISSIVEASILLUMINATION = false;
  43046. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43047. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43048. _this.LIGHTMAP = false;
  43049. _this.LIGHTMAPDIRECTUV = 0;
  43050. _this.OBJECTSPACE_NORMALMAP = false;
  43051. _this.USELIGHTMAPASSHADOWMAP = false;
  43052. _this.REFLECTIONMAP_3D = false;
  43053. _this.REFLECTIONMAP_SPHERICAL = false;
  43054. _this.REFLECTIONMAP_PLANAR = false;
  43055. _this.REFLECTIONMAP_CUBIC = false;
  43056. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43057. _this.REFLECTIONMAP_PROJECTION = false;
  43058. _this.REFLECTIONMAP_SKYBOX = false;
  43059. _this.REFLECTIONMAP_EXPLICIT = false;
  43060. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43061. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43062. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43063. _this.INVERTCUBICMAP = false;
  43064. _this.LOGARITHMICDEPTH = false;
  43065. _this.REFRACTION = false;
  43066. _this.REFRACTIONMAP_3D = false;
  43067. _this.REFLECTIONOVERALPHA = false;
  43068. _this.TWOSIDEDLIGHTING = false;
  43069. _this.SHADOWFLOAT = false;
  43070. _this.MORPHTARGETS = false;
  43071. _this.MORPHTARGETS_NORMAL = false;
  43072. _this.MORPHTARGETS_TANGENT = false;
  43073. _this.NUM_MORPH_INFLUENCERS = 0;
  43074. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43075. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43076. _this.IMAGEPROCESSING = false;
  43077. _this.VIGNETTE = false;
  43078. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43079. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43080. _this.TONEMAPPING = false;
  43081. _this.CONTRAST = false;
  43082. _this.COLORCURVES = false;
  43083. _this.COLORGRADING = false;
  43084. _this.COLORGRADING3D = false;
  43085. _this.SAMPLER3DGREENDEPTH = false;
  43086. _this.SAMPLER3DBGRMAP = false;
  43087. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43088. /**
  43089. * If the reflection texture on this material is in linear color space
  43090. * @hidden
  43091. */
  43092. _this.IS_REFLECTION_LINEAR = false;
  43093. /**
  43094. * If the refraction texture on this material is in linear color space
  43095. * @hidden
  43096. */
  43097. _this.IS_REFRACTION_LINEAR = false;
  43098. _this.EXPOSURE = false;
  43099. _this.rebuild();
  43100. return _this;
  43101. }
  43102. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43103. var modes = [
  43104. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43105. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43106. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43107. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43108. ];
  43109. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43110. var mode = modes_1[_i];
  43111. this[mode] = (mode === modeToEnable);
  43112. }
  43113. };
  43114. return StandardMaterialDefines;
  43115. }(BABYLON.MaterialDefines));
  43116. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43117. var StandardMaterial = /** @class */ (function (_super) {
  43118. __extends(StandardMaterial, _super);
  43119. function StandardMaterial(name, scene) {
  43120. var _this = _super.call(this, name, scene) || this;
  43121. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43122. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43123. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43124. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43125. _this.specularPower = 64;
  43126. _this._useAlphaFromDiffuseTexture = false;
  43127. _this._useEmissiveAsIllumination = false;
  43128. _this._linkEmissiveWithDiffuse = false;
  43129. _this._useSpecularOverAlpha = false;
  43130. _this._useReflectionOverAlpha = false;
  43131. _this._disableLighting = false;
  43132. _this._useObjectSpaceNormalMap = false;
  43133. _this._useParallax = false;
  43134. _this._useParallaxOcclusion = false;
  43135. _this.parallaxScaleBias = 0.05;
  43136. _this._roughness = 0;
  43137. _this.indexOfRefraction = 0.98;
  43138. _this.invertRefractionY = true;
  43139. /**
  43140. * Defines the alpha limits in alpha test mode
  43141. */
  43142. _this.alphaCutOff = 0.4;
  43143. _this._useLightmapAsShadowmap = false;
  43144. _this._useReflectionFresnelFromSpecular = false;
  43145. _this._useGlossinessFromSpecularMapAlpha = false;
  43146. _this._maxSimultaneousLights = 4;
  43147. /**
  43148. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43149. */
  43150. _this._invertNormalMapX = false;
  43151. /**
  43152. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43153. */
  43154. _this._invertNormalMapY = false;
  43155. /**
  43156. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43157. */
  43158. _this._twoSidedLighting = false;
  43159. _this._renderTargets = new BABYLON.SmartArray(16);
  43160. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43161. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43162. // Setup the default processing configuration to the scene.
  43163. _this._attachImageProcessingConfiguration(null);
  43164. _this.getRenderTargetTextures = function () {
  43165. _this._renderTargets.reset();
  43166. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43167. _this._renderTargets.push(_this._reflectionTexture);
  43168. }
  43169. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43170. _this._renderTargets.push(_this._refractionTexture);
  43171. }
  43172. return _this._renderTargets;
  43173. };
  43174. return _this;
  43175. }
  43176. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43177. /**
  43178. * Gets the image processing configuration used either in this material.
  43179. */
  43180. get: function () {
  43181. return this._imageProcessingConfiguration;
  43182. },
  43183. /**
  43184. * Sets the Default image processing configuration used either in the this material.
  43185. *
  43186. * If sets to null, the scene one is in use.
  43187. */
  43188. set: function (value) {
  43189. this._attachImageProcessingConfiguration(value);
  43190. // Ensure the effect will be rebuilt.
  43191. this._markAllSubMeshesAsTexturesDirty();
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. /**
  43197. * Attaches a new image processing configuration to the Standard Material.
  43198. * @param configuration
  43199. */
  43200. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43201. var _this = this;
  43202. if (configuration === this._imageProcessingConfiguration) {
  43203. return;
  43204. }
  43205. // Detaches observer.
  43206. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43207. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43208. }
  43209. // Pick the scene configuration if needed.
  43210. if (!configuration) {
  43211. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43212. }
  43213. else {
  43214. this._imageProcessingConfiguration = configuration;
  43215. }
  43216. // Attaches observer.
  43217. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43218. _this._markAllSubMeshesAsImageProcessingDirty();
  43219. });
  43220. };
  43221. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43222. /**
  43223. * Gets wether the color curves effect is enabled.
  43224. */
  43225. get: function () {
  43226. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43227. },
  43228. /**
  43229. * Sets wether the color curves effect is enabled.
  43230. */
  43231. set: function (value) {
  43232. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43233. },
  43234. enumerable: true,
  43235. configurable: true
  43236. });
  43237. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43238. /**
  43239. * Gets wether the color grading effect is enabled.
  43240. */
  43241. get: function () {
  43242. return this.imageProcessingConfiguration.colorGradingEnabled;
  43243. },
  43244. /**
  43245. * Gets wether the color grading effect is enabled.
  43246. */
  43247. set: function (value) {
  43248. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43249. },
  43250. enumerable: true,
  43251. configurable: true
  43252. });
  43253. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43254. /**
  43255. * Gets wether tonemapping is enabled or not.
  43256. */
  43257. get: function () {
  43258. return this._imageProcessingConfiguration.toneMappingEnabled;
  43259. },
  43260. /**
  43261. * Sets wether tonemapping is enabled or not
  43262. */
  43263. set: function (value) {
  43264. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43265. },
  43266. enumerable: true,
  43267. configurable: true
  43268. });
  43269. ;
  43270. ;
  43271. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43272. /**
  43273. * The camera exposure used on this material.
  43274. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43275. * This corresponds to a photographic exposure.
  43276. */
  43277. get: function () {
  43278. return this._imageProcessingConfiguration.exposure;
  43279. },
  43280. /**
  43281. * The camera exposure used on this material.
  43282. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43283. * This corresponds to a photographic exposure.
  43284. */
  43285. set: function (value) {
  43286. this._imageProcessingConfiguration.exposure = value;
  43287. },
  43288. enumerable: true,
  43289. configurable: true
  43290. });
  43291. ;
  43292. ;
  43293. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43294. /**
  43295. * Gets The camera contrast used on this material.
  43296. */
  43297. get: function () {
  43298. return this._imageProcessingConfiguration.contrast;
  43299. },
  43300. /**
  43301. * Sets The camera contrast used on this material.
  43302. */
  43303. set: function (value) {
  43304. this._imageProcessingConfiguration.contrast = value;
  43305. },
  43306. enumerable: true,
  43307. configurable: true
  43308. });
  43309. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43310. /**
  43311. * Gets the Color Grading 2D Lookup Texture.
  43312. */
  43313. get: function () {
  43314. return this._imageProcessingConfiguration.colorGradingTexture;
  43315. },
  43316. /**
  43317. * Sets the Color Grading 2D Lookup Texture.
  43318. */
  43319. set: function (value) {
  43320. this._imageProcessingConfiguration.colorGradingTexture = value;
  43321. },
  43322. enumerable: true,
  43323. configurable: true
  43324. });
  43325. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43326. /**
  43327. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43328. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43329. * 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;
  43330. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43331. */
  43332. get: function () {
  43333. return this._imageProcessingConfiguration.colorCurves;
  43334. },
  43335. /**
  43336. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43337. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43338. * 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;
  43339. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43340. */
  43341. set: function (value) {
  43342. this._imageProcessingConfiguration.colorCurves = value;
  43343. },
  43344. enumerable: true,
  43345. configurable: true
  43346. });
  43347. StandardMaterial.prototype.getClassName = function () {
  43348. return "StandardMaterial";
  43349. };
  43350. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43351. get: function () {
  43352. return this._useLogarithmicDepth;
  43353. },
  43354. set: function (value) {
  43355. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43356. this._markAllSubMeshesAsMiscDirty();
  43357. },
  43358. enumerable: true,
  43359. configurable: true
  43360. });
  43361. StandardMaterial.prototype.needAlphaBlending = function () {
  43362. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43363. };
  43364. StandardMaterial.prototype.needAlphaTesting = function () {
  43365. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43366. };
  43367. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43368. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43369. };
  43370. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43371. return this._diffuseTexture;
  43372. };
  43373. /**
  43374. * Child classes can use it to update shaders
  43375. */
  43376. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43377. if (useInstances === void 0) { useInstances = false; }
  43378. if (subMesh.effect && this.isFrozen) {
  43379. if (this._wasPreviouslyReady && subMesh.effect) {
  43380. return true;
  43381. }
  43382. }
  43383. if (!subMesh._materialDefines) {
  43384. subMesh._materialDefines = new StandardMaterialDefines();
  43385. }
  43386. var scene = this.getScene();
  43387. var defines = subMesh._materialDefines;
  43388. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43389. if (defines._renderId === scene.getRenderId()) {
  43390. return true;
  43391. }
  43392. }
  43393. var engine = scene.getEngine();
  43394. // Lights
  43395. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43396. // Textures
  43397. if (defines._areTexturesDirty) {
  43398. defines._needUVs = false;
  43399. defines.MAINUV1 = false;
  43400. defines.MAINUV2 = false;
  43401. if (scene.texturesEnabled) {
  43402. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43403. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43404. return false;
  43405. }
  43406. else {
  43407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43408. }
  43409. }
  43410. else {
  43411. defines.DIFFUSE = false;
  43412. }
  43413. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43414. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43415. return false;
  43416. }
  43417. else {
  43418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43419. }
  43420. }
  43421. else {
  43422. defines.AMBIENT = false;
  43423. }
  43424. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43425. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43426. return false;
  43427. }
  43428. else {
  43429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43430. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43431. }
  43432. }
  43433. else {
  43434. defines.OPACITY = false;
  43435. }
  43436. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43437. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43438. return false;
  43439. }
  43440. else {
  43441. defines._needNormals = true;
  43442. defines.REFLECTION = true;
  43443. defines.ROUGHNESS = (this._roughness > 0);
  43444. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43445. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43446. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43447. switch (this._reflectionTexture.coordinatesMode) {
  43448. case BABYLON.Texture.EXPLICIT_MODE:
  43449. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43450. break;
  43451. case BABYLON.Texture.PLANAR_MODE:
  43452. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43453. break;
  43454. case BABYLON.Texture.PROJECTION_MODE:
  43455. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43456. break;
  43457. case BABYLON.Texture.SKYBOX_MODE:
  43458. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43459. break;
  43460. case BABYLON.Texture.SPHERICAL_MODE:
  43461. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43462. break;
  43463. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43464. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43465. break;
  43466. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43467. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43468. break;
  43469. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43470. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43471. break;
  43472. case BABYLON.Texture.CUBIC_MODE:
  43473. case BABYLON.Texture.INVCUBIC_MODE:
  43474. default:
  43475. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43476. break;
  43477. }
  43478. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43479. }
  43480. }
  43481. else {
  43482. defines.REFLECTION = false;
  43483. }
  43484. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43485. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43486. return false;
  43487. }
  43488. else {
  43489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43490. }
  43491. }
  43492. else {
  43493. defines.EMISSIVE = false;
  43494. }
  43495. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43496. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43497. return false;
  43498. }
  43499. else {
  43500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43501. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43502. }
  43503. }
  43504. else {
  43505. defines.LIGHTMAP = false;
  43506. }
  43507. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43508. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43509. return false;
  43510. }
  43511. else {
  43512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43513. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43514. }
  43515. }
  43516. else {
  43517. defines.SPECULAR = false;
  43518. }
  43519. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43520. // Bump texure can not be not blocking.
  43521. if (!this._bumpTexture.isReady()) {
  43522. return false;
  43523. }
  43524. else {
  43525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43526. defines.PARALLAX = this._useParallax;
  43527. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43528. }
  43529. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43530. }
  43531. else {
  43532. defines.BUMP = false;
  43533. }
  43534. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43535. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43536. return false;
  43537. }
  43538. else {
  43539. defines._needUVs = true;
  43540. defines.REFRACTION = true;
  43541. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43542. }
  43543. }
  43544. else {
  43545. defines.REFRACTION = false;
  43546. }
  43547. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43548. }
  43549. else {
  43550. defines.DIFFUSE = false;
  43551. defines.AMBIENT = false;
  43552. defines.OPACITY = false;
  43553. defines.REFLECTION = false;
  43554. defines.EMISSIVE = false;
  43555. defines.LIGHTMAP = false;
  43556. defines.BUMP = false;
  43557. defines.REFRACTION = false;
  43558. }
  43559. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43560. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43561. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43562. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43563. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43564. }
  43565. if (defines._areImageProcessingDirty) {
  43566. if (!this._imageProcessingConfiguration.isReady()) {
  43567. return false;
  43568. }
  43569. this._imageProcessingConfiguration.prepareDefines(defines);
  43570. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43571. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43572. }
  43573. if (defines._areFresnelDirty) {
  43574. if (StandardMaterial.FresnelEnabled) {
  43575. // Fresnel
  43576. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43577. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43578. this._reflectionFresnelParameters) {
  43579. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43580. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43581. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43582. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43583. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43584. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43585. defines._needNormals = true;
  43586. defines.FRESNEL = true;
  43587. }
  43588. }
  43589. else {
  43590. defines.FRESNEL = false;
  43591. }
  43592. }
  43593. // Misc.
  43594. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43595. // Attribs
  43596. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43597. // Values that need to be evaluated on every frame
  43598. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43599. // Get correct effect
  43600. if (defines.isDirty) {
  43601. defines.markAsProcessed();
  43602. scene.resetCachedMaterial();
  43603. // Fallbacks
  43604. var fallbacks = new BABYLON.EffectFallbacks();
  43605. if (defines.REFLECTION) {
  43606. fallbacks.addFallback(0, "REFLECTION");
  43607. }
  43608. if (defines.SPECULAR) {
  43609. fallbacks.addFallback(0, "SPECULAR");
  43610. }
  43611. if (defines.BUMP) {
  43612. fallbacks.addFallback(0, "BUMP");
  43613. }
  43614. if (defines.PARALLAX) {
  43615. fallbacks.addFallback(1, "PARALLAX");
  43616. }
  43617. if (defines.PARALLAXOCCLUSION) {
  43618. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43619. }
  43620. if (defines.SPECULAROVERALPHA) {
  43621. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43622. }
  43623. if (defines.FOG) {
  43624. fallbacks.addFallback(1, "FOG");
  43625. }
  43626. if (defines.POINTSIZE) {
  43627. fallbacks.addFallback(0, "POINTSIZE");
  43628. }
  43629. if (defines.LOGARITHMICDEPTH) {
  43630. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43631. }
  43632. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43633. if (defines.SPECULARTERM) {
  43634. fallbacks.addFallback(0, "SPECULARTERM");
  43635. }
  43636. if (defines.DIFFUSEFRESNEL) {
  43637. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43638. }
  43639. if (defines.OPACITYFRESNEL) {
  43640. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43641. }
  43642. if (defines.REFLECTIONFRESNEL) {
  43643. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43644. }
  43645. if (defines.EMISSIVEFRESNEL) {
  43646. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43647. }
  43648. if (defines.FRESNEL) {
  43649. fallbacks.addFallback(4, "FRESNEL");
  43650. }
  43651. //Attributes
  43652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43653. if (defines.NORMAL) {
  43654. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43655. }
  43656. if (defines.UV1) {
  43657. attribs.push(BABYLON.VertexBuffer.UVKind);
  43658. }
  43659. if (defines.UV2) {
  43660. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43661. }
  43662. if (defines.VERTEXCOLOR) {
  43663. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43664. }
  43665. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43666. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43667. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43668. var shaderName = "default";
  43669. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43670. "vFogInfos", "vFogColor", "pointSize",
  43671. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43672. "mBones",
  43673. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43674. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43675. "vReflectionPosition", "vReflectionSize",
  43676. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43677. ];
  43678. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43679. var uniformBuffers = ["Material", "Scene"];
  43680. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43681. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43682. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43683. uniformsNames: uniforms,
  43684. uniformBuffersNames: uniformBuffers,
  43685. samplers: samplers,
  43686. defines: defines,
  43687. maxSimultaneousLights: this._maxSimultaneousLights
  43688. });
  43689. if (this.customShaderNameResolve) {
  43690. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43691. }
  43692. var join = defines.toString();
  43693. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43694. attributes: attribs,
  43695. uniformsNames: uniforms,
  43696. uniformBuffersNames: uniformBuffers,
  43697. samplers: samplers,
  43698. defines: join,
  43699. fallbacks: fallbacks,
  43700. onCompiled: this.onCompiled,
  43701. onError: this.onError,
  43702. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43703. }, engine), defines);
  43704. this.buildUniformLayout();
  43705. }
  43706. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43707. return false;
  43708. }
  43709. defines._renderId = scene.getRenderId();
  43710. this._wasPreviouslyReady = true;
  43711. return true;
  43712. };
  43713. StandardMaterial.prototype.buildUniformLayout = function () {
  43714. // Order is important !
  43715. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43716. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43717. this._uniformBuffer.addUniform("opacityParts", 4);
  43718. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43719. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43720. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43721. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43722. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43723. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43724. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43725. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43726. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43727. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43728. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43729. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43730. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43731. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43732. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43733. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43734. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43735. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43736. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43737. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43738. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43739. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43740. this._uniformBuffer.addUniform("specularMatrix", 16);
  43741. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43742. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43743. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43744. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43745. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43746. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43747. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43748. this._uniformBuffer.addUniform("pointSize", 1);
  43749. this._uniformBuffer.create();
  43750. };
  43751. StandardMaterial.prototype.unbind = function () {
  43752. if (this._activeEffect) {
  43753. var needFlag = false;
  43754. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43755. this._activeEffect.setTexture("reflection2DSampler", null);
  43756. needFlag = true;
  43757. }
  43758. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43759. this._activeEffect.setTexture("refraction2DSampler", null);
  43760. needFlag = true;
  43761. }
  43762. if (needFlag) {
  43763. this._markAllSubMeshesAsTexturesDirty();
  43764. }
  43765. }
  43766. _super.prototype.unbind.call(this);
  43767. };
  43768. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43769. var scene = this.getScene();
  43770. var defines = subMesh._materialDefines;
  43771. if (!defines) {
  43772. return;
  43773. }
  43774. var effect = subMesh.effect;
  43775. if (!effect) {
  43776. return;
  43777. }
  43778. this._activeEffect = effect;
  43779. // Matrices
  43780. this.bindOnlyWorldMatrix(world);
  43781. // Normal Matrix
  43782. if (defines.OBJECTSPACE_NORMALMAP) {
  43783. world.toNormalMatrix(this._normalMatrix);
  43784. this.bindOnlyNormalMatrix(this._normalMatrix);
  43785. }
  43786. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43787. // Bones
  43788. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43789. if (mustRebind) {
  43790. this._uniformBuffer.bindToEffect(effect, "Material");
  43791. this.bindViewProjection(effect);
  43792. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43793. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43794. // Fresnel
  43795. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43796. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43797. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43798. }
  43799. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43800. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43801. }
  43802. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43803. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43804. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43805. }
  43806. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43807. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43808. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43809. }
  43810. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43811. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43812. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43813. }
  43814. }
  43815. // Textures
  43816. if (scene.texturesEnabled) {
  43817. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43818. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43819. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43820. if (this._diffuseTexture.hasAlpha) {
  43821. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43822. }
  43823. }
  43824. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43825. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43826. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43827. }
  43828. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43829. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43830. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43831. }
  43832. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43833. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43834. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43835. if (this._reflectionTexture.boundingBoxSize) {
  43836. var cubeTexture = this._reflectionTexture;
  43837. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43838. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43839. }
  43840. }
  43841. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43842. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43843. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43844. }
  43845. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43846. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43847. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43848. }
  43849. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43850. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43851. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43852. }
  43853. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43854. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43855. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43856. if (scene._mirroredCameraPosition) {
  43857. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43858. }
  43859. else {
  43860. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43861. }
  43862. }
  43863. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43864. var depth = 1.0;
  43865. if (!this._refractionTexture.isCube) {
  43866. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43867. if (this._refractionTexture.depth) {
  43868. depth = this._refractionTexture.depth;
  43869. }
  43870. }
  43871. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43872. }
  43873. }
  43874. // Point size
  43875. if (this.pointsCloud) {
  43876. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43877. }
  43878. if (defines.SPECULARTERM) {
  43879. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43880. }
  43881. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43882. // Diffuse
  43883. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43884. }
  43885. // Textures
  43886. if (scene.texturesEnabled) {
  43887. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43888. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43889. }
  43890. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43891. effect.setTexture("ambientSampler", this._ambientTexture);
  43892. }
  43893. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43894. effect.setTexture("opacitySampler", this._opacityTexture);
  43895. }
  43896. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43897. if (this._reflectionTexture.isCube) {
  43898. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43899. }
  43900. else {
  43901. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43902. }
  43903. }
  43904. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43905. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43906. }
  43907. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43908. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43909. }
  43910. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43911. effect.setTexture("specularSampler", this._specularTexture);
  43912. }
  43913. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43914. effect.setTexture("bumpSampler", this._bumpTexture);
  43915. }
  43916. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43917. var depth = 1.0;
  43918. if (this._refractionTexture.isCube) {
  43919. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43920. }
  43921. else {
  43922. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43923. }
  43924. }
  43925. }
  43926. // Clip plane
  43927. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43928. // Colors
  43929. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43930. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43931. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43932. }
  43933. if (mustRebind || !this.isFrozen) {
  43934. // Lights
  43935. if (scene.lightsEnabled && !this._disableLighting) {
  43936. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43937. }
  43938. // View
  43939. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43940. this.bindView(effect);
  43941. }
  43942. // Fog
  43943. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43944. // Morph targets
  43945. if (defines.NUM_MORPH_INFLUENCERS) {
  43946. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43947. }
  43948. // Log. depth
  43949. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43950. // image processing
  43951. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43952. this._imageProcessingConfiguration.bind(this._activeEffect);
  43953. }
  43954. }
  43955. this._uniformBuffer.update();
  43956. this._afterBind(mesh, this._activeEffect);
  43957. };
  43958. StandardMaterial.prototype.getAnimatables = function () {
  43959. var results = [];
  43960. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43961. results.push(this._diffuseTexture);
  43962. }
  43963. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43964. results.push(this._ambientTexture);
  43965. }
  43966. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43967. results.push(this._opacityTexture);
  43968. }
  43969. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43970. results.push(this._reflectionTexture);
  43971. }
  43972. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43973. results.push(this._emissiveTexture);
  43974. }
  43975. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43976. results.push(this._specularTexture);
  43977. }
  43978. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43979. results.push(this._bumpTexture);
  43980. }
  43981. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43982. results.push(this._lightmapTexture);
  43983. }
  43984. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43985. results.push(this._refractionTexture);
  43986. }
  43987. return results;
  43988. };
  43989. StandardMaterial.prototype.getActiveTextures = function () {
  43990. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43991. if (this._diffuseTexture) {
  43992. activeTextures.push(this._diffuseTexture);
  43993. }
  43994. if (this._ambientTexture) {
  43995. activeTextures.push(this._ambientTexture);
  43996. }
  43997. if (this._opacityTexture) {
  43998. activeTextures.push(this._opacityTexture);
  43999. }
  44000. if (this._reflectionTexture) {
  44001. activeTextures.push(this._reflectionTexture);
  44002. }
  44003. if (this._emissiveTexture) {
  44004. activeTextures.push(this._emissiveTexture);
  44005. }
  44006. if (this._specularTexture) {
  44007. activeTextures.push(this._specularTexture);
  44008. }
  44009. if (this._bumpTexture) {
  44010. activeTextures.push(this._bumpTexture);
  44011. }
  44012. if (this._lightmapTexture) {
  44013. activeTextures.push(this._lightmapTexture);
  44014. }
  44015. if (this._refractionTexture) {
  44016. activeTextures.push(this._refractionTexture);
  44017. }
  44018. return activeTextures;
  44019. };
  44020. StandardMaterial.prototype.hasTexture = function (texture) {
  44021. if (_super.prototype.hasTexture.call(this, texture)) {
  44022. return true;
  44023. }
  44024. if (this._diffuseTexture === texture) {
  44025. return true;
  44026. }
  44027. if (this._ambientTexture === texture) {
  44028. return true;
  44029. }
  44030. if (this._opacityTexture === texture) {
  44031. return true;
  44032. }
  44033. if (this._reflectionTexture === texture) {
  44034. return true;
  44035. }
  44036. if (this._emissiveTexture === texture) {
  44037. return true;
  44038. }
  44039. if (this._specularTexture === texture) {
  44040. return true;
  44041. }
  44042. if (this._bumpTexture === texture) {
  44043. return true;
  44044. }
  44045. if (this._lightmapTexture === texture) {
  44046. return true;
  44047. }
  44048. if (this._refractionTexture === texture) {
  44049. return true;
  44050. }
  44051. return false;
  44052. };
  44053. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44054. if (forceDisposeTextures) {
  44055. if (this._diffuseTexture) {
  44056. this._diffuseTexture.dispose();
  44057. }
  44058. if (this._ambientTexture) {
  44059. this._ambientTexture.dispose();
  44060. }
  44061. if (this._opacityTexture) {
  44062. this._opacityTexture.dispose();
  44063. }
  44064. if (this._reflectionTexture) {
  44065. this._reflectionTexture.dispose();
  44066. }
  44067. if (this._emissiveTexture) {
  44068. this._emissiveTexture.dispose();
  44069. }
  44070. if (this._specularTexture) {
  44071. this._specularTexture.dispose();
  44072. }
  44073. if (this._bumpTexture) {
  44074. this._bumpTexture.dispose();
  44075. }
  44076. if (this._lightmapTexture) {
  44077. this._lightmapTexture.dispose();
  44078. }
  44079. if (this._refractionTexture) {
  44080. this._refractionTexture.dispose();
  44081. }
  44082. }
  44083. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44084. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44085. }
  44086. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44087. };
  44088. StandardMaterial.prototype.clone = function (name) {
  44089. var _this = this;
  44090. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44091. result.name = name;
  44092. result.id = name;
  44093. return result;
  44094. };
  44095. StandardMaterial.prototype.serialize = function () {
  44096. return BABYLON.SerializationHelper.Serialize(this);
  44097. };
  44098. // Statics
  44099. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44100. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44101. };
  44102. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44103. get: function () {
  44104. return StandardMaterial._DiffuseTextureEnabled;
  44105. },
  44106. set: function (value) {
  44107. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44108. return;
  44109. }
  44110. StandardMaterial._DiffuseTextureEnabled = value;
  44111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44112. },
  44113. enumerable: true,
  44114. configurable: true
  44115. });
  44116. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44117. get: function () {
  44118. return StandardMaterial._AmbientTextureEnabled;
  44119. },
  44120. set: function (value) {
  44121. if (StandardMaterial._AmbientTextureEnabled === value) {
  44122. return;
  44123. }
  44124. StandardMaterial._AmbientTextureEnabled = value;
  44125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44126. },
  44127. enumerable: true,
  44128. configurable: true
  44129. });
  44130. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44131. get: function () {
  44132. return StandardMaterial._OpacityTextureEnabled;
  44133. },
  44134. set: function (value) {
  44135. if (StandardMaterial._OpacityTextureEnabled === value) {
  44136. return;
  44137. }
  44138. StandardMaterial._OpacityTextureEnabled = value;
  44139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44140. },
  44141. enumerable: true,
  44142. configurable: true
  44143. });
  44144. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44145. get: function () {
  44146. return StandardMaterial._ReflectionTextureEnabled;
  44147. },
  44148. set: function (value) {
  44149. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44150. return;
  44151. }
  44152. StandardMaterial._ReflectionTextureEnabled = value;
  44153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44154. },
  44155. enumerable: true,
  44156. configurable: true
  44157. });
  44158. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44159. get: function () {
  44160. return StandardMaterial._EmissiveTextureEnabled;
  44161. },
  44162. set: function (value) {
  44163. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44164. return;
  44165. }
  44166. StandardMaterial._EmissiveTextureEnabled = value;
  44167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44168. },
  44169. enumerable: true,
  44170. configurable: true
  44171. });
  44172. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44173. get: function () {
  44174. return StandardMaterial._SpecularTextureEnabled;
  44175. },
  44176. set: function (value) {
  44177. if (StandardMaterial._SpecularTextureEnabled === value) {
  44178. return;
  44179. }
  44180. StandardMaterial._SpecularTextureEnabled = value;
  44181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44182. },
  44183. enumerable: true,
  44184. configurable: true
  44185. });
  44186. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44187. get: function () {
  44188. return StandardMaterial._BumpTextureEnabled;
  44189. },
  44190. set: function (value) {
  44191. if (StandardMaterial._BumpTextureEnabled === value) {
  44192. return;
  44193. }
  44194. StandardMaterial._BumpTextureEnabled = value;
  44195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44196. },
  44197. enumerable: true,
  44198. configurable: true
  44199. });
  44200. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44201. get: function () {
  44202. return StandardMaterial._LightmapTextureEnabled;
  44203. },
  44204. set: function (value) {
  44205. if (StandardMaterial._LightmapTextureEnabled === value) {
  44206. return;
  44207. }
  44208. StandardMaterial._LightmapTextureEnabled = value;
  44209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44210. },
  44211. enumerable: true,
  44212. configurable: true
  44213. });
  44214. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44215. get: function () {
  44216. return StandardMaterial._RefractionTextureEnabled;
  44217. },
  44218. set: function (value) {
  44219. if (StandardMaterial._RefractionTextureEnabled === value) {
  44220. return;
  44221. }
  44222. StandardMaterial._RefractionTextureEnabled = value;
  44223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44224. },
  44225. enumerable: true,
  44226. configurable: true
  44227. });
  44228. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44229. get: function () {
  44230. return StandardMaterial._ColorGradingTextureEnabled;
  44231. },
  44232. set: function (value) {
  44233. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44234. return;
  44235. }
  44236. StandardMaterial._ColorGradingTextureEnabled = value;
  44237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44238. },
  44239. enumerable: true,
  44240. configurable: true
  44241. });
  44242. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44243. get: function () {
  44244. return StandardMaterial._FresnelEnabled;
  44245. },
  44246. set: function (value) {
  44247. if (StandardMaterial._FresnelEnabled === value) {
  44248. return;
  44249. }
  44250. StandardMaterial._FresnelEnabled = value;
  44251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44252. },
  44253. enumerable: true,
  44254. configurable: true
  44255. });
  44256. // Flags used to enable or disable a type of texture for all Standard Materials
  44257. StandardMaterial._DiffuseTextureEnabled = true;
  44258. StandardMaterial._AmbientTextureEnabled = true;
  44259. StandardMaterial._OpacityTextureEnabled = true;
  44260. StandardMaterial._ReflectionTextureEnabled = true;
  44261. StandardMaterial._EmissiveTextureEnabled = true;
  44262. StandardMaterial._SpecularTextureEnabled = true;
  44263. StandardMaterial._BumpTextureEnabled = true;
  44264. StandardMaterial._LightmapTextureEnabled = true;
  44265. StandardMaterial._RefractionTextureEnabled = true;
  44266. StandardMaterial._ColorGradingTextureEnabled = true;
  44267. StandardMaterial._FresnelEnabled = true;
  44268. __decorate([
  44269. BABYLON.serializeAsTexture("diffuseTexture")
  44270. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44271. __decorate([
  44272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44273. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44274. __decorate([
  44275. BABYLON.serializeAsTexture("ambientTexture")
  44276. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44277. __decorate([
  44278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44279. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44280. __decorate([
  44281. BABYLON.serializeAsTexture("opacityTexture")
  44282. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44283. __decorate([
  44284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44285. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44286. __decorate([
  44287. BABYLON.serializeAsTexture("reflectionTexture")
  44288. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44289. __decorate([
  44290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44291. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44292. __decorate([
  44293. BABYLON.serializeAsTexture("emissiveTexture")
  44294. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44295. __decorate([
  44296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44297. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44298. __decorate([
  44299. BABYLON.serializeAsTexture("specularTexture")
  44300. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44301. __decorate([
  44302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44303. ], StandardMaterial.prototype, "specularTexture", void 0);
  44304. __decorate([
  44305. BABYLON.serializeAsTexture("bumpTexture")
  44306. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44307. __decorate([
  44308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44309. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44310. __decorate([
  44311. BABYLON.serializeAsTexture("lightmapTexture")
  44312. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44313. __decorate([
  44314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44315. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44316. __decorate([
  44317. BABYLON.serializeAsTexture("refractionTexture")
  44318. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44319. __decorate([
  44320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44321. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44322. __decorate([
  44323. BABYLON.serializeAsColor3("ambient")
  44324. ], StandardMaterial.prototype, "ambientColor", void 0);
  44325. __decorate([
  44326. BABYLON.serializeAsColor3("diffuse")
  44327. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44328. __decorate([
  44329. BABYLON.serializeAsColor3("specular")
  44330. ], StandardMaterial.prototype, "specularColor", void 0);
  44331. __decorate([
  44332. BABYLON.serializeAsColor3("emissive")
  44333. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44334. __decorate([
  44335. BABYLON.serialize()
  44336. ], StandardMaterial.prototype, "specularPower", void 0);
  44337. __decorate([
  44338. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44339. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44340. __decorate([
  44341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44342. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44343. __decorate([
  44344. BABYLON.serialize("useEmissiveAsIllumination")
  44345. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44346. __decorate([
  44347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44348. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44349. __decorate([
  44350. BABYLON.serialize("linkEmissiveWithDiffuse")
  44351. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44352. __decorate([
  44353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44354. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44355. __decorate([
  44356. BABYLON.serialize("useSpecularOverAlpha")
  44357. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44358. __decorate([
  44359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44360. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44361. __decorate([
  44362. BABYLON.serialize("useReflectionOverAlpha")
  44363. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44364. __decorate([
  44365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44366. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44367. __decorate([
  44368. BABYLON.serialize("disableLighting")
  44369. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44370. __decorate([
  44371. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44372. ], StandardMaterial.prototype, "disableLighting", void 0);
  44373. __decorate([
  44374. BABYLON.serialize("useObjectSpaceNormalMap")
  44375. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44376. __decorate([
  44377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44378. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44379. __decorate([
  44380. BABYLON.serialize("useParallax")
  44381. ], StandardMaterial.prototype, "_useParallax", void 0);
  44382. __decorate([
  44383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44384. ], StandardMaterial.prototype, "useParallax", void 0);
  44385. __decorate([
  44386. BABYLON.serialize("useParallaxOcclusion")
  44387. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44388. __decorate([
  44389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44390. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44391. __decorate([
  44392. BABYLON.serialize()
  44393. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44394. __decorate([
  44395. BABYLON.serialize("roughness")
  44396. ], StandardMaterial.prototype, "_roughness", void 0);
  44397. __decorate([
  44398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44399. ], StandardMaterial.prototype, "roughness", void 0);
  44400. __decorate([
  44401. BABYLON.serialize()
  44402. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44403. __decorate([
  44404. BABYLON.serialize()
  44405. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44406. __decorate([
  44407. BABYLON.serialize()
  44408. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44409. __decorate([
  44410. BABYLON.serialize("useLightmapAsShadowmap")
  44411. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44412. __decorate([
  44413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44414. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44415. __decorate([
  44416. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44417. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44418. __decorate([
  44419. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44420. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44421. __decorate([
  44422. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44423. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44424. __decorate([
  44425. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44426. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44427. __decorate([
  44428. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44429. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44430. __decorate([
  44431. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44432. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44433. __decorate([
  44434. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44435. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44436. __decorate([
  44437. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44438. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44439. __decorate([
  44440. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44441. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44444. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44445. __decorate([
  44446. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44447. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44450. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44451. __decorate([
  44452. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44453. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44456. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44457. __decorate([
  44458. BABYLON.serialize("maxSimultaneousLights")
  44459. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44462. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44463. __decorate([
  44464. BABYLON.serialize("invertNormalMapX")
  44465. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44468. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44469. __decorate([
  44470. BABYLON.serialize("invertNormalMapY")
  44471. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44474. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44475. __decorate([
  44476. BABYLON.serialize("twoSidedLighting")
  44477. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44478. __decorate([
  44479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44480. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44481. __decorate([
  44482. BABYLON.serialize()
  44483. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44484. return StandardMaterial;
  44485. }(BABYLON.PushMaterial));
  44486. BABYLON.StandardMaterial = StandardMaterial;
  44487. })(BABYLON || (BABYLON = {}));
  44488. //# sourceMappingURL=babylon.standardMaterial.js.map
  44489. var BABYLON;
  44490. (function (BABYLON) {
  44491. /**
  44492. * Manages the defines for the PBR Material.
  44493. * @hiddenChildren
  44494. */
  44495. var PBRMaterialDefines = /** @class */ (function (_super) {
  44496. __extends(PBRMaterialDefines, _super);
  44497. /**
  44498. * Initializes the PBR Material defines.
  44499. */
  44500. function PBRMaterialDefines() {
  44501. var _this = _super.call(this) || this;
  44502. _this.PBR = true;
  44503. _this.MAINUV1 = false;
  44504. _this.MAINUV2 = false;
  44505. _this.UV1 = false;
  44506. _this.UV2 = false;
  44507. _this.ALBEDO = false;
  44508. _this.ALBEDODIRECTUV = 0;
  44509. _this.VERTEXCOLOR = false;
  44510. _this.AMBIENT = false;
  44511. _this.AMBIENTDIRECTUV = 0;
  44512. _this.AMBIENTINGRAYSCALE = false;
  44513. _this.OPACITY = false;
  44514. _this.VERTEXALPHA = false;
  44515. _this.OPACITYDIRECTUV = 0;
  44516. _this.OPACITYRGB = false;
  44517. _this.ALPHATEST = false;
  44518. _this.DEPTHPREPASS = false;
  44519. _this.ALPHABLEND = false;
  44520. _this.ALPHAFROMALBEDO = false;
  44521. _this.ALPHATESTVALUE = "0.5";
  44522. _this.SPECULAROVERALPHA = false;
  44523. _this.RADIANCEOVERALPHA = false;
  44524. _this.ALPHAFRESNEL = false;
  44525. _this.LINEARALPHAFRESNEL = false;
  44526. _this.PREMULTIPLYALPHA = false;
  44527. _this.EMISSIVE = false;
  44528. _this.EMISSIVEDIRECTUV = 0;
  44529. _this.REFLECTIVITY = false;
  44530. _this.REFLECTIVITYDIRECTUV = 0;
  44531. _this.SPECULARTERM = false;
  44532. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44533. _this.MICROSURFACEAUTOMATIC = false;
  44534. _this.LODBASEDMICROSFURACE = false;
  44535. _this.MICROSURFACEMAP = false;
  44536. _this.MICROSURFACEMAPDIRECTUV = 0;
  44537. _this.METALLICWORKFLOW = false;
  44538. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44539. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44540. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44541. _this.AOSTOREINMETALMAPRED = false;
  44542. _this.ENVIRONMENTBRDF = false;
  44543. _this.NORMAL = false;
  44544. _this.TANGENT = false;
  44545. _this.BUMP = false;
  44546. _this.BUMPDIRECTUV = 0;
  44547. _this.OBJECTSPACE_NORMALMAP = false;
  44548. _this.PARALLAX = false;
  44549. _this.PARALLAXOCCLUSION = false;
  44550. _this.NORMALXYSCALE = true;
  44551. _this.LIGHTMAP = false;
  44552. _this.LIGHTMAPDIRECTUV = 0;
  44553. _this.USELIGHTMAPASSHADOWMAP = false;
  44554. _this.GAMMALIGHTMAP = false;
  44555. _this.REFLECTION = false;
  44556. _this.REFLECTIONMAP_3D = false;
  44557. _this.REFLECTIONMAP_SPHERICAL = false;
  44558. _this.REFLECTIONMAP_PLANAR = false;
  44559. _this.REFLECTIONMAP_CUBIC = false;
  44560. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44561. _this.REFLECTIONMAP_PROJECTION = false;
  44562. _this.REFLECTIONMAP_SKYBOX = false;
  44563. _this.REFLECTIONMAP_EXPLICIT = false;
  44564. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44565. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44566. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44567. _this.INVERTCUBICMAP = false;
  44568. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44569. _this.USESPHERICALINVERTEX = false;
  44570. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44571. _this.LODINREFLECTIONALPHA = false;
  44572. _this.GAMMAREFLECTION = false;
  44573. _this.RADIANCEOCCLUSION = false;
  44574. _this.HORIZONOCCLUSION = false;
  44575. _this.REFRACTION = false;
  44576. _this.REFRACTIONMAP_3D = false;
  44577. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44578. _this.LODINREFRACTIONALPHA = false;
  44579. _this.GAMMAREFRACTION = false;
  44580. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44581. _this.INSTANCES = false;
  44582. _this.NUM_BONE_INFLUENCERS = 0;
  44583. _this.BonesPerMesh = 0;
  44584. _this.NONUNIFORMSCALING = false;
  44585. _this.MORPHTARGETS = false;
  44586. _this.MORPHTARGETS_NORMAL = false;
  44587. _this.MORPHTARGETS_TANGENT = false;
  44588. _this.NUM_MORPH_INFLUENCERS = 0;
  44589. _this.IMAGEPROCESSING = false;
  44590. _this.VIGNETTE = false;
  44591. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44592. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44593. _this.TONEMAPPING = false;
  44594. _this.CONTRAST = false;
  44595. _this.COLORCURVES = false;
  44596. _this.COLORGRADING = false;
  44597. _this.COLORGRADING3D = false;
  44598. _this.SAMPLER3DGREENDEPTH = false;
  44599. _this.SAMPLER3DBGRMAP = false;
  44600. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44601. _this.EXPOSURE = false;
  44602. _this.USEPHYSICALLIGHTFALLOFF = false;
  44603. _this.TWOSIDEDLIGHTING = false;
  44604. _this.SHADOWFLOAT = false;
  44605. _this.CLIPPLANE = false;
  44606. _this.POINTSIZE = false;
  44607. _this.FOG = false;
  44608. _this.LOGARITHMICDEPTH = false;
  44609. _this.FORCENORMALFORWARD = false;
  44610. _this.SPECULARAA = false;
  44611. _this.UNLIT = false;
  44612. _this.rebuild();
  44613. return _this;
  44614. }
  44615. /**
  44616. * Resets the PBR Material defines.
  44617. */
  44618. PBRMaterialDefines.prototype.reset = function () {
  44619. _super.prototype.reset.call(this);
  44620. this.ALPHATESTVALUE = "0.5";
  44621. this.PBR = true;
  44622. };
  44623. return PBRMaterialDefines;
  44624. }(BABYLON.MaterialDefines));
  44625. /**
  44626. * The Physically based material base class of BJS.
  44627. *
  44628. * This offers the main features of a standard PBR material.
  44629. * For more information, please refer to the documentation :
  44630. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44631. */
  44632. var PBRBaseMaterial = /** @class */ (function (_super) {
  44633. __extends(PBRBaseMaterial, _super);
  44634. /**
  44635. * Instantiates a new PBRMaterial instance.
  44636. *
  44637. * @param name The material name
  44638. * @param scene The scene the material will be use in.
  44639. */
  44640. function PBRBaseMaterial(name, scene) {
  44641. var _this = _super.call(this, name, scene) || this;
  44642. /**
  44643. * Intensity of the direct lights e.g. the four lights available in your scene.
  44644. * This impacts both the direct diffuse and specular highlights.
  44645. */
  44646. _this._directIntensity = 1.0;
  44647. /**
  44648. * Intensity of the emissive part of the material.
  44649. * This helps controlling the emissive effect without modifying the emissive color.
  44650. */
  44651. _this._emissiveIntensity = 1.0;
  44652. /**
  44653. * Intensity of the environment e.g. how much the environment will light the object
  44654. * either through harmonics for rough material or through the refelction for shiny ones.
  44655. */
  44656. _this._environmentIntensity = 1.0;
  44657. /**
  44658. * This is a special control allowing the reduction of the specular highlights coming from the
  44659. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44660. */
  44661. _this._specularIntensity = 1.0;
  44662. /**
  44663. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44664. */
  44665. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44666. /**
  44667. * Debug Control allowing disabling the bump map on this material.
  44668. */
  44669. _this._disableBumpMap = false;
  44670. /**
  44671. * AKA Occlusion Texture Intensity in other nomenclature.
  44672. */
  44673. _this._ambientTextureStrength = 1.0;
  44674. /**
  44675. * The color of a material in ambient lighting.
  44676. */
  44677. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44678. /**
  44679. * AKA Diffuse Color in other nomenclature.
  44680. */
  44681. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44682. /**
  44683. * AKA Specular Color in other nomenclature.
  44684. */
  44685. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44686. /**
  44687. * The color applied when light is reflected from a material.
  44688. */
  44689. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44690. /**
  44691. * The color applied when light is emitted from a material.
  44692. */
  44693. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44694. /**
  44695. * AKA Glossiness in other nomenclature.
  44696. */
  44697. _this._microSurface = 0.9;
  44698. /**
  44699. * source material index of refraction (IOR)' / 'destination material IOR.
  44700. */
  44701. _this._indexOfRefraction = 0.66;
  44702. /**
  44703. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44704. */
  44705. _this._invertRefractionY = false;
  44706. /**
  44707. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44708. * Materials half opaque for instance using refraction could benefit from this control.
  44709. */
  44710. _this._linkRefractionWithTransparency = false;
  44711. /**
  44712. * Specifies that the material will use the light map as a show map.
  44713. */
  44714. _this._useLightmapAsShadowmap = false;
  44715. /**
  44716. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44717. * makes the reflect vector face the model (under horizon).
  44718. */
  44719. _this._useHorizonOcclusion = true;
  44720. /**
  44721. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44722. * too much the area relying on ambient texture to define their ambient occlusion.
  44723. */
  44724. _this._useRadianceOcclusion = true;
  44725. /**
  44726. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44727. */
  44728. _this._useAlphaFromAlbedoTexture = false;
  44729. /**
  44730. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44731. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44732. */
  44733. _this._useSpecularOverAlpha = true;
  44734. /**
  44735. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44736. */
  44737. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44738. /**
  44739. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44740. */
  44741. _this._useRoughnessFromMetallicTextureAlpha = true;
  44742. /**
  44743. * Specifies if the metallic texture contains the roughness information in its green channel.
  44744. */
  44745. _this._useRoughnessFromMetallicTextureGreen = false;
  44746. /**
  44747. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44748. */
  44749. _this._useMetallnessFromMetallicTextureBlue = false;
  44750. /**
  44751. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44752. */
  44753. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44754. /**
  44755. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44756. */
  44757. _this._useAmbientInGrayScale = false;
  44758. /**
  44759. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44760. * The material will try to infer what glossiness each pixel should be.
  44761. */
  44762. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44763. /**
  44764. * BJS is using an harcoded light falloff based on a manually sets up range.
  44765. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44766. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44767. */
  44768. _this._usePhysicalLightFalloff = true;
  44769. /**
  44770. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44771. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44772. */
  44773. _this._useRadianceOverAlpha = true;
  44774. /**
  44775. * Allows using an object space normal map (instead of tangent space).
  44776. */
  44777. _this._useObjectSpaceNormalMap = false;
  44778. /**
  44779. * Allows using the bump map in parallax mode.
  44780. */
  44781. _this._useParallax = false;
  44782. /**
  44783. * Allows using the bump map in parallax occlusion mode.
  44784. */
  44785. _this._useParallaxOcclusion = false;
  44786. /**
  44787. * Controls the scale bias of the parallax mode.
  44788. */
  44789. _this._parallaxScaleBias = 0.05;
  44790. /**
  44791. * If sets to true, disables all the lights affecting the material.
  44792. */
  44793. _this._disableLighting = false;
  44794. /**
  44795. * Number of Simultaneous lights allowed on the material.
  44796. */
  44797. _this._maxSimultaneousLights = 4;
  44798. /**
  44799. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44800. */
  44801. _this._invertNormalMapX = false;
  44802. /**
  44803. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44804. */
  44805. _this._invertNormalMapY = false;
  44806. /**
  44807. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44808. */
  44809. _this._twoSidedLighting = false;
  44810. /**
  44811. * Defines the alpha limits in alpha test mode.
  44812. */
  44813. _this._alphaCutOff = 0.4;
  44814. /**
  44815. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44816. */
  44817. _this._forceAlphaTest = false;
  44818. /**
  44819. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44820. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44821. */
  44822. _this._useAlphaFresnel = false;
  44823. /**
  44824. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44825. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44826. */
  44827. _this._useLinearAlphaFresnel = false;
  44828. /**
  44829. * The transparency mode of the material.
  44830. */
  44831. _this._transparencyMode = null;
  44832. /**
  44833. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44834. * from cos thetav and roughness:
  44835. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44836. */
  44837. _this._environmentBRDFTexture = null;
  44838. /**
  44839. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44840. */
  44841. _this._forceIrradianceInFragment = false;
  44842. /**
  44843. * Force normal to face away from face.
  44844. */
  44845. _this._forceNormalForward = false;
  44846. /**
  44847. * Enables specular anti aliasing in the PBR shader.
  44848. * It will both interacts on the Geometry for analytical and IBL lighting.
  44849. * It also prefilter the roughness map based on the bump values.
  44850. */
  44851. _this._enableSpecularAntiAliasing = false;
  44852. /**
  44853. * Stores the available render targets.
  44854. */
  44855. _this._renderTargets = new BABYLON.SmartArray(16);
  44856. /**
  44857. * Sets the global ambient color for the material used in lighting calculations.
  44858. */
  44859. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44860. /**
  44861. * If set to true, no lighting calculations will be applied.
  44862. */
  44863. _this._unlit = false;
  44864. // Setup the default processing configuration to the scene.
  44865. _this._attachImageProcessingConfiguration(null);
  44866. _this.getRenderTargetTextures = function () {
  44867. _this._renderTargets.reset();
  44868. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44869. _this._renderTargets.push(_this._reflectionTexture);
  44870. }
  44871. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44872. _this._renderTargets.push(_this._refractionTexture);
  44873. }
  44874. return _this._renderTargets;
  44875. };
  44876. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44877. return _this;
  44878. }
  44879. /**
  44880. * Attaches a new image processing configuration to the PBR Material.
  44881. * @param configuration
  44882. */
  44883. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44884. var _this = this;
  44885. if (configuration === this._imageProcessingConfiguration) {
  44886. return;
  44887. }
  44888. // Detaches observer.
  44889. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44890. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44891. }
  44892. // Pick the scene configuration if needed.
  44893. if (!configuration) {
  44894. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44895. }
  44896. else {
  44897. this._imageProcessingConfiguration = configuration;
  44898. }
  44899. // Attaches observer.
  44900. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44901. _this._markAllSubMeshesAsImageProcessingDirty();
  44902. });
  44903. };
  44904. /**
  44905. * Gets the name of the material class.
  44906. */
  44907. PBRBaseMaterial.prototype.getClassName = function () {
  44908. return "PBRBaseMaterial";
  44909. };
  44910. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44911. /**
  44912. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44913. */
  44914. get: function () {
  44915. return this._useLogarithmicDepth;
  44916. },
  44917. /**
  44918. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44919. */
  44920. set: function (value) {
  44921. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44922. },
  44923. enumerable: true,
  44924. configurable: true
  44925. });
  44926. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44927. /**
  44928. * Gets the current transparency mode.
  44929. */
  44930. get: function () {
  44931. return this._transparencyMode;
  44932. },
  44933. /**
  44934. * Sets the transparency mode of the material.
  44935. *
  44936. * | Value | Type | Description |
  44937. * | ----- | ----------------------------------- | ----------- |
  44938. * | 0 | OPAQUE | |
  44939. * | 1 | ALPHATEST | |
  44940. * | 2 | ALPHABLEND | |
  44941. * | 3 | ALPHATESTANDBLEND | |
  44942. *
  44943. */
  44944. set: function (value) {
  44945. if (this._transparencyMode === value) {
  44946. return;
  44947. }
  44948. this._transparencyMode = value;
  44949. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44950. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44951. },
  44952. enumerable: true,
  44953. configurable: true
  44954. });
  44955. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44956. /**
  44957. * Returns true if alpha blending should be disabled.
  44958. */
  44959. get: function () {
  44960. return (this._linkRefractionWithTransparency ||
  44961. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44962. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44963. },
  44964. enumerable: true,
  44965. configurable: true
  44966. });
  44967. /**
  44968. * Specifies whether or not this material should be rendered in alpha blend mode.
  44969. */
  44970. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44971. if (this._disableAlphaBlending) {
  44972. return false;
  44973. }
  44974. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44975. };
  44976. /**
  44977. * Specifies if the mesh will require alpha blending.
  44978. * @param mesh - BJS mesh.
  44979. */
  44980. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44981. if (this._disableAlphaBlending) {
  44982. return false;
  44983. }
  44984. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44985. };
  44986. /**
  44987. * Specifies whether or not this material should be rendered in alpha test mode.
  44988. */
  44989. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44990. if (this._forceAlphaTest) {
  44991. return true;
  44992. }
  44993. if (this._linkRefractionWithTransparency) {
  44994. return false;
  44995. }
  44996. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44997. };
  44998. /**
  44999. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45000. */
  45001. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45002. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45003. };
  45004. /**
  45005. * Gets the texture used for the alpha test.
  45006. */
  45007. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45008. return this._albedoTexture;
  45009. };
  45010. /**
  45011. * Specifies that the submesh is ready to be used.
  45012. * @param mesh - BJS mesh.
  45013. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45014. * @param useInstances - Specifies that instances should be used.
  45015. * @returns - boolean indicating that the submesh is ready or not.
  45016. */
  45017. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45018. if (subMesh.effect && this.isFrozen) {
  45019. if (this._wasPreviouslyReady) {
  45020. return true;
  45021. }
  45022. }
  45023. if (!subMesh._materialDefines) {
  45024. subMesh._materialDefines = new PBRMaterialDefines();
  45025. }
  45026. var defines = subMesh._materialDefines;
  45027. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45028. if (defines._renderId === this.getScene().getRenderId()) {
  45029. return true;
  45030. }
  45031. }
  45032. var scene = this.getScene();
  45033. var engine = scene.getEngine();
  45034. if (defines._areTexturesDirty) {
  45035. if (scene.texturesEnabled) {
  45036. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45037. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45038. return false;
  45039. }
  45040. }
  45041. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45042. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45043. return false;
  45044. }
  45045. }
  45046. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45047. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45048. return false;
  45049. }
  45050. }
  45051. var reflectionTexture = this._getReflectionTexture();
  45052. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45053. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45054. return false;
  45055. }
  45056. }
  45057. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45058. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45059. return false;
  45060. }
  45061. }
  45062. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45063. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45064. return false;
  45065. }
  45066. }
  45067. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45068. if (this._metallicTexture) {
  45069. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45070. return false;
  45071. }
  45072. }
  45073. else if (this._reflectivityTexture) {
  45074. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45075. return false;
  45076. }
  45077. }
  45078. if (this._microSurfaceTexture) {
  45079. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45080. return false;
  45081. }
  45082. }
  45083. }
  45084. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45085. // Bump texture cannot be not blocking.
  45086. if (!this._bumpTexture.isReady()) {
  45087. return false;
  45088. }
  45089. }
  45090. var refractionTexture = this._getRefractionTexture();
  45091. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45092. if (!refractionTexture.isReadyOrNotBlocking()) {
  45093. return false;
  45094. }
  45095. }
  45096. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45097. // This is blocking.
  45098. if (!this._environmentBRDFTexture.isReady()) {
  45099. return false;
  45100. }
  45101. }
  45102. }
  45103. }
  45104. if (defines._areImageProcessingDirty) {
  45105. if (!this._imageProcessingConfiguration.isReady()) {
  45106. return false;
  45107. }
  45108. }
  45109. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45110. mesh.createNormals(true);
  45111. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45112. }
  45113. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45114. if (effect) {
  45115. scene.resetCachedMaterial();
  45116. subMesh.setEffect(effect, defines);
  45117. this.buildUniformLayout();
  45118. }
  45119. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45120. return false;
  45121. }
  45122. defines._renderId = scene.getRenderId();
  45123. this._wasPreviouslyReady = true;
  45124. return true;
  45125. };
  45126. /**
  45127. * Specifies if the material uses metallic roughness workflow.
  45128. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45129. */
  45130. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45131. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45132. return true;
  45133. }
  45134. return false;
  45135. };
  45136. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45137. if (onCompiled === void 0) { onCompiled = null; }
  45138. if (onError === void 0) { onError = null; }
  45139. if (useInstances === void 0) { useInstances = null; }
  45140. if (useClipPlane === void 0) { useClipPlane = null; }
  45141. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45142. if (!defines.isDirty) {
  45143. return null;
  45144. }
  45145. defines.markAsProcessed();
  45146. var scene = this.getScene();
  45147. var engine = scene.getEngine();
  45148. // Fallbacks
  45149. var fallbacks = new BABYLON.EffectFallbacks();
  45150. var fallbackRank = 0;
  45151. if (defines.USESPHERICALINVERTEX) {
  45152. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45153. }
  45154. if (defines.FOG) {
  45155. fallbacks.addFallback(fallbackRank, "FOG");
  45156. }
  45157. if (defines.SPECULARAA) {
  45158. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45159. }
  45160. if (defines.POINTSIZE) {
  45161. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45162. }
  45163. if (defines.LOGARITHMICDEPTH) {
  45164. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45165. }
  45166. if (defines.PARALLAX) {
  45167. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45168. }
  45169. if (defines.PARALLAXOCCLUSION) {
  45170. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45171. }
  45172. if (defines.ENVIRONMENTBRDF) {
  45173. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45174. }
  45175. if (defines.TANGENT) {
  45176. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45177. }
  45178. if (defines.BUMP) {
  45179. fallbacks.addFallback(fallbackRank++, "BUMP");
  45180. }
  45181. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45182. if (defines.SPECULARTERM) {
  45183. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45184. }
  45185. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45186. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45187. }
  45188. if (defines.LIGHTMAP) {
  45189. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45190. }
  45191. if (defines.NORMAL) {
  45192. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45193. }
  45194. if (defines.AMBIENT) {
  45195. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45196. }
  45197. if (defines.EMISSIVE) {
  45198. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45199. }
  45200. if (defines.VERTEXCOLOR) {
  45201. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45202. }
  45203. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45204. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45205. }
  45206. if (defines.MORPHTARGETS) {
  45207. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45208. }
  45209. //Attributes
  45210. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45211. if (defines.NORMAL) {
  45212. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45213. }
  45214. if (defines.TANGENT) {
  45215. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45216. }
  45217. if (defines.UV1) {
  45218. attribs.push(BABYLON.VertexBuffer.UVKind);
  45219. }
  45220. if (defines.UV2) {
  45221. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45222. }
  45223. if (defines.VERTEXCOLOR) {
  45224. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45225. }
  45226. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45227. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45228. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45229. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45230. "vFogInfos", "vFogColor", "pointSize",
  45231. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45232. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45233. "mBones",
  45234. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45235. "vLightingIntensity",
  45236. "logarithmicDepthConstant",
  45237. "vSphericalX", "vSphericalY", "vSphericalZ",
  45238. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45239. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45240. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45241. "vTangentSpaceParams"
  45242. ];
  45243. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45244. "bumpSampler", "lightmapSampler", "opacitySampler",
  45245. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45246. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45247. "microSurfaceSampler", "environmentBrdfSampler"];
  45248. var uniformBuffers = ["Material", "Scene"];
  45249. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45250. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45251. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45252. uniformsNames: uniforms,
  45253. uniformBuffersNames: uniformBuffers,
  45254. samplers: samplers,
  45255. defines: defines,
  45256. maxSimultaneousLights: this._maxSimultaneousLights
  45257. });
  45258. var join = defines.toString();
  45259. return engine.createEffect("pbr", {
  45260. attributes: attribs,
  45261. uniformsNames: uniforms,
  45262. uniformBuffersNames: uniformBuffers,
  45263. samplers: samplers,
  45264. defines: join,
  45265. fallbacks: fallbacks,
  45266. onCompiled: onCompiled,
  45267. onError: onError,
  45268. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45269. }, engine);
  45270. };
  45271. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45272. if (useInstances === void 0) { useInstances = null; }
  45273. if (useClipPlane === void 0) { useClipPlane = null; }
  45274. var scene = this.getScene();
  45275. var engine = scene.getEngine();
  45276. // Lights
  45277. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45278. defines._needNormals = true;
  45279. // Textures
  45280. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45281. if (defines._areTexturesDirty) {
  45282. defines._needUVs = false;
  45283. if (scene.texturesEnabled) {
  45284. if (scene.getEngine().getCaps().textureLOD) {
  45285. defines.LODBASEDMICROSFURACE = true;
  45286. }
  45287. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45289. }
  45290. else {
  45291. defines.ALBEDO = false;
  45292. }
  45293. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45295. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45296. }
  45297. else {
  45298. defines.AMBIENT = false;
  45299. }
  45300. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45302. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45303. }
  45304. else {
  45305. defines.OPACITY = false;
  45306. }
  45307. var reflectionTexture = this._getReflectionTexture();
  45308. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45309. defines.REFLECTION = true;
  45310. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45311. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45312. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45313. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45314. defines.INVERTCUBICMAP = true;
  45315. }
  45316. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45317. switch (reflectionTexture.coordinatesMode) {
  45318. case BABYLON.Texture.EXPLICIT_MODE:
  45319. defines.REFLECTIONMAP_EXPLICIT = true;
  45320. break;
  45321. case BABYLON.Texture.PLANAR_MODE:
  45322. defines.REFLECTIONMAP_PLANAR = true;
  45323. break;
  45324. case BABYLON.Texture.PROJECTION_MODE:
  45325. defines.REFLECTIONMAP_PROJECTION = true;
  45326. break;
  45327. case BABYLON.Texture.SKYBOX_MODE:
  45328. defines.REFLECTIONMAP_SKYBOX = true;
  45329. break;
  45330. case BABYLON.Texture.SPHERICAL_MODE:
  45331. defines.REFLECTIONMAP_SPHERICAL = true;
  45332. break;
  45333. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45334. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45335. break;
  45336. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45337. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45338. break;
  45339. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45340. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45341. break;
  45342. case BABYLON.Texture.CUBIC_MODE:
  45343. case BABYLON.Texture.INVCUBIC_MODE:
  45344. default:
  45345. defines.REFLECTIONMAP_CUBIC = true;
  45346. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45347. break;
  45348. }
  45349. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45350. if (reflectionTexture.sphericalPolynomial) {
  45351. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45352. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45353. defines.USESPHERICALINVERTEX = false;
  45354. }
  45355. else {
  45356. defines.USESPHERICALINVERTEX = true;
  45357. }
  45358. }
  45359. }
  45360. }
  45361. else {
  45362. defines.REFLECTION = false;
  45363. defines.REFLECTIONMAP_3D = false;
  45364. defines.REFLECTIONMAP_SPHERICAL = false;
  45365. defines.REFLECTIONMAP_PLANAR = false;
  45366. defines.REFLECTIONMAP_CUBIC = false;
  45367. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45368. defines.REFLECTIONMAP_PROJECTION = false;
  45369. defines.REFLECTIONMAP_SKYBOX = false;
  45370. defines.REFLECTIONMAP_EXPLICIT = false;
  45371. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45372. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45373. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45374. defines.INVERTCUBICMAP = false;
  45375. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45376. defines.USESPHERICALINVERTEX = false;
  45377. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45378. defines.LODINREFLECTIONALPHA = false;
  45379. defines.GAMMAREFLECTION = false;
  45380. }
  45381. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45383. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45384. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45385. }
  45386. else {
  45387. defines.LIGHTMAP = false;
  45388. }
  45389. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45390. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45391. }
  45392. else {
  45393. defines.EMISSIVE = false;
  45394. }
  45395. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45396. if (this._metallicTexture) {
  45397. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45398. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45399. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45400. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45401. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45402. }
  45403. else if (this._reflectivityTexture) {
  45404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45405. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45406. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45407. }
  45408. else {
  45409. defines.REFLECTIVITY = false;
  45410. }
  45411. if (this._microSurfaceTexture) {
  45412. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45413. }
  45414. else {
  45415. defines.MICROSURFACEMAP = false;
  45416. }
  45417. }
  45418. else {
  45419. defines.REFLECTIVITY = false;
  45420. defines.MICROSURFACEMAP = false;
  45421. }
  45422. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45423. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45424. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45425. defines.PARALLAX = true;
  45426. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45427. }
  45428. else {
  45429. defines.PARALLAX = false;
  45430. }
  45431. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45432. }
  45433. else {
  45434. defines.BUMP = false;
  45435. }
  45436. var refractionTexture = this._getRefractionTexture();
  45437. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45438. defines.REFRACTION = true;
  45439. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45440. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45441. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45442. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45443. if (this._linkRefractionWithTransparency) {
  45444. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45445. }
  45446. }
  45447. else {
  45448. defines.REFRACTION = false;
  45449. }
  45450. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45451. defines.ENVIRONMENTBRDF = true;
  45452. }
  45453. else {
  45454. defines.ENVIRONMENTBRDF = false;
  45455. }
  45456. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45457. defines.ALPHAFROMALBEDO = true;
  45458. }
  45459. else {
  45460. defines.ALPHAFROMALBEDO = false;
  45461. }
  45462. }
  45463. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45464. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45465. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45466. if (!this.backFaceCulling && this._twoSidedLighting) {
  45467. defines.TWOSIDEDLIGHTING = true;
  45468. }
  45469. else {
  45470. defines.TWOSIDEDLIGHTING = false;
  45471. }
  45472. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45473. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45474. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45475. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45476. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45477. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45478. }
  45479. if (defines._areImageProcessingDirty) {
  45480. this._imageProcessingConfiguration.prepareDefines(defines);
  45481. }
  45482. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45483. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45484. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45485. // Misc.
  45486. if (defines._areMiscDirty) {
  45487. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45488. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45489. }
  45490. // Values that need to be evaluated on every frame
  45491. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45492. // Attribs
  45493. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45494. };
  45495. /**
  45496. * Force shader compilation
  45497. */
  45498. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45499. var _this = this;
  45500. var localOptions = __assign({ clipPlane: false }, options);
  45501. var defines = new PBRMaterialDefines();
  45502. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45503. if (effect.isReady()) {
  45504. if (onCompiled) {
  45505. onCompiled(this);
  45506. }
  45507. }
  45508. else {
  45509. effect.onCompileObservable.add(function () {
  45510. if (onCompiled) {
  45511. onCompiled(_this);
  45512. }
  45513. });
  45514. }
  45515. };
  45516. /**
  45517. * Initializes the uniform buffer layout for the shader.
  45518. */
  45519. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45520. // Order is important !
  45521. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45522. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45523. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45524. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45525. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45526. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45527. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45528. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45529. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45530. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45531. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45532. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45533. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45534. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45535. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45536. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45537. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45538. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45539. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45540. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45541. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45542. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45543. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45544. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45545. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45546. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45547. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45548. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45549. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45550. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45551. this._uniformBuffer.addUniform("pointSize", 1);
  45552. this._uniformBuffer.create();
  45553. };
  45554. /**
  45555. * Unbinds the textures.
  45556. */
  45557. PBRBaseMaterial.prototype.unbind = function () {
  45558. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45559. this._uniformBuffer.setTexture("reflectionSampler", null);
  45560. }
  45561. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45562. this._uniformBuffer.setTexture("refractionSampler", null);
  45563. }
  45564. _super.prototype.unbind.call(this);
  45565. };
  45566. /**
  45567. * Binds the submesh data.
  45568. * @param world - The world matrix.
  45569. * @param mesh - The BJS mesh.
  45570. * @param subMesh - A submesh of the BJS mesh.
  45571. */
  45572. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45573. var scene = this.getScene();
  45574. var defines = subMesh._materialDefines;
  45575. if (!defines) {
  45576. return;
  45577. }
  45578. var effect = subMesh.effect;
  45579. if (!effect) {
  45580. return;
  45581. }
  45582. this._activeEffect = effect;
  45583. // Matrices
  45584. this.bindOnlyWorldMatrix(world);
  45585. // Normal Matrix
  45586. if (defines.OBJECTSPACE_NORMALMAP) {
  45587. world.toNormalMatrix(this._normalMatrix);
  45588. this.bindOnlyNormalMatrix(this._normalMatrix);
  45589. }
  45590. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45591. // Bones
  45592. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45593. var reflectionTexture = null;
  45594. if (mustRebind) {
  45595. this._uniformBuffer.bindToEffect(effect, "Material");
  45596. this.bindViewProjection(effect);
  45597. reflectionTexture = this._getReflectionTexture();
  45598. var refractionTexture = this._getRefractionTexture();
  45599. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45600. // Texture uniforms
  45601. if (scene.texturesEnabled) {
  45602. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45603. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45604. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45605. }
  45606. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45607. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45608. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45609. }
  45610. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45611. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45612. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45613. }
  45614. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45615. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45616. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45617. if (reflectionTexture.boundingBoxSize) {
  45618. var cubeTexture = reflectionTexture;
  45619. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45620. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45621. }
  45622. var polynomials = reflectionTexture.sphericalPolynomial;
  45623. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45624. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45625. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45626. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45627. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45628. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45629. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45630. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45631. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45632. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45633. }
  45634. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45635. }
  45636. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45637. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45638. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45639. }
  45640. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45641. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45642. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45643. }
  45644. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45645. if (this._metallicTexture) {
  45646. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45647. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45648. }
  45649. else if (this._reflectivityTexture) {
  45650. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45651. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45652. }
  45653. if (this._microSurfaceTexture) {
  45654. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45655. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45656. }
  45657. }
  45658. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45659. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45660. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45661. if (scene._mirroredCameraPosition) {
  45662. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45663. }
  45664. else {
  45665. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45666. }
  45667. }
  45668. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45669. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45670. var depth = 1.0;
  45671. if (!refractionTexture.isCube) {
  45672. if (refractionTexture.depth) {
  45673. depth = refractionTexture.depth;
  45674. }
  45675. }
  45676. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45677. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45678. }
  45679. }
  45680. // Point size
  45681. if (this.pointsCloud) {
  45682. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45683. }
  45684. // Colors
  45685. if (defines.METALLICWORKFLOW) {
  45686. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45687. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45688. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45689. }
  45690. else {
  45691. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45692. }
  45693. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45694. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45695. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45696. // Misc
  45697. this._lightingInfos.x = this._directIntensity;
  45698. this._lightingInfos.y = this._emissiveIntensity;
  45699. this._lightingInfos.z = this._environmentIntensity;
  45700. this._lightingInfos.w = this._specularIntensity;
  45701. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45702. }
  45703. // Textures
  45704. if (scene.texturesEnabled) {
  45705. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45706. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45707. }
  45708. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45709. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45710. }
  45711. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45712. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45713. }
  45714. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45715. if (defines.LODBASEDMICROSFURACE) {
  45716. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45717. }
  45718. else {
  45719. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45720. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45721. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45722. }
  45723. }
  45724. if (defines.ENVIRONMENTBRDF) {
  45725. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45726. }
  45727. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45728. if (defines.LODBASEDMICROSFURACE) {
  45729. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45730. }
  45731. else {
  45732. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45733. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45734. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45735. }
  45736. }
  45737. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45738. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45739. }
  45740. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45741. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45742. }
  45743. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45744. if (this._metallicTexture) {
  45745. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45746. }
  45747. else if (this._reflectivityTexture) {
  45748. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45749. }
  45750. if (this._microSurfaceTexture) {
  45751. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45752. }
  45753. }
  45754. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45755. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45756. }
  45757. }
  45758. // Clip plane
  45759. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45760. // Colors
  45761. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45762. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45763. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45764. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45765. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45766. }
  45767. if (mustRebind || !this.isFrozen) {
  45768. // Lights
  45769. if (scene.lightsEnabled && !this._disableLighting) {
  45770. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45771. }
  45772. // View
  45773. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45774. this.bindView(effect);
  45775. }
  45776. // Fog
  45777. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45778. // Morph targets
  45779. if (defines.NUM_MORPH_INFLUENCERS) {
  45780. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45781. }
  45782. // image processing
  45783. this._imageProcessingConfiguration.bind(this._activeEffect);
  45784. // Log. depth
  45785. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45786. }
  45787. this._uniformBuffer.update();
  45788. this._afterBind(mesh, this._activeEffect);
  45789. };
  45790. /**
  45791. * Returns the animatable textures.
  45792. * @returns - Array of animatable textures.
  45793. */
  45794. PBRBaseMaterial.prototype.getAnimatables = function () {
  45795. var results = [];
  45796. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45797. results.push(this._albedoTexture);
  45798. }
  45799. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45800. results.push(this._ambientTexture);
  45801. }
  45802. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45803. results.push(this._opacityTexture);
  45804. }
  45805. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45806. results.push(this._reflectionTexture);
  45807. }
  45808. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45809. results.push(this._emissiveTexture);
  45810. }
  45811. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45812. results.push(this._metallicTexture);
  45813. }
  45814. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45815. results.push(this._reflectivityTexture);
  45816. }
  45817. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45818. results.push(this._bumpTexture);
  45819. }
  45820. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45821. results.push(this._lightmapTexture);
  45822. }
  45823. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45824. results.push(this._refractionTexture);
  45825. }
  45826. return results;
  45827. };
  45828. /**
  45829. * Returns the texture used for reflections.
  45830. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45831. */
  45832. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45833. if (this._reflectionTexture) {
  45834. return this._reflectionTexture;
  45835. }
  45836. return this.getScene().environmentTexture;
  45837. };
  45838. /**
  45839. * Returns the texture used for refraction or null if none is used.
  45840. * @returns - Refection texture if present. If no refraction texture and refraction
  45841. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45842. */
  45843. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45844. if (this._refractionTexture) {
  45845. return this._refractionTexture;
  45846. }
  45847. if (this._linkRefractionWithTransparency) {
  45848. return this.getScene().environmentTexture;
  45849. }
  45850. return null;
  45851. };
  45852. /**
  45853. * Disposes the resources of the material.
  45854. * @param forceDisposeEffect - Forces the disposal of effects.
  45855. * @param forceDisposeTextures - Forces the disposal of all textures.
  45856. */
  45857. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45858. if (forceDisposeTextures) {
  45859. if (this._albedoTexture) {
  45860. this._albedoTexture.dispose();
  45861. }
  45862. if (this._ambientTexture) {
  45863. this._ambientTexture.dispose();
  45864. }
  45865. if (this._opacityTexture) {
  45866. this._opacityTexture.dispose();
  45867. }
  45868. if (this._reflectionTexture) {
  45869. this._reflectionTexture.dispose();
  45870. }
  45871. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45872. this._environmentBRDFTexture.dispose();
  45873. }
  45874. if (this._emissiveTexture) {
  45875. this._emissiveTexture.dispose();
  45876. }
  45877. if (this._metallicTexture) {
  45878. this._metallicTexture.dispose();
  45879. }
  45880. if (this._reflectivityTexture) {
  45881. this._reflectivityTexture.dispose();
  45882. }
  45883. if (this._bumpTexture) {
  45884. this._bumpTexture.dispose();
  45885. }
  45886. if (this._lightmapTexture) {
  45887. this._lightmapTexture.dispose();
  45888. }
  45889. if (this._refractionTexture) {
  45890. this._refractionTexture.dispose();
  45891. }
  45892. }
  45893. this._renderTargets.dispose();
  45894. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45895. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45896. }
  45897. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45898. };
  45899. /**
  45900. * Stores the reflectivity values based on metallic roughness workflow.
  45901. */
  45902. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45903. __decorate([
  45904. BABYLON.serializeAsImageProcessingConfiguration()
  45905. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45906. __decorate([
  45907. BABYLON.serialize()
  45908. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45909. __decorate([
  45910. BABYLON.serialize()
  45911. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45912. return PBRBaseMaterial;
  45913. }(BABYLON.PushMaterial));
  45914. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45915. })(BABYLON || (BABYLON = {}));
  45916. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45917. var BABYLON;
  45918. (function (BABYLON) {
  45919. /**
  45920. * The Physically based simple base material of BJS.
  45921. *
  45922. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45923. * It is used as the base class for both the specGloss and metalRough conventions.
  45924. */
  45925. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45926. __extends(PBRBaseSimpleMaterial, _super);
  45927. /**
  45928. * Instantiates a new PBRMaterial instance.
  45929. *
  45930. * @param name The material name
  45931. * @param scene The scene the material will be use in.
  45932. */
  45933. function PBRBaseSimpleMaterial(name, scene) {
  45934. var _this = _super.call(this, name, scene) || this;
  45935. /**
  45936. * Number of Simultaneous lights allowed on the material.
  45937. */
  45938. _this.maxSimultaneousLights = 4;
  45939. /**
  45940. * If sets to true, disables all the lights affecting the material.
  45941. */
  45942. _this.disableLighting = false;
  45943. /**
  45944. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45945. */
  45946. _this.invertNormalMapX = false;
  45947. /**
  45948. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45949. */
  45950. _this.invertNormalMapY = false;
  45951. /**
  45952. * Emissivie color used to self-illuminate the model.
  45953. */
  45954. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45955. /**
  45956. * Occlusion Channel Strenght.
  45957. */
  45958. _this.occlusionStrength = 1.0;
  45959. _this.useLightmapAsShadowmap = false;
  45960. _this._useAlphaFromAlbedoTexture = true;
  45961. _this._useAmbientInGrayScale = true;
  45962. return _this;
  45963. }
  45964. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45965. /**
  45966. * Gets the current double sided mode.
  45967. */
  45968. get: function () {
  45969. return this._twoSidedLighting;
  45970. },
  45971. /**
  45972. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45973. */
  45974. set: function (value) {
  45975. if (this._twoSidedLighting === value) {
  45976. return;
  45977. }
  45978. this._twoSidedLighting = value;
  45979. this.backFaceCulling = !value;
  45980. this._markAllSubMeshesAsTexturesDirty();
  45981. },
  45982. enumerable: true,
  45983. configurable: true
  45984. });
  45985. /**
  45986. * Return the active textures of the material.
  45987. */
  45988. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45989. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45990. if (this.environmentTexture) {
  45991. activeTextures.push(this.environmentTexture);
  45992. }
  45993. if (this.normalTexture) {
  45994. activeTextures.push(this.normalTexture);
  45995. }
  45996. if (this.emissiveTexture) {
  45997. activeTextures.push(this.emissiveTexture);
  45998. }
  45999. if (this.occlusionTexture) {
  46000. activeTextures.push(this.occlusionTexture);
  46001. }
  46002. if (this.lightmapTexture) {
  46003. activeTextures.push(this.lightmapTexture);
  46004. }
  46005. return activeTextures;
  46006. };
  46007. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46008. if (_super.prototype.hasTexture.call(this, texture)) {
  46009. return true;
  46010. }
  46011. if (this.lightmapTexture === texture) {
  46012. return true;
  46013. }
  46014. return false;
  46015. };
  46016. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46017. return "PBRBaseSimpleMaterial";
  46018. };
  46019. __decorate([
  46020. BABYLON.serialize(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46022. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46023. __decorate([
  46024. BABYLON.serialize(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46026. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46027. __decorate([
  46028. BABYLON.serializeAsTexture(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46030. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46031. __decorate([
  46032. BABYLON.serialize(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46034. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46035. __decorate([
  46036. BABYLON.serialize(),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46038. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46039. __decorate([
  46040. BABYLON.serializeAsTexture(),
  46041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46042. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46043. __decorate([
  46044. BABYLON.serializeAsColor3("emissive"),
  46045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46046. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46047. __decorate([
  46048. BABYLON.serializeAsTexture(),
  46049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46050. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46051. __decorate([
  46052. BABYLON.serialize(),
  46053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46054. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46055. __decorate([
  46056. BABYLON.serializeAsTexture(),
  46057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46058. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46059. __decorate([
  46060. BABYLON.serialize(),
  46061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46062. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46063. __decorate([
  46064. BABYLON.serialize()
  46065. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46066. __decorate([
  46067. BABYLON.serializeAsTexture(),
  46068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46069. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46070. __decorate([
  46071. BABYLON.serialize(),
  46072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46073. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46074. return PBRBaseSimpleMaterial;
  46075. }(BABYLON.PBRBaseMaterial));
  46076. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46077. })(BABYLON || (BABYLON = {}));
  46078. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46079. var BABYLON;
  46080. (function (BABYLON) {
  46081. /**
  46082. * The Physically based material of BJS.
  46083. *
  46084. * This offers the main features of a standard PBR material.
  46085. * For more information, please refer to the documentation :
  46086. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46087. */
  46088. var PBRMaterial = /** @class */ (function (_super) {
  46089. __extends(PBRMaterial, _super);
  46090. /**
  46091. * Instantiates a new PBRMaterial instance.
  46092. *
  46093. * @param name The material name
  46094. * @param scene The scene the material will be use in.
  46095. */
  46096. function PBRMaterial(name, scene) {
  46097. var _this = _super.call(this, name, scene) || this;
  46098. /**
  46099. * Intensity of the direct lights e.g. the four lights available in your scene.
  46100. * This impacts both the direct diffuse and specular highlights.
  46101. */
  46102. _this.directIntensity = 1.0;
  46103. /**
  46104. * Intensity of the emissive part of the material.
  46105. * This helps controlling the emissive effect without modifying the emissive color.
  46106. */
  46107. _this.emissiveIntensity = 1.0;
  46108. /**
  46109. * Intensity of the environment e.g. how much the environment will light the object
  46110. * either through harmonics for rough material or through the refelction for shiny ones.
  46111. */
  46112. _this.environmentIntensity = 1.0;
  46113. /**
  46114. * This is a special control allowing the reduction of the specular highlights coming from the
  46115. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46116. */
  46117. _this.specularIntensity = 1.0;
  46118. /**
  46119. * Debug Control allowing disabling the bump map on this material.
  46120. */
  46121. _this.disableBumpMap = false;
  46122. /**
  46123. * AKA Occlusion Texture Intensity in other nomenclature.
  46124. */
  46125. _this.ambientTextureStrength = 1.0;
  46126. /**
  46127. * The color of a material in ambient lighting.
  46128. */
  46129. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46130. /**
  46131. * AKA Diffuse Color in other nomenclature.
  46132. */
  46133. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46134. /**
  46135. * AKA Specular Color in other nomenclature.
  46136. */
  46137. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46138. /**
  46139. * The color reflected from the material.
  46140. */
  46141. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46142. /**
  46143. * The color emitted from the material.
  46144. */
  46145. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46146. /**
  46147. * AKA Glossiness in other nomenclature.
  46148. */
  46149. _this.microSurface = 1.0;
  46150. /**
  46151. * source material index of refraction (IOR)' / 'destination material IOR.
  46152. */
  46153. _this.indexOfRefraction = 0.66;
  46154. /**
  46155. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46156. */
  46157. _this.invertRefractionY = false;
  46158. /**
  46159. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46160. * Materials half opaque for instance using refraction could benefit from this control.
  46161. */
  46162. _this.linkRefractionWithTransparency = false;
  46163. _this.useLightmapAsShadowmap = false;
  46164. /**
  46165. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46166. */
  46167. _this.useAlphaFromAlbedoTexture = false;
  46168. /**
  46169. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46170. */
  46171. _this.forceAlphaTest = false;
  46172. /**
  46173. * Defines the alpha limits in alpha test mode.
  46174. */
  46175. _this.alphaCutOff = 0.4;
  46176. /**
  46177. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46178. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46179. */
  46180. _this.useSpecularOverAlpha = true;
  46181. /**
  46182. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46183. */
  46184. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46185. /**
  46186. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46187. */
  46188. _this.useRoughnessFromMetallicTextureAlpha = true;
  46189. /**
  46190. * Specifies if the metallic texture contains the roughness information in its green channel.
  46191. */
  46192. _this.useRoughnessFromMetallicTextureGreen = false;
  46193. /**
  46194. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46195. */
  46196. _this.useMetallnessFromMetallicTextureBlue = false;
  46197. /**
  46198. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46199. */
  46200. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46201. /**
  46202. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46203. */
  46204. _this.useAmbientInGrayScale = false;
  46205. /**
  46206. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46207. * The material will try to infer what glossiness each pixel should be.
  46208. */
  46209. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46210. /**
  46211. * BJS is using an harcoded light falloff based on a manually sets up range.
  46212. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46213. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46214. */
  46215. _this.usePhysicalLightFalloff = true;
  46216. /**
  46217. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46218. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46219. */
  46220. _this.useRadianceOverAlpha = true;
  46221. /**
  46222. * Allows using an object space normal map (instead of tangent space).
  46223. */
  46224. _this.useObjectSpaceNormalMap = false;
  46225. /**
  46226. * Allows using the bump map in parallax mode.
  46227. */
  46228. _this.useParallax = false;
  46229. /**
  46230. * Allows using the bump map in parallax occlusion mode.
  46231. */
  46232. _this.useParallaxOcclusion = false;
  46233. /**
  46234. * Controls the scale bias of the parallax mode.
  46235. */
  46236. _this.parallaxScaleBias = 0.05;
  46237. /**
  46238. * If sets to true, disables all the lights affecting the material.
  46239. */
  46240. _this.disableLighting = false;
  46241. /**
  46242. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46243. */
  46244. _this.forceIrradianceInFragment = false;
  46245. /**
  46246. * Number of Simultaneous lights allowed on the material.
  46247. */
  46248. _this.maxSimultaneousLights = 4;
  46249. /**
  46250. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46251. */
  46252. _this.invertNormalMapX = false;
  46253. /**
  46254. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46255. */
  46256. _this.invertNormalMapY = false;
  46257. /**
  46258. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46259. */
  46260. _this.twoSidedLighting = false;
  46261. /**
  46262. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46263. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46264. */
  46265. _this.useAlphaFresnel = false;
  46266. /**
  46267. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46268. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46269. */
  46270. _this.useLinearAlphaFresnel = false;
  46271. /**
  46272. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46273. * And/Or occlude the blended part.
  46274. */
  46275. _this.environmentBRDFTexture = null;
  46276. /**
  46277. * Force normal to face away from face.
  46278. */
  46279. _this.forceNormalForward = false;
  46280. /**
  46281. * Enables specular anti aliasing in the PBR shader.
  46282. * It will both interacts on the Geometry for analytical and IBL lighting.
  46283. * It also prefilter the roughness map based on the bump values.
  46284. */
  46285. _this.enableSpecularAntiAliasing = false;
  46286. /**
  46287. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46288. * makes the reflect vector face the model (under horizon).
  46289. */
  46290. _this.useHorizonOcclusion = true;
  46291. /**
  46292. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46293. * too much the area relying on ambient texture to define their ambient occlusion.
  46294. */
  46295. _this.useRadianceOcclusion = true;
  46296. /**
  46297. * If set to true, no lighting calculations will be applied.
  46298. */
  46299. _this.unlit = false;
  46300. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46301. return _this;
  46302. }
  46303. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46304. /**
  46305. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46306. */
  46307. get: function () {
  46308. return this._PBRMATERIAL_OPAQUE;
  46309. },
  46310. enumerable: true,
  46311. configurable: true
  46312. });
  46313. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46314. /**
  46315. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46316. */
  46317. get: function () {
  46318. return this._PBRMATERIAL_ALPHATEST;
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46324. /**
  46325. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46326. */
  46327. get: function () {
  46328. return this._PBRMATERIAL_ALPHABLEND;
  46329. },
  46330. enumerable: true,
  46331. configurable: true
  46332. });
  46333. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46334. /**
  46335. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46336. * They are also discarded below the alpha cutoff threshold to improve performances.
  46337. */
  46338. get: function () {
  46339. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46340. },
  46341. enumerable: true,
  46342. configurable: true
  46343. });
  46344. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46345. /**
  46346. * Gets the image processing configuration used either in this material.
  46347. */
  46348. get: function () {
  46349. return this._imageProcessingConfiguration;
  46350. },
  46351. /**
  46352. * Sets the Default image processing configuration used either in the this material.
  46353. *
  46354. * If sets to null, the scene one is in use.
  46355. */
  46356. set: function (value) {
  46357. this._attachImageProcessingConfiguration(value);
  46358. // Ensure the effect will be rebuilt.
  46359. this._markAllSubMeshesAsTexturesDirty();
  46360. },
  46361. enumerable: true,
  46362. configurable: true
  46363. });
  46364. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46365. /**
  46366. * Gets wether the color curves effect is enabled.
  46367. */
  46368. get: function () {
  46369. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46370. },
  46371. /**
  46372. * Sets wether the color curves effect is enabled.
  46373. */
  46374. set: function (value) {
  46375. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46376. },
  46377. enumerable: true,
  46378. configurable: true
  46379. });
  46380. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46381. /**
  46382. * Gets wether the color grading effect is enabled.
  46383. */
  46384. get: function () {
  46385. return this.imageProcessingConfiguration.colorGradingEnabled;
  46386. },
  46387. /**
  46388. * Gets wether the color grading effect is enabled.
  46389. */
  46390. set: function (value) {
  46391. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46397. /**
  46398. * Gets wether tonemapping is enabled or not.
  46399. */
  46400. get: function () {
  46401. return this._imageProcessingConfiguration.toneMappingEnabled;
  46402. },
  46403. /**
  46404. * Sets wether tonemapping is enabled or not
  46405. */
  46406. set: function (value) {
  46407. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46408. },
  46409. enumerable: true,
  46410. configurable: true
  46411. });
  46412. ;
  46413. ;
  46414. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46415. /**
  46416. * The camera exposure used on this material.
  46417. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46418. * This corresponds to a photographic exposure.
  46419. */
  46420. get: function () {
  46421. return this._imageProcessingConfiguration.exposure;
  46422. },
  46423. /**
  46424. * The camera exposure used on this material.
  46425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46426. * This corresponds to a photographic exposure.
  46427. */
  46428. set: function (value) {
  46429. this._imageProcessingConfiguration.exposure = value;
  46430. },
  46431. enumerable: true,
  46432. configurable: true
  46433. });
  46434. ;
  46435. ;
  46436. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46437. /**
  46438. * Gets The camera contrast used on this material.
  46439. */
  46440. get: function () {
  46441. return this._imageProcessingConfiguration.contrast;
  46442. },
  46443. /**
  46444. * Sets The camera contrast used on this material.
  46445. */
  46446. set: function (value) {
  46447. this._imageProcessingConfiguration.contrast = value;
  46448. },
  46449. enumerable: true,
  46450. configurable: true
  46451. });
  46452. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46453. /**
  46454. * Gets the Color Grading 2D Lookup Texture.
  46455. */
  46456. get: function () {
  46457. return this._imageProcessingConfiguration.colorGradingTexture;
  46458. },
  46459. /**
  46460. * Sets the Color Grading 2D Lookup Texture.
  46461. */
  46462. set: function (value) {
  46463. this._imageProcessingConfiguration.colorGradingTexture = value;
  46464. },
  46465. enumerable: true,
  46466. configurable: true
  46467. });
  46468. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46469. /**
  46470. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46471. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46472. * 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;
  46473. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46474. */
  46475. get: function () {
  46476. return this._imageProcessingConfiguration.colorCurves;
  46477. },
  46478. /**
  46479. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46480. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46481. * 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;
  46482. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46483. */
  46484. set: function (value) {
  46485. this._imageProcessingConfiguration.colorCurves = value;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. /**
  46491. * Returns the name of this material class.
  46492. */
  46493. PBRMaterial.prototype.getClassName = function () {
  46494. return "PBRMaterial";
  46495. };
  46496. /**
  46497. * Returns an array of the actively used textures.
  46498. * @returns - Array of BaseTextures
  46499. */
  46500. PBRMaterial.prototype.getActiveTextures = function () {
  46501. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46502. if (this._albedoTexture) {
  46503. activeTextures.push(this._albedoTexture);
  46504. }
  46505. if (this._ambientTexture) {
  46506. activeTextures.push(this._ambientTexture);
  46507. }
  46508. if (this._opacityTexture) {
  46509. activeTextures.push(this._opacityTexture);
  46510. }
  46511. if (this._reflectionTexture) {
  46512. activeTextures.push(this._reflectionTexture);
  46513. }
  46514. if (this._emissiveTexture) {
  46515. activeTextures.push(this._emissiveTexture);
  46516. }
  46517. if (this._reflectivityTexture) {
  46518. activeTextures.push(this._reflectivityTexture);
  46519. }
  46520. if (this._metallicTexture) {
  46521. activeTextures.push(this._metallicTexture);
  46522. }
  46523. if (this._microSurfaceTexture) {
  46524. activeTextures.push(this._microSurfaceTexture);
  46525. }
  46526. if (this._bumpTexture) {
  46527. activeTextures.push(this._bumpTexture);
  46528. }
  46529. if (this._lightmapTexture) {
  46530. activeTextures.push(this._lightmapTexture);
  46531. }
  46532. if (this._refractionTexture) {
  46533. activeTextures.push(this._refractionTexture);
  46534. }
  46535. return activeTextures;
  46536. };
  46537. /**
  46538. * Checks to see if a texture is used in the material.
  46539. * @param texture - Base texture to use.
  46540. * @returns - Boolean specifying if a texture is used in the material.
  46541. */
  46542. PBRMaterial.prototype.hasTexture = function (texture) {
  46543. if (_super.prototype.hasTexture.call(this, texture)) {
  46544. return true;
  46545. }
  46546. if (this._albedoTexture === texture) {
  46547. return true;
  46548. }
  46549. if (this._ambientTexture === texture) {
  46550. return true;
  46551. }
  46552. if (this._opacityTexture === texture) {
  46553. return true;
  46554. }
  46555. if (this._reflectionTexture === texture) {
  46556. return true;
  46557. }
  46558. if (this._reflectivityTexture === texture) {
  46559. return true;
  46560. }
  46561. if (this._metallicTexture === texture) {
  46562. return true;
  46563. }
  46564. if (this._microSurfaceTexture === texture) {
  46565. return true;
  46566. }
  46567. if (this._bumpTexture === texture) {
  46568. return true;
  46569. }
  46570. if (this._lightmapTexture === texture) {
  46571. return true;
  46572. }
  46573. if (this._refractionTexture === texture) {
  46574. return true;
  46575. }
  46576. return false;
  46577. };
  46578. /**
  46579. * Makes a duplicate of the current material.
  46580. * @param name - name to use for the new material.
  46581. */
  46582. PBRMaterial.prototype.clone = function (name) {
  46583. var _this = this;
  46584. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46585. clone.id = name;
  46586. clone.name = name;
  46587. return clone;
  46588. };
  46589. /**
  46590. * Serializes this PBR Material.
  46591. * @returns - An object with the serialized material.
  46592. */
  46593. PBRMaterial.prototype.serialize = function () {
  46594. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46595. serializationObject.customType = "BABYLON.PBRMaterial";
  46596. return serializationObject;
  46597. };
  46598. // Statics
  46599. /**
  46600. * Parses a PBR Material from a serialized object.
  46601. * @param source - Serialized object.
  46602. * @param scene - BJS scene instance.
  46603. * @param rootUrl - url for the scene object
  46604. * @returns - PBRMaterial
  46605. */
  46606. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46607. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46608. };
  46609. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46610. /**
  46611. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46612. */
  46613. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46614. /**
  46615. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46616. */
  46617. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46618. /**
  46619. * 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.
  46620. * They are also discarded below the alpha cutoff threshold to improve performances.
  46621. */
  46622. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46623. __decorate([
  46624. BABYLON.serialize(),
  46625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46626. ], PBRMaterial.prototype, "directIntensity", void 0);
  46627. __decorate([
  46628. BABYLON.serialize(),
  46629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46630. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46631. __decorate([
  46632. BABYLON.serialize(),
  46633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46634. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46635. __decorate([
  46636. BABYLON.serialize(),
  46637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46638. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46639. __decorate([
  46640. BABYLON.serialize(),
  46641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46642. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46643. __decorate([
  46644. BABYLON.serializeAsTexture(),
  46645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46646. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46647. __decorate([
  46648. BABYLON.serializeAsTexture(),
  46649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46650. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46651. __decorate([
  46652. BABYLON.serialize(),
  46653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46654. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46655. __decorate([
  46656. BABYLON.serializeAsTexture(),
  46657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46658. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46659. __decorate([
  46660. BABYLON.serializeAsTexture(),
  46661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46662. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46663. __decorate([
  46664. BABYLON.serializeAsTexture(),
  46665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46666. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46667. __decorate([
  46668. BABYLON.serializeAsTexture(),
  46669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46670. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46671. __decorate([
  46672. BABYLON.serializeAsTexture(),
  46673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46674. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46675. __decorate([
  46676. BABYLON.serialize(),
  46677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46678. ], PBRMaterial.prototype, "metallic", void 0);
  46679. __decorate([
  46680. BABYLON.serialize(),
  46681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46682. ], PBRMaterial.prototype, "roughness", void 0);
  46683. __decorate([
  46684. BABYLON.serializeAsTexture(),
  46685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46686. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46687. __decorate([
  46688. BABYLON.serializeAsTexture(),
  46689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46690. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46691. __decorate([
  46692. BABYLON.serializeAsTexture(),
  46693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46694. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46695. __decorate([
  46696. BABYLON.serializeAsTexture(),
  46697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46698. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46699. __decorate([
  46700. BABYLON.serializeAsColor3("ambient"),
  46701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46702. ], PBRMaterial.prototype, "ambientColor", void 0);
  46703. __decorate([
  46704. BABYLON.serializeAsColor3("albedo"),
  46705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46706. ], PBRMaterial.prototype, "albedoColor", void 0);
  46707. __decorate([
  46708. BABYLON.serializeAsColor3("reflectivity"),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46710. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46711. __decorate([
  46712. BABYLON.serializeAsColor3("reflection"),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46714. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46715. __decorate([
  46716. BABYLON.serializeAsColor3("emissive"),
  46717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46718. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46719. __decorate([
  46720. BABYLON.serialize(),
  46721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46722. ], PBRMaterial.prototype, "microSurface", void 0);
  46723. __decorate([
  46724. BABYLON.serialize(),
  46725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46726. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46727. __decorate([
  46728. BABYLON.serialize(),
  46729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46730. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46731. __decorate([
  46732. BABYLON.serialize(),
  46733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46734. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46735. __decorate([
  46736. BABYLON.serialize(),
  46737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46738. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46739. __decorate([
  46740. BABYLON.serialize(),
  46741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46742. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46743. __decorate([
  46744. BABYLON.serialize(),
  46745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46746. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46747. __decorate([
  46748. BABYLON.serialize(),
  46749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46750. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46751. __decorate([
  46752. BABYLON.serialize(),
  46753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46754. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46755. __decorate([
  46756. BABYLON.serialize(),
  46757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46758. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46759. __decorate([
  46760. BABYLON.serialize(),
  46761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46762. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46763. __decorate([
  46764. BABYLON.serialize(),
  46765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46766. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46767. __decorate([
  46768. BABYLON.serialize(),
  46769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46770. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46771. __decorate([
  46772. BABYLON.serialize(),
  46773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46774. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46775. __decorate([
  46776. BABYLON.serialize(),
  46777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46778. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46779. __decorate([
  46780. BABYLON.serialize(),
  46781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46782. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46783. __decorate([
  46784. BABYLON.serialize(),
  46785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46786. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46787. __decorate([
  46788. BABYLON.serialize(),
  46789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46790. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46791. __decorate([
  46792. BABYLON.serialize(),
  46793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46794. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46795. __decorate([
  46796. BABYLON.serialize(),
  46797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46798. ], PBRMaterial.prototype, "useParallax", void 0);
  46799. __decorate([
  46800. BABYLON.serialize(),
  46801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46802. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46803. __decorate([
  46804. BABYLON.serialize(),
  46805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46806. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46807. __decorate([
  46808. BABYLON.serialize(),
  46809. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46810. ], PBRMaterial.prototype, "disableLighting", void 0);
  46811. __decorate([
  46812. BABYLON.serialize(),
  46813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46814. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46815. __decorate([
  46816. BABYLON.serialize(),
  46817. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46818. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46819. __decorate([
  46820. BABYLON.serialize(),
  46821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46822. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46823. __decorate([
  46824. BABYLON.serialize(),
  46825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46826. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46827. __decorate([
  46828. BABYLON.serialize(),
  46829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46830. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46831. __decorate([
  46832. BABYLON.serialize(),
  46833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46834. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46835. __decorate([
  46836. BABYLON.serialize(),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46838. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46839. __decorate([
  46840. BABYLON.serializeAsTexture(),
  46841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46842. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46843. __decorate([
  46844. BABYLON.serialize(),
  46845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46846. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46847. __decorate([
  46848. BABYLON.serialize(),
  46849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46850. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46851. __decorate([
  46852. BABYLON.serialize(),
  46853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46854. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46855. __decorate([
  46856. BABYLON.serialize(),
  46857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46858. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46859. __decorate([
  46860. BABYLON.serialize(),
  46861. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46862. ], PBRMaterial.prototype, "unlit", void 0);
  46863. return PBRMaterial;
  46864. }(BABYLON.PBRBaseMaterial));
  46865. BABYLON.PBRMaterial = PBRMaterial;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. /**
  46871. * The PBR material of BJS following the metal roughness convention.
  46872. *
  46873. * This fits to the PBR convention in the GLTF definition:
  46874. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46875. */
  46876. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46877. __extends(PBRMetallicRoughnessMaterial, _super);
  46878. /**
  46879. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46880. *
  46881. * @param name The material name
  46882. * @param scene The scene the material will be use in.
  46883. */
  46884. function PBRMetallicRoughnessMaterial(name, scene) {
  46885. var _this = _super.call(this, name, scene) || this;
  46886. _this._useRoughnessFromMetallicTextureAlpha = false;
  46887. _this._useRoughnessFromMetallicTextureGreen = true;
  46888. _this._useMetallnessFromMetallicTextureBlue = true;
  46889. _this.metallic = 1.0;
  46890. _this.roughness = 1.0;
  46891. return _this;
  46892. }
  46893. /**
  46894. * Return the currrent class name of the material.
  46895. */
  46896. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46897. return "PBRMetallicRoughnessMaterial";
  46898. };
  46899. /**
  46900. * Return the active textures of the material.
  46901. */
  46902. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46903. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46904. if (this.baseTexture) {
  46905. activeTextures.push(this.baseTexture);
  46906. }
  46907. if (this.metallicRoughnessTexture) {
  46908. activeTextures.push(this.metallicRoughnessTexture);
  46909. }
  46910. return activeTextures;
  46911. };
  46912. /**
  46913. * Checks to see if a texture is used in the material.
  46914. * @param texture - Base texture to use.
  46915. * @returns - Boolean specifying if a texture is used in the material.
  46916. */
  46917. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46918. if (_super.prototype.hasTexture.call(this, texture)) {
  46919. return true;
  46920. }
  46921. if (this.baseTexture === texture) {
  46922. return true;
  46923. }
  46924. if (this.metallicRoughnessTexture === texture) {
  46925. return true;
  46926. }
  46927. return false;
  46928. };
  46929. /**
  46930. * Makes a duplicate of the current material.
  46931. * @param name - name to use for the new material.
  46932. */
  46933. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46934. var _this = this;
  46935. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46936. clone.id = name;
  46937. clone.name = name;
  46938. return clone;
  46939. };
  46940. /**
  46941. * Serialize the material to a parsable JSON object.
  46942. */
  46943. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46944. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46945. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46946. return serializationObject;
  46947. };
  46948. /**
  46949. * Parses a JSON object correponding to the serialize function.
  46950. */
  46951. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46952. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46953. };
  46954. __decorate([
  46955. BABYLON.serializeAsColor3(),
  46956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46957. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46958. __decorate([
  46959. BABYLON.serializeAsTexture(),
  46960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46961. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46962. __decorate([
  46963. BABYLON.serialize(),
  46964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46965. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46966. __decorate([
  46967. BABYLON.serialize(),
  46968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46969. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46970. __decorate([
  46971. BABYLON.serializeAsTexture(),
  46972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46973. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46974. return PBRMetallicRoughnessMaterial;
  46975. }(BABYLON.PBRBaseSimpleMaterial));
  46976. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46977. })(BABYLON || (BABYLON = {}));
  46978. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46979. var BABYLON;
  46980. (function (BABYLON) {
  46981. /**
  46982. * The PBR material of BJS following the specular glossiness convention.
  46983. *
  46984. * This fits to the PBR convention in the GLTF definition:
  46985. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46986. */
  46987. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46988. __extends(PBRSpecularGlossinessMaterial, _super);
  46989. /**
  46990. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46991. *
  46992. * @param name The material name
  46993. * @param scene The scene the material will be use in.
  46994. */
  46995. function PBRSpecularGlossinessMaterial(name, scene) {
  46996. var _this = _super.call(this, name, scene) || this;
  46997. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46998. return _this;
  46999. }
  47000. /**
  47001. * Return the currrent class name of the material.
  47002. */
  47003. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47004. return "PBRSpecularGlossinessMaterial";
  47005. };
  47006. /**
  47007. * Return the active textures of the material.
  47008. */
  47009. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47010. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47011. if (this.diffuseTexture) {
  47012. activeTextures.push(this.diffuseTexture);
  47013. }
  47014. if (this.specularGlossinessTexture) {
  47015. activeTextures.push(this.specularGlossinessTexture);
  47016. }
  47017. return activeTextures;
  47018. };
  47019. /**
  47020. * Checks to see if a texture is used in the material.
  47021. * @param texture - Base texture to use.
  47022. * @returns - Boolean specifying if a texture is used in the material.
  47023. */
  47024. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47025. if (_super.prototype.hasTexture.call(this, texture)) {
  47026. return true;
  47027. }
  47028. if (this.diffuseTexture === texture) {
  47029. return true;
  47030. }
  47031. if (this.specularGlossinessTexture === texture) {
  47032. return true;
  47033. }
  47034. return false;
  47035. };
  47036. /**
  47037. * Makes a duplicate of the current material.
  47038. * @param name - name to use for the new material.
  47039. */
  47040. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47041. var _this = this;
  47042. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47043. clone.id = name;
  47044. clone.name = name;
  47045. return clone;
  47046. };
  47047. /**
  47048. * Serialize the material to a parsable JSON object.
  47049. */
  47050. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47051. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47052. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47053. return serializationObject;
  47054. };
  47055. /**
  47056. * Parses a JSON object correponding to the serialize function.
  47057. */
  47058. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47059. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47060. };
  47061. __decorate([
  47062. BABYLON.serializeAsColor3("diffuse"),
  47063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47064. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47065. __decorate([
  47066. BABYLON.serializeAsTexture(),
  47067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47068. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47069. __decorate([
  47070. BABYLON.serializeAsColor3("specular"),
  47071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47072. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47073. __decorate([
  47074. BABYLON.serialize(),
  47075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47076. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47077. __decorate([
  47078. BABYLON.serializeAsTexture(),
  47079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47080. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47081. return PBRSpecularGlossinessMaterial;
  47082. }(BABYLON.PBRBaseSimpleMaterial));
  47083. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47084. })(BABYLON || (BABYLON = {}));
  47085. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47086. var BABYLON;
  47087. (function (BABYLON) {
  47088. BABYLON.CameraInputTypes = {};
  47089. var CameraInputsManager = /** @class */ (function () {
  47090. function CameraInputsManager(camera) {
  47091. this.attached = {};
  47092. this.camera = camera;
  47093. this.checkInputs = function () { };
  47094. }
  47095. /**
  47096. * Add an input method to a camera.
  47097. * builtin inputs example: camera.inputs.addGamepad();
  47098. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47099. * @param input camera input method
  47100. */
  47101. CameraInputsManager.prototype.add = function (input) {
  47102. var type = input.getSimpleName();
  47103. if (this.attached[type]) {
  47104. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47105. return;
  47106. }
  47107. this.attached[type] = input;
  47108. input.camera = this.camera;
  47109. //for checkInputs, we are dynamically creating a function
  47110. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47111. if (input.checkInputs) {
  47112. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47113. }
  47114. if (this.attachedElement) {
  47115. input.attachControl(this.attachedElement);
  47116. }
  47117. };
  47118. /**
  47119. * Remove a specific input method from a camera
  47120. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47121. * @param inputToRemove camera input method
  47122. */
  47123. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47124. for (var cam in this.attached) {
  47125. var input = this.attached[cam];
  47126. if (input === inputToRemove) {
  47127. input.detachControl(this.attachedElement);
  47128. input.camera = null;
  47129. delete this.attached[cam];
  47130. this.rebuildInputCheck();
  47131. }
  47132. }
  47133. };
  47134. CameraInputsManager.prototype.removeByType = function (inputType) {
  47135. for (var cam in this.attached) {
  47136. var input = this.attached[cam];
  47137. if (input.getClassName() === inputType) {
  47138. input.detachControl(this.attachedElement);
  47139. input.camera = null;
  47140. delete this.attached[cam];
  47141. this.rebuildInputCheck();
  47142. }
  47143. }
  47144. };
  47145. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47146. var current = this.checkInputs;
  47147. return function () {
  47148. current();
  47149. fn();
  47150. };
  47151. };
  47152. CameraInputsManager.prototype.attachInput = function (input) {
  47153. if (this.attachedElement) {
  47154. input.attachControl(this.attachedElement, this.noPreventDefault);
  47155. }
  47156. };
  47157. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47158. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47159. if (this.attachedElement) {
  47160. return;
  47161. }
  47162. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47163. this.attachedElement = element;
  47164. this.noPreventDefault = noPreventDefault;
  47165. for (var cam in this.attached) {
  47166. this.attached[cam].attachControl(element, noPreventDefault);
  47167. }
  47168. };
  47169. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47170. if (disconnect === void 0) { disconnect = false; }
  47171. if (this.attachedElement !== element) {
  47172. return;
  47173. }
  47174. for (var cam in this.attached) {
  47175. this.attached[cam].detachControl(element);
  47176. if (disconnect) {
  47177. this.attached[cam].camera = null;
  47178. }
  47179. }
  47180. this.attachedElement = null;
  47181. };
  47182. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47183. this.checkInputs = function () { };
  47184. for (var cam in this.attached) {
  47185. var input = this.attached[cam];
  47186. if (input.checkInputs) {
  47187. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47188. }
  47189. }
  47190. };
  47191. /**
  47192. * Remove all attached input methods from a camera
  47193. */
  47194. CameraInputsManager.prototype.clear = function () {
  47195. if (this.attachedElement) {
  47196. this.detachElement(this.attachedElement, true);
  47197. }
  47198. this.attached = {};
  47199. this.attachedElement = null;
  47200. this.checkInputs = function () { };
  47201. };
  47202. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47203. var inputs = {};
  47204. for (var cam in this.attached) {
  47205. var input = this.attached[cam];
  47206. var res = BABYLON.SerializationHelper.Serialize(input);
  47207. inputs[input.getClassName()] = res;
  47208. }
  47209. serializedCamera.inputsmgr = inputs;
  47210. };
  47211. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47212. var parsedInputs = parsedCamera.inputsmgr;
  47213. if (parsedInputs) {
  47214. this.clear();
  47215. for (var n in parsedInputs) {
  47216. var construct = BABYLON.CameraInputTypes[n];
  47217. if (construct) {
  47218. var parsedinput = parsedInputs[n];
  47219. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47220. this.add(input);
  47221. }
  47222. }
  47223. }
  47224. else {
  47225. //2016-03-08 this part is for managing backward compatibility
  47226. for (var n in this.attached) {
  47227. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47228. if (construct) {
  47229. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47230. this.remove(this.attached[n]);
  47231. this.add(input);
  47232. }
  47233. }
  47234. }
  47235. };
  47236. return CameraInputsManager;
  47237. }());
  47238. BABYLON.CameraInputsManager = CameraInputsManager;
  47239. })(BABYLON || (BABYLON = {}));
  47240. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47241. var BABYLON;
  47242. (function (BABYLON) {
  47243. var TargetCamera = /** @class */ (function (_super) {
  47244. __extends(TargetCamera, _super);
  47245. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47246. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47247. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47248. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47249. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47250. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47251. _this.speed = 2.0;
  47252. _this.noRotationConstraint = false;
  47253. _this.lockedTarget = null;
  47254. _this._currentTarget = BABYLON.Vector3.Zero();
  47255. _this._viewMatrix = BABYLON.Matrix.Zero();
  47256. _this._camMatrix = BABYLON.Matrix.Zero();
  47257. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47258. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47259. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47260. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47261. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47262. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47263. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47264. return _this;
  47265. }
  47266. TargetCamera.prototype.getFrontPosition = function (distance) {
  47267. this.getWorldMatrix();
  47268. var direction = this.getTarget().subtract(this.position);
  47269. direction.normalize();
  47270. direction.scaleInPlace(distance);
  47271. return this.globalPosition.add(direction);
  47272. };
  47273. TargetCamera.prototype._getLockedTargetPosition = function () {
  47274. if (!this.lockedTarget) {
  47275. return null;
  47276. }
  47277. if (this.lockedTarget.absolutePosition) {
  47278. this.lockedTarget.computeWorldMatrix();
  47279. }
  47280. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47281. };
  47282. TargetCamera.prototype.storeState = function () {
  47283. this._storedPosition = this.position.clone();
  47284. this._storedRotation = this.rotation.clone();
  47285. if (this.rotationQuaternion) {
  47286. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47287. }
  47288. return _super.prototype.storeState.call(this);
  47289. };
  47290. /**
  47291. * Restored camera state. You must call storeState() first
  47292. */
  47293. TargetCamera.prototype._restoreStateValues = function () {
  47294. if (!_super.prototype._restoreStateValues.call(this)) {
  47295. return false;
  47296. }
  47297. this.position = this._storedPosition.clone();
  47298. this.rotation = this._storedRotation.clone();
  47299. if (this.rotationQuaternion) {
  47300. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47301. }
  47302. this.cameraDirection.copyFromFloats(0, 0, 0);
  47303. this.cameraRotation.copyFromFloats(0, 0);
  47304. return true;
  47305. };
  47306. // Cache
  47307. TargetCamera.prototype._initCache = function () {
  47308. _super.prototype._initCache.call(this);
  47309. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47310. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47311. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47312. };
  47313. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47314. if (!ignoreParentClass) {
  47315. _super.prototype._updateCache.call(this);
  47316. }
  47317. var lockedTargetPosition = this._getLockedTargetPosition();
  47318. if (!lockedTargetPosition) {
  47319. this._cache.lockedTarget = null;
  47320. }
  47321. else {
  47322. if (!this._cache.lockedTarget) {
  47323. this._cache.lockedTarget = lockedTargetPosition.clone();
  47324. }
  47325. else {
  47326. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47327. }
  47328. }
  47329. this._cache.rotation.copyFrom(this.rotation);
  47330. if (this.rotationQuaternion)
  47331. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47332. };
  47333. // Synchronized
  47334. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47335. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47336. return false;
  47337. }
  47338. var lockedTargetPosition = this._getLockedTargetPosition();
  47339. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47340. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47341. };
  47342. // Methods
  47343. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47344. var engine = this.getEngine();
  47345. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47346. };
  47347. // Target
  47348. TargetCamera.prototype.setTarget = function (target) {
  47349. this.upVector.normalize();
  47350. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47351. this._camMatrix.invert();
  47352. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47353. var vDir = target.subtract(this.position);
  47354. if (vDir.x >= 0.0) {
  47355. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47356. }
  47357. else {
  47358. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47359. }
  47360. this.rotation.z = 0;
  47361. if (isNaN(this.rotation.x)) {
  47362. this.rotation.x = 0;
  47363. }
  47364. if (isNaN(this.rotation.y)) {
  47365. this.rotation.y = 0;
  47366. }
  47367. if (isNaN(this.rotation.z)) {
  47368. this.rotation.z = 0;
  47369. }
  47370. if (this.rotationQuaternion) {
  47371. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47372. }
  47373. };
  47374. /**
  47375. * Return the current target position of the camera. This value is expressed in local space.
  47376. */
  47377. TargetCamera.prototype.getTarget = function () {
  47378. return this._currentTarget;
  47379. };
  47380. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47381. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47382. };
  47383. TargetCamera.prototype._updatePosition = function () {
  47384. if (this.parent) {
  47385. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47386. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47387. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47388. return;
  47389. }
  47390. this.position.addInPlace(this.cameraDirection);
  47391. };
  47392. TargetCamera.prototype._checkInputs = function () {
  47393. var needToMove = this._decideIfNeedsToMove();
  47394. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47395. // Move
  47396. if (needToMove) {
  47397. this._updatePosition();
  47398. }
  47399. // Rotate
  47400. if (needToRotate) {
  47401. this.rotation.x += this.cameraRotation.x;
  47402. this.rotation.y += this.cameraRotation.y;
  47403. //rotate, if quaternion is set and rotation was used
  47404. if (this.rotationQuaternion) {
  47405. var len = this.rotation.lengthSquared();
  47406. if (len) {
  47407. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47408. }
  47409. }
  47410. if (!this.noRotationConstraint) {
  47411. var limit = (Math.PI / 2) * 0.95;
  47412. if (this.rotation.x > limit)
  47413. this.rotation.x = limit;
  47414. if (this.rotation.x < -limit)
  47415. this.rotation.x = -limit;
  47416. }
  47417. }
  47418. // Inertia
  47419. if (needToMove) {
  47420. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47421. this.cameraDirection.x = 0;
  47422. }
  47423. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47424. this.cameraDirection.y = 0;
  47425. }
  47426. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47427. this.cameraDirection.z = 0;
  47428. }
  47429. this.cameraDirection.scaleInPlace(this.inertia);
  47430. }
  47431. if (needToRotate) {
  47432. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47433. this.cameraRotation.x = 0;
  47434. }
  47435. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47436. this.cameraRotation.y = 0;
  47437. }
  47438. this.cameraRotation.scaleInPlace(this.inertia);
  47439. }
  47440. _super.prototype._checkInputs.call(this);
  47441. };
  47442. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47443. if (this.rotationQuaternion) {
  47444. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47445. }
  47446. else {
  47447. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47448. }
  47449. //update the up vector!
  47450. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47451. };
  47452. TargetCamera.prototype._getViewMatrix = function () {
  47453. if (this.lockedTarget) {
  47454. this.setTarget(this._getLockedTargetPosition());
  47455. }
  47456. // Compute
  47457. this._updateCameraRotationMatrix();
  47458. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47459. // Computing target and final matrix
  47460. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47461. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47462. return this._viewMatrix;
  47463. };
  47464. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47465. if (this.parent) {
  47466. var parentWorldMatrix = this.parent.getWorldMatrix();
  47467. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47468. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47469. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47470. this._markSyncedWithParent();
  47471. }
  47472. else {
  47473. this._globalPosition.copyFrom(this.position);
  47474. this._globalCurrentTarget.copyFrom(target);
  47475. this._globalCurrentUpVector.copyFrom(up);
  47476. }
  47477. if (this.getScene().useRightHandedSystem) {
  47478. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47479. }
  47480. else {
  47481. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47482. }
  47483. };
  47484. /**
  47485. * @override
  47486. * Override Camera.createRigCamera
  47487. */
  47488. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47489. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47490. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47491. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47492. if (!this.rotationQuaternion) {
  47493. this.rotationQuaternion = new BABYLON.Quaternion();
  47494. }
  47495. rigCamera._cameraRigParams = {};
  47496. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47497. }
  47498. return rigCamera;
  47499. }
  47500. return null;
  47501. };
  47502. /**
  47503. * @override
  47504. * Override Camera._updateRigCameras
  47505. */
  47506. TargetCamera.prototype._updateRigCameras = function () {
  47507. var camLeft = this._rigCameras[0];
  47508. var camRight = this._rigCameras[1];
  47509. switch (this.cameraRigMode) {
  47510. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47511. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47512. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47513. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47514. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47515. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47516. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47517. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47518. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47519. camLeft.setTarget(this.getTarget());
  47520. camRight.setTarget(this.getTarget());
  47521. break;
  47522. case BABYLON.Camera.RIG_MODE_VR:
  47523. if (camLeft.rotationQuaternion) {
  47524. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47525. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47526. }
  47527. else {
  47528. camLeft.rotation.copyFrom(this.rotation);
  47529. camRight.rotation.copyFrom(this.rotation);
  47530. }
  47531. camLeft.position.copyFrom(this.position);
  47532. camRight.position.copyFrom(this.position);
  47533. break;
  47534. }
  47535. _super.prototype._updateRigCameras.call(this);
  47536. };
  47537. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47538. if (!this._rigCamTransformMatrix) {
  47539. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47540. }
  47541. var target = this.getTarget();
  47542. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47543. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47544. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47545. };
  47546. TargetCamera.prototype.getClassName = function () {
  47547. return "TargetCamera";
  47548. };
  47549. __decorate([
  47550. BABYLON.serializeAsVector3()
  47551. ], TargetCamera.prototype, "rotation", void 0);
  47552. __decorate([
  47553. BABYLON.serialize()
  47554. ], TargetCamera.prototype, "speed", void 0);
  47555. __decorate([
  47556. BABYLON.serializeAsMeshReference("lockedTargetId")
  47557. ], TargetCamera.prototype, "lockedTarget", void 0);
  47558. return TargetCamera;
  47559. }(BABYLON.Camera));
  47560. BABYLON.TargetCamera = TargetCamera;
  47561. })(BABYLON || (BABYLON = {}));
  47562. //# sourceMappingURL=babylon.targetCamera.js.map
  47563. var BABYLON;
  47564. (function (BABYLON) {
  47565. var FreeCameraMouseInput = /** @class */ (function () {
  47566. function FreeCameraMouseInput(touchEnabled) {
  47567. if (touchEnabled === void 0) { touchEnabled = true; }
  47568. this.touchEnabled = touchEnabled;
  47569. this.buttons = [0, 1, 2];
  47570. this.angularSensibility = 2000.0;
  47571. this.previousPosition = null;
  47572. }
  47573. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47574. var _this = this;
  47575. var engine = this.camera.getEngine();
  47576. if (!this._pointerInput) {
  47577. this._pointerInput = function (p, s) {
  47578. var evt = p.event;
  47579. if (engine.isInVRExclusivePointerMode) {
  47580. return;
  47581. }
  47582. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47583. return;
  47584. }
  47585. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47586. return;
  47587. }
  47588. var srcElement = (evt.srcElement || evt.target);
  47589. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47590. try {
  47591. srcElement.setPointerCapture(evt.pointerId);
  47592. }
  47593. catch (e) {
  47594. //Nothing to do with the error. Execution will continue.
  47595. }
  47596. _this.previousPosition = {
  47597. x: evt.clientX,
  47598. y: evt.clientY
  47599. };
  47600. if (!noPreventDefault) {
  47601. evt.preventDefault();
  47602. element.focus();
  47603. }
  47604. }
  47605. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47606. try {
  47607. srcElement.releasePointerCapture(evt.pointerId);
  47608. }
  47609. catch (e) {
  47610. //Nothing to do with the error.
  47611. }
  47612. _this.previousPosition = null;
  47613. if (!noPreventDefault) {
  47614. evt.preventDefault();
  47615. }
  47616. }
  47617. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47618. if (!_this.previousPosition || engine.isPointerLock) {
  47619. return;
  47620. }
  47621. var offsetX = evt.clientX - _this.previousPosition.x;
  47622. if (_this.camera.getScene().useRightHandedSystem)
  47623. offsetX *= -1;
  47624. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47625. offsetX *= -1;
  47626. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47627. var offsetY = evt.clientY - _this.previousPosition.y;
  47628. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47629. _this.previousPosition = {
  47630. x: evt.clientX,
  47631. y: evt.clientY
  47632. };
  47633. if (!noPreventDefault) {
  47634. evt.preventDefault();
  47635. }
  47636. }
  47637. };
  47638. }
  47639. this._onMouseMove = function (evt) {
  47640. if (!engine.isPointerLock) {
  47641. return;
  47642. }
  47643. if (engine.isInVRExclusivePointerMode) {
  47644. return;
  47645. }
  47646. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47647. if (_this.camera.getScene().useRightHandedSystem)
  47648. offsetX *= -1;
  47649. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47650. offsetX *= -1;
  47651. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47652. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47653. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47654. _this.previousPosition = null;
  47655. if (!noPreventDefault) {
  47656. evt.preventDefault();
  47657. }
  47658. };
  47659. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47660. element.addEventListener("mousemove", this._onMouseMove, false);
  47661. };
  47662. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47663. if (this._observer && element) {
  47664. this.camera.getScene().onPointerObservable.remove(this._observer);
  47665. if (this._onMouseMove) {
  47666. element.removeEventListener("mousemove", this._onMouseMove);
  47667. }
  47668. this._observer = null;
  47669. this._onMouseMove = null;
  47670. this.previousPosition = null;
  47671. }
  47672. };
  47673. FreeCameraMouseInput.prototype.getClassName = function () {
  47674. return "FreeCameraMouseInput";
  47675. };
  47676. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47677. return "mouse";
  47678. };
  47679. __decorate([
  47680. BABYLON.serialize()
  47681. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47682. __decorate([
  47683. BABYLON.serialize()
  47684. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47685. return FreeCameraMouseInput;
  47686. }());
  47687. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47688. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47689. })(BABYLON || (BABYLON = {}));
  47690. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47691. var BABYLON;
  47692. (function (BABYLON) {
  47693. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47694. function FreeCameraKeyboardMoveInput() {
  47695. this._keys = new Array();
  47696. this.keysUp = [38];
  47697. this.keysDown = [40];
  47698. this.keysLeft = [37];
  47699. this.keysRight = [39];
  47700. }
  47701. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47702. var _this = this;
  47703. if (this._onCanvasBlurObserver) {
  47704. return;
  47705. }
  47706. this._scene = this.camera.getScene();
  47707. this._engine = this._scene.getEngine();
  47708. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47709. _this._keys = [];
  47710. });
  47711. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47712. var evt = info.event;
  47713. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47714. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47715. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47716. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47717. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47718. var index = _this._keys.indexOf(evt.keyCode);
  47719. if (index === -1) {
  47720. _this._keys.push(evt.keyCode);
  47721. }
  47722. if (!noPreventDefault) {
  47723. evt.preventDefault();
  47724. }
  47725. }
  47726. }
  47727. else {
  47728. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47729. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47730. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47731. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47732. var index = _this._keys.indexOf(evt.keyCode);
  47733. if (index >= 0) {
  47734. _this._keys.splice(index, 1);
  47735. }
  47736. if (!noPreventDefault) {
  47737. evt.preventDefault();
  47738. }
  47739. }
  47740. }
  47741. });
  47742. };
  47743. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47744. if (this._scene) {
  47745. if (this._onKeyboardObserver) {
  47746. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47747. }
  47748. if (this._onCanvasBlurObserver) {
  47749. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47750. }
  47751. this._onKeyboardObserver = null;
  47752. this._onCanvasBlurObserver = null;
  47753. }
  47754. this._keys = [];
  47755. };
  47756. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47757. if (this._onKeyboardObserver) {
  47758. var camera = this.camera;
  47759. // Keyboard
  47760. for (var index = 0; index < this._keys.length; index++) {
  47761. var keyCode = this._keys[index];
  47762. var speed = camera._computeLocalCameraSpeed();
  47763. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47764. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47765. }
  47766. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47767. camera._localDirection.copyFromFloats(0, 0, speed);
  47768. }
  47769. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47770. camera._localDirection.copyFromFloats(speed, 0, 0);
  47771. }
  47772. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47773. camera._localDirection.copyFromFloats(0, 0, -speed);
  47774. }
  47775. if (camera.getScene().useRightHandedSystem) {
  47776. camera._localDirection.z *= -1;
  47777. }
  47778. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47779. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47780. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47781. }
  47782. }
  47783. };
  47784. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47785. return "FreeCameraKeyboardMoveInput";
  47786. };
  47787. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47788. this._keys = [];
  47789. };
  47790. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47791. return "keyboard";
  47792. };
  47793. __decorate([
  47794. BABYLON.serialize()
  47795. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47796. __decorate([
  47797. BABYLON.serialize()
  47798. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47799. __decorate([
  47800. BABYLON.serialize()
  47801. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47802. __decorate([
  47803. BABYLON.serialize()
  47804. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47805. return FreeCameraKeyboardMoveInput;
  47806. }());
  47807. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47808. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47809. })(BABYLON || (BABYLON = {}));
  47810. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47811. var BABYLON;
  47812. (function (BABYLON) {
  47813. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47814. __extends(FreeCameraInputsManager, _super);
  47815. function FreeCameraInputsManager(camera) {
  47816. return _super.call(this, camera) || this;
  47817. }
  47818. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47819. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47820. return this;
  47821. };
  47822. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47823. if (touchEnabled === void 0) { touchEnabled = true; }
  47824. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47825. return this;
  47826. };
  47827. FreeCameraInputsManager.prototype.addGamepad = function () {
  47828. this.add(new BABYLON.FreeCameraGamepadInput());
  47829. return this;
  47830. };
  47831. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47832. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47833. return this;
  47834. };
  47835. FreeCameraInputsManager.prototype.addTouch = function () {
  47836. this.add(new BABYLON.FreeCameraTouchInput());
  47837. return this;
  47838. };
  47839. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47840. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47841. return this;
  47842. };
  47843. return FreeCameraInputsManager;
  47844. }(BABYLON.CameraInputsManager));
  47845. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47846. })(BABYLON || (BABYLON = {}));
  47847. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47848. var BABYLON;
  47849. (function (BABYLON) {
  47850. var FreeCamera = /** @class */ (function (_super) {
  47851. __extends(FreeCamera, _super);
  47852. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47853. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47854. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47855. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47856. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47857. _this.checkCollisions = false;
  47858. _this.applyGravity = false;
  47859. _this._needMoveForGravity = false;
  47860. _this._oldPosition = BABYLON.Vector3.Zero();
  47861. _this._diffPosition = BABYLON.Vector3.Zero();
  47862. _this._newPosition = BABYLON.Vector3.Zero();
  47863. // Collisions
  47864. _this._collisionMask = -1;
  47865. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47866. if (collidedMesh === void 0) { collidedMesh = null; }
  47867. //TODO move this to the collision coordinator!
  47868. if (_this.getScene().workerCollisions)
  47869. newPosition.multiplyInPlace(_this._collider._radius);
  47870. var updatePosition = function (newPos) {
  47871. _this._newPosition.copyFrom(newPos);
  47872. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47873. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47874. _this.position.addInPlace(_this._diffPosition);
  47875. if (_this.onCollide && collidedMesh) {
  47876. _this.onCollide(collidedMesh);
  47877. }
  47878. }
  47879. };
  47880. updatePosition(newPosition);
  47881. };
  47882. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47883. _this.inputs.addKeyboard().addMouse();
  47884. return _this;
  47885. }
  47886. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47887. //-- begin properties for backward compatibility for inputs
  47888. /**
  47889. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47890. * Higher values reduce sensitivity.
  47891. */
  47892. get: function () {
  47893. var mouse = this.inputs.attached["mouse"];
  47894. if (mouse)
  47895. return mouse.angularSensibility;
  47896. return 0;
  47897. },
  47898. /**
  47899. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47900. * Higher values reduce sensitivity.
  47901. */
  47902. set: function (value) {
  47903. var mouse = this.inputs.attached["mouse"];
  47904. if (mouse)
  47905. mouse.angularSensibility = value;
  47906. },
  47907. enumerable: true,
  47908. configurable: true
  47909. });
  47910. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47911. get: function () {
  47912. var keyboard = this.inputs.attached["keyboard"];
  47913. if (keyboard)
  47914. return keyboard.keysUp;
  47915. return [];
  47916. },
  47917. set: function (value) {
  47918. var keyboard = this.inputs.attached["keyboard"];
  47919. if (keyboard)
  47920. keyboard.keysUp = value;
  47921. },
  47922. enumerable: true,
  47923. configurable: true
  47924. });
  47925. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47926. get: function () {
  47927. var keyboard = this.inputs.attached["keyboard"];
  47928. if (keyboard)
  47929. return keyboard.keysDown;
  47930. return [];
  47931. },
  47932. set: function (value) {
  47933. var keyboard = this.inputs.attached["keyboard"];
  47934. if (keyboard)
  47935. keyboard.keysDown = value;
  47936. },
  47937. enumerable: true,
  47938. configurable: true
  47939. });
  47940. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47941. get: function () {
  47942. var keyboard = this.inputs.attached["keyboard"];
  47943. if (keyboard)
  47944. return keyboard.keysLeft;
  47945. return [];
  47946. },
  47947. set: function (value) {
  47948. var keyboard = this.inputs.attached["keyboard"];
  47949. if (keyboard)
  47950. keyboard.keysLeft = value;
  47951. },
  47952. enumerable: true,
  47953. configurable: true
  47954. });
  47955. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47956. get: function () {
  47957. var keyboard = this.inputs.attached["keyboard"];
  47958. if (keyboard)
  47959. return keyboard.keysRight;
  47960. return [];
  47961. },
  47962. set: function (value) {
  47963. var keyboard = this.inputs.attached["keyboard"];
  47964. if (keyboard)
  47965. keyboard.keysRight = value;
  47966. },
  47967. enumerable: true,
  47968. configurable: true
  47969. });
  47970. // Controls
  47971. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47972. this.inputs.attachElement(element, noPreventDefault);
  47973. };
  47974. FreeCamera.prototype.detachControl = function (element) {
  47975. this.inputs.detachElement(element);
  47976. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47977. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47978. };
  47979. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47980. get: function () {
  47981. return this._collisionMask;
  47982. },
  47983. set: function (mask) {
  47984. this._collisionMask = !isNaN(mask) ? mask : -1;
  47985. },
  47986. enumerable: true,
  47987. configurable: true
  47988. });
  47989. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47990. var globalPosition;
  47991. if (this.parent) {
  47992. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47993. }
  47994. else {
  47995. globalPosition = this.position;
  47996. }
  47997. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47998. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47999. if (!this._collider) {
  48000. this._collider = new BABYLON.Collider();
  48001. }
  48002. this._collider._radius = this.ellipsoid;
  48003. this._collider.collisionMask = this._collisionMask;
  48004. //no need for clone, as long as gravity is not on.
  48005. var actualDisplacement = displacement;
  48006. //add gravity to the direction to prevent the dual-collision checking
  48007. if (this.applyGravity) {
  48008. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48009. actualDisplacement = displacement.add(this.getScene().gravity);
  48010. }
  48011. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48012. };
  48013. FreeCamera.prototype._checkInputs = function () {
  48014. if (!this._localDirection) {
  48015. this._localDirection = BABYLON.Vector3.Zero();
  48016. this._transformedDirection = BABYLON.Vector3.Zero();
  48017. }
  48018. this.inputs.checkInputs();
  48019. _super.prototype._checkInputs.call(this);
  48020. };
  48021. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48022. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48023. };
  48024. FreeCamera.prototype._updatePosition = function () {
  48025. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48026. this._collideWithWorld(this.cameraDirection);
  48027. }
  48028. else {
  48029. _super.prototype._updatePosition.call(this);
  48030. }
  48031. };
  48032. FreeCamera.prototype.dispose = function () {
  48033. this.inputs.clear();
  48034. _super.prototype.dispose.call(this);
  48035. };
  48036. FreeCamera.prototype.getClassName = function () {
  48037. return "FreeCamera";
  48038. };
  48039. __decorate([
  48040. BABYLON.serializeAsVector3()
  48041. ], FreeCamera.prototype, "ellipsoid", void 0);
  48042. __decorate([
  48043. BABYLON.serializeAsVector3()
  48044. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48045. __decorate([
  48046. BABYLON.serialize()
  48047. ], FreeCamera.prototype, "checkCollisions", void 0);
  48048. __decorate([
  48049. BABYLON.serialize()
  48050. ], FreeCamera.prototype, "applyGravity", void 0);
  48051. return FreeCamera;
  48052. }(BABYLON.TargetCamera));
  48053. BABYLON.FreeCamera = FreeCamera;
  48054. })(BABYLON || (BABYLON = {}));
  48055. //# sourceMappingURL=babylon.freeCamera.js.map
  48056. var BABYLON;
  48057. (function (BABYLON) {
  48058. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48059. function ArcRotateCameraKeyboardMoveInput() {
  48060. this._keys = new Array();
  48061. this.keysUp = [38];
  48062. this.keysDown = [40];
  48063. this.keysLeft = [37];
  48064. this.keysRight = [39];
  48065. this.keysReset = [220];
  48066. this.panningSensibility = 50.0;
  48067. this.zoomingSensibility = 25.0;
  48068. this.useAltToZoom = true;
  48069. }
  48070. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48071. var _this = this;
  48072. if (this._onCanvasBlurObserver) {
  48073. return;
  48074. }
  48075. this._scene = this.camera.getScene();
  48076. this._engine = this._scene.getEngine();
  48077. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48078. _this._keys = [];
  48079. });
  48080. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48081. var evt = info.event;
  48082. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48083. _this._ctrlPressed = evt.ctrlKey;
  48084. _this._altPressed = evt.altKey;
  48085. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48086. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48087. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48088. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48089. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48090. var index = _this._keys.indexOf(evt.keyCode);
  48091. if (index === -1) {
  48092. _this._keys.push(evt.keyCode);
  48093. }
  48094. if (evt.preventDefault) {
  48095. if (!noPreventDefault) {
  48096. evt.preventDefault();
  48097. }
  48098. }
  48099. }
  48100. }
  48101. else {
  48102. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48103. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48104. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48105. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48106. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48107. var index = _this._keys.indexOf(evt.keyCode);
  48108. if (index >= 0) {
  48109. _this._keys.splice(index, 1);
  48110. }
  48111. if (evt.preventDefault) {
  48112. if (!noPreventDefault) {
  48113. evt.preventDefault();
  48114. }
  48115. }
  48116. }
  48117. }
  48118. });
  48119. };
  48120. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48121. if (this._scene) {
  48122. if (this._onKeyboardObserver) {
  48123. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48124. }
  48125. if (this._onCanvasBlurObserver) {
  48126. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48127. }
  48128. this._onKeyboardObserver = null;
  48129. this._onCanvasBlurObserver = null;
  48130. }
  48131. this._keys = [];
  48132. };
  48133. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48134. if (this._onKeyboardObserver) {
  48135. var camera = this.camera;
  48136. for (var index = 0; index < this._keys.length; index++) {
  48137. var keyCode = this._keys[index];
  48138. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48139. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48140. camera.inertialPanningX -= 1 / this.panningSensibility;
  48141. }
  48142. else {
  48143. camera.inertialAlphaOffset -= 0.01;
  48144. }
  48145. }
  48146. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48147. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48148. camera.inertialPanningY += 1 / this.panningSensibility;
  48149. }
  48150. else if (this._altPressed && this.useAltToZoom) {
  48151. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48152. }
  48153. else {
  48154. camera.inertialBetaOffset -= 0.01;
  48155. }
  48156. }
  48157. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48158. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48159. camera.inertialPanningX += 1 / this.panningSensibility;
  48160. }
  48161. else {
  48162. camera.inertialAlphaOffset += 0.01;
  48163. }
  48164. }
  48165. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48166. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48167. camera.inertialPanningY -= 1 / this.panningSensibility;
  48168. }
  48169. else if (this._altPressed && this.useAltToZoom) {
  48170. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48171. }
  48172. else {
  48173. camera.inertialBetaOffset += 0.01;
  48174. }
  48175. }
  48176. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48177. camera.restoreState();
  48178. }
  48179. }
  48180. }
  48181. };
  48182. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48183. return "ArcRotateCameraKeyboardMoveInput";
  48184. };
  48185. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48186. return "keyboard";
  48187. };
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48212. return ArcRotateCameraKeyboardMoveInput;
  48213. }());
  48214. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48215. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48216. })(BABYLON || (BABYLON = {}));
  48217. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48218. var BABYLON;
  48219. (function (BABYLON) {
  48220. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48221. function ArcRotateCameraMouseWheelInput() {
  48222. this.wheelPrecision = 3.0;
  48223. /**
  48224. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48225. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48226. */
  48227. this.wheelDeltaPercentage = 0;
  48228. }
  48229. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48230. var _this = this;
  48231. this._wheel = function (p, s) {
  48232. //sanity check - this should be a PointerWheel event.
  48233. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48234. return;
  48235. var event = p.event;
  48236. var delta = 0;
  48237. if (event.wheelDelta) {
  48238. if (_this.wheelDeltaPercentage) {
  48239. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48240. if (event.wheelDelta > 0) {
  48241. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48242. }
  48243. else {
  48244. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48245. }
  48246. }
  48247. else {
  48248. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48249. }
  48250. }
  48251. else if (event.detail) {
  48252. delta = -event.detail / _this.wheelPrecision;
  48253. }
  48254. if (delta)
  48255. _this.camera.inertialRadiusOffset += delta;
  48256. if (event.preventDefault) {
  48257. if (!noPreventDefault) {
  48258. event.preventDefault();
  48259. }
  48260. }
  48261. };
  48262. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48263. };
  48264. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48265. if (this._observer && element) {
  48266. this.camera.getScene().onPointerObservable.remove(this._observer);
  48267. this._observer = null;
  48268. this._wheel = null;
  48269. }
  48270. };
  48271. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48272. return "ArcRotateCameraMouseWheelInput";
  48273. };
  48274. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48275. return "mousewheel";
  48276. };
  48277. __decorate([
  48278. BABYLON.serialize()
  48279. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48280. __decorate([
  48281. BABYLON.serialize()
  48282. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48283. return ArcRotateCameraMouseWheelInput;
  48284. }());
  48285. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48286. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48287. })(BABYLON || (BABYLON = {}));
  48288. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48289. var BABYLON;
  48290. (function (BABYLON) {
  48291. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48292. function ArcRotateCameraPointersInput() {
  48293. this.buttons = [0, 1, 2];
  48294. this.angularSensibilityX = 1000.0;
  48295. this.angularSensibilityY = 1000.0;
  48296. this.pinchPrecision = 12.0;
  48297. /**
  48298. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48299. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48300. */
  48301. this.pinchDeltaPercentage = 0;
  48302. this.panningSensibility = 1000.0;
  48303. this.multiTouchPanning = true;
  48304. this.multiTouchPanAndZoom = true;
  48305. this._isPanClick = false;
  48306. this.pinchInwards = true;
  48307. }
  48308. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48309. var _this = this;
  48310. var engine = this.camera.getEngine();
  48311. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48312. var pointA = null;
  48313. var pointB = null;
  48314. var previousPinchSquaredDistance = 0;
  48315. var initialDistance = 0;
  48316. var twoFingerActivityCount = 0;
  48317. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48318. this._pointerInput = function (p, s) {
  48319. var evt = p.event;
  48320. var isTouch = p.event.pointerType === "touch";
  48321. if (engine.isInVRExclusivePointerMode) {
  48322. return;
  48323. }
  48324. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48325. return;
  48326. }
  48327. var srcElement = (evt.srcElement || evt.target);
  48328. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48329. try {
  48330. srcElement.setPointerCapture(evt.pointerId);
  48331. }
  48332. catch (e) {
  48333. //Nothing to do with the error. Execution will continue.
  48334. }
  48335. // Manage panning with pan button click
  48336. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48337. // manage pointers
  48338. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48339. if (pointA === null) {
  48340. pointA = cacheSoloPointer;
  48341. }
  48342. else if (pointB === null) {
  48343. pointB = cacheSoloPointer;
  48344. }
  48345. if (!noPreventDefault) {
  48346. evt.preventDefault();
  48347. element.focus();
  48348. }
  48349. }
  48350. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48351. _this.camera.restoreState();
  48352. }
  48353. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48354. try {
  48355. srcElement.releasePointerCapture(evt.pointerId);
  48356. }
  48357. catch (e) {
  48358. //Nothing to do with the error.
  48359. }
  48360. cacheSoloPointer = null;
  48361. previousPinchSquaredDistance = 0;
  48362. previousMultiTouchPanPosition.isPaning = false;
  48363. previousMultiTouchPanPosition.isPinching = false;
  48364. twoFingerActivityCount = 0;
  48365. initialDistance = 0;
  48366. if (!isTouch) {
  48367. pointB = null; // Mouse and pen are mono pointer
  48368. }
  48369. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48370. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48371. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48372. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48373. if (engine._badOS) {
  48374. pointA = pointB = null;
  48375. }
  48376. else {
  48377. //only remove the impacted pointer in case of multitouch allowing on most
  48378. //platforms switching from rotate to zoom and pan seamlessly.
  48379. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48380. pointA = pointB;
  48381. pointB = null;
  48382. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48383. }
  48384. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48385. pointB = null;
  48386. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48387. }
  48388. else {
  48389. pointA = pointB = null;
  48390. }
  48391. }
  48392. if (!noPreventDefault) {
  48393. evt.preventDefault();
  48394. }
  48395. }
  48396. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48397. if (!noPreventDefault) {
  48398. evt.preventDefault();
  48399. }
  48400. // One button down
  48401. if (pointA && pointB === null && cacheSoloPointer) {
  48402. if (_this.panningSensibility !== 0 &&
  48403. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48404. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48405. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48406. }
  48407. else {
  48408. var offsetX = evt.clientX - cacheSoloPointer.x;
  48409. var offsetY = evt.clientY - cacheSoloPointer.y;
  48410. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48411. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48412. }
  48413. cacheSoloPointer.x = evt.clientX;
  48414. cacheSoloPointer.y = evt.clientY;
  48415. }
  48416. // Two buttons down: pinch/pan
  48417. else if (pointA && pointB) {
  48418. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48419. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48420. ed.x = evt.clientX;
  48421. ed.y = evt.clientY;
  48422. var direction = _this.pinchInwards ? 1 : -1;
  48423. var distX = pointA.x - pointB.x;
  48424. var distY = pointA.y - pointB.y;
  48425. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48426. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48427. if (previousPinchSquaredDistance === 0) {
  48428. initialDistance = pinchDistance;
  48429. previousPinchSquaredDistance = pinchSquaredDistance;
  48430. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48431. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48432. return;
  48433. }
  48434. if (_this.multiTouchPanAndZoom) {
  48435. if (_this.pinchDeltaPercentage) {
  48436. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48437. }
  48438. else {
  48439. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48440. (_this.pinchPrecision *
  48441. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48442. direction);
  48443. }
  48444. if (_this.panningSensibility !== 0) {
  48445. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48446. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48447. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48448. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48449. previousMultiTouchPanPosition.x = pointersCenterX;
  48450. previousMultiTouchPanPosition.y = pointersCenterY;
  48451. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48452. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48453. }
  48454. }
  48455. else {
  48456. twoFingerActivityCount++;
  48457. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48458. if (_this.pinchDeltaPercentage) {
  48459. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48460. }
  48461. else {
  48462. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48463. (_this.pinchPrecision *
  48464. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48465. direction);
  48466. }
  48467. previousMultiTouchPanPosition.isPaning = false;
  48468. previousMultiTouchPanPosition.isPinching = true;
  48469. }
  48470. else {
  48471. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48472. if (!previousMultiTouchPanPosition.isPaning) {
  48473. previousMultiTouchPanPosition.isPaning = true;
  48474. previousMultiTouchPanPosition.isPinching = false;
  48475. previousMultiTouchPanPosition.x = ed.x;
  48476. previousMultiTouchPanPosition.y = ed.y;
  48477. return;
  48478. }
  48479. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48480. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48481. }
  48482. }
  48483. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48484. previousMultiTouchPanPosition.x = ed.x;
  48485. previousMultiTouchPanPosition.y = ed.y;
  48486. }
  48487. }
  48488. previousPinchSquaredDistance = pinchSquaredDistance;
  48489. }
  48490. }
  48491. };
  48492. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48493. this._onContextMenu = function (evt) {
  48494. evt.preventDefault();
  48495. };
  48496. if (!this.camera._useCtrlForPanning) {
  48497. element.addEventListener("contextmenu", this._onContextMenu, false);
  48498. }
  48499. this._onLostFocus = function () {
  48500. //this._keys = [];
  48501. pointA = pointB = null;
  48502. previousPinchSquaredDistance = 0;
  48503. previousMultiTouchPanPosition.isPaning = false;
  48504. previousMultiTouchPanPosition.isPinching = false;
  48505. twoFingerActivityCount = 0;
  48506. cacheSoloPointer = null;
  48507. initialDistance = 0;
  48508. };
  48509. this._onMouseMove = function (evt) {
  48510. if (!engine.isPointerLock) {
  48511. return;
  48512. }
  48513. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48514. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48515. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48516. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48517. if (!noPreventDefault) {
  48518. evt.preventDefault();
  48519. }
  48520. };
  48521. this._onGestureStart = function (e) {
  48522. if (window.MSGesture === undefined) {
  48523. return;
  48524. }
  48525. if (!_this._MSGestureHandler) {
  48526. _this._MSGestureHandler = new MSGesture();
  48527. _this._MSGestureHandler.target = element;
  48528. }
  48529. _this._MSGestureHandler.addPointer(e.pointerId);
  48530. };
  48531. this._onGesture = function (e) {
  48532. _this.camera.radius *= e.scale;
  48533. if (e.preventDefault) {
  48534. if (!noPreventDefault) {
  48535. e.stopPropagation();
  48536. e.preventDefault();
  48537. }
  48538. }
  48539. };
  48540. element.addEventListener("mousemove", this._onMouseMove, false);
  48541. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48542. element.addEventListener("MSGestureChange", this._onGesture, false);
  48543. BABYLON.Tools.RegisterTopRootEvents([
  48544. { name: "blur", handler: this._onLostFocus }
  48545. ]);
  48546. };
  48547. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48548. if (this._onLostFocus) {
  48549. BABYLON.Tools.UnregisterTopRootEvents([
  48550. { name: "blur", handler: this._onLostFocus }
  48551. ]);
  48552. }
  48553. if (element && this._observer) {
  48554. this.camera.getScene().onPointerObservable.remove(this._observer);
  48555. this._observer = null;
  48556. if (this._onContextMenu) {
  48557. element.removeEventListener("contextmenu", this._onContextMenu);
  48558. }
  48559. if (this._onMouseMove) {
  48560. element.removeEventListener("mousemove", this._onMouseMove);
  48561. }
  48562. if (this._onGestureStart) {
  48563. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48564. }
  48565. if (this._onGesture) {
  48566. element.removeEventListener("MSGestureChange", this._onGesture);
  48567. }
  48568. this._isPanClick = false;
  48569. this.pinchInwards = true;
  48570. this._onMouseMove = null;
  48571. this._onGestureStart = null;
  48572. this._onGesture = null;
  48573. this._MSGestureHandler = null;
  48574. this._onLostFocus = null;
  48575. this._onContextMenu = null;
  48576. }
  48577. };
  48578. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48579. return "ArcRotateCameraPointersInput";
  48580. };
  48581. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48582. return "pointers";
  48583. };
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48587. __decorate([
  48588. BABYLON.serialize()
  48589. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48590. __decorate([
  48591. BABYLON.serialize()
  48592. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48593. __decorate([
  48594. BABYLON.serialize()
  48595. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48608. return ArcRotateCameraPointersInput;
  48609. }());
  48610. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48611. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48612. })(BABYLON || (BABYLON = {}));
  48613. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48614. var BABYLON;
  48615. (function (BABYLON) {
  48616. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48617. __extends(ArcRotateCameraInputsManager, _super);
  48618. function ArcRotateCameraInputsManager(camera) {
  48619. return _super.call(this, camera) || this;
  48620. }
  48621. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48622. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48623. return this;
  48624. };
  48625. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48626. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48627. return this;
  48628. };
  48629. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48630. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48631. return this;
  48632. };
  48633. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48634. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48635. return this;
  48636. };
  48637. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48638. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48639. return this;
  48640. };
  48641. return ArcRotateCameraInputsManager;
  48642. }(BABYLON.CameraInputsManager));
  48643. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48644. })(BABYLON || (BABYLON = {}));
  48645. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48646. var BABYLON;
  48647. (function (BABYLON) {
  48648. var ArcRotateCamera = /** @class */ (function (_super) {
  48649. __extends(ArcRotateCamera, _super);
  48650. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48651. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48652. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48653. _this.inertialAlphaOffset = 0;
  48654. _this.inertialBetaOffset = 0;
  48655. _this.inertialRadiusOffset = 0;
  48656. _this.lowerAlphaLimit = null;
  48657. _this.upperAlphaLimit = null;
  48658. _this.lowerBetaLimit = 0.01;
  48659. _this.upperBetaLimit = Math.PI;
  48660. _this.lowerRadiusLimit = null;
  48661. _this.upperRadiusLimit = null;
  48662. _this.inertialPanningX = 0;
  48663. _this.inertialPanningY = 0;
  48664. _this.pinchToPanMaxDistance = 20;
  48665. _this.panningDistanceLimit = null;
  48666. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48667. _this.panningInertia = 0.9;
  48668. //-- end properties for backward compatibility for inputs
  48669. _this.zoomOnFactor = 1;
  48670. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48671. _this.allowUpsideDown = true;
  48672. _this._viewMatrix = new BABYLON.Matrix();
  48673. // Panning
  48674. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48675. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48676. _this.checkCollisions = false;
  48677. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48678. _this._previousPosition = BABYLON.Vector3.Zero();
  48679. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48680. _this._newPosition = BABYLON.Vector3.Zero();
  48681. _this._computationVector = BABYLON.Vector3.Zero();
  48682. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48683. if (collidedMesh === void 0) { collidedMesh = null; }
  48684. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48685. newPosition.multiplyInPlace(_this._collider._radius);
  48686. }
  48687. if (!collidedMesh) {
  48688. _this._previousPosition.copyFrom(_this.position);
  48689. }
  48690. else {
  48691. _this.setPosition(newPosition);
  48692. if (_this.onCollide) {
  48693. _this.onCollide(collidedMesh);
  48694. }
  48695. }
  48696. // Recompute because of constraints
  48697. var cosa = Math.cos(_this.alpha);
  48698. var sina = Math.sin(_this.alpha);
  48699. var cosb = Math.cos(_this.beta);
  48700. var sinb = Math.sin(_this.beta);
  48701. if (sinb === 0) {
  48702. sinb = 0.0001;
  48703. }
  48704. var target = _this._getTargetPosition();
  48705. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48706. target.addToRef(_this._computationVector, _this._newPosition);
  48707. _this.position.copyFrom(_this._newPosition);
  48708. var up = _this.upVector;
  48709. if (_this.allowUpsideDown && _this.beta < 0) {
  48710. up = up.clone();
  48711. up = up.negate();
  48712. }
  48713. _this._computeViewMatrix(_this.position, target, up);
  48714. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48715. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48716. _this._collisionTriggered = false;
  48717. };
  48718. _this._target = BABYLON.Vector3.Zero();
  48719. if (target) {
  48720. _this.setTarget(target);
  48721. }
  48722. _this.alpha = alpha;
  48723. _this.beta = beta;
  48724. _this.radius = radius;
  48725. _this.getViewMatrix();
  48726. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48727. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48728. return _this;
  48729. }
  48730. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48731. get: function () {
  48732. return this._target;
  48733. },
  48734. set: function (value) {
  48735. this.setTarget(value);
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48741. //-- begin properties for backward compatibility for inputs
  48742. get: function () {
  48743. var pointers = this.inputs.attached["pointers"];
  48744. if (pointers)
  48745. return pointers.angularSensibilityX;
  48746. return 0;
  48747. },
  48748. set: function (value) {
  48749. var pointers = this.inputs.attached["pointers"];
  48750. if (pointers) {
  48751. pointers.angularSensibilityX = value;
  48752. }
  48753. },
  48754. enumerable: true,
  48755. configurable: true
  48756. });
  48757. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48758. get: function () {
  48759. var pointers = this.inputs.attached["pointers"];
  48760. if (pointers)
  48761. return pointers.angularSensibilityY;
  48762. return 0;
  48763. },
  48764. set: function (value) {
  48765. var pointers = this.inputs.attached["pointers"];
  48766. if (pointers) {
  48767. pointers.angularSensibilityY = value;
  48768. }
  48769. },
  48770. enumerable: true,
  48771. configurable: true
  48772. });
  48773. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48774. get: function () {
  48775. var pointers = this.inputs.attached["pointers"];
  48776. if (pointers)
  48777. return pointers.pinchPrecision;
  48778. return 0;
  48779. },
  48780. set: function (value) {
  48781. var pointers = this.inputs.attached["pointers"];
  48782. if (pointers) {
  48783. pointers.pinchPrecision = value;
  48784. }
  48785. },
  48786. enumerable: true,
  48787. configurable: true
  48788. });
  48789. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48790. get: function () {
  48791. var pointers = this.inputs.attached["pointers"];
  48792. if (pointers)
  48793. return pointers.pinchDeltaPercentage;
  48794. return 0;
  48795. },
  48796. set: function (value) {
  48797. var pointers = this.inputs.attached["pointers"];
  48798. if (pointers) {
  48799. pointers.pinchDeltaPercentage = value;
  48800. }
  48801. },
  48802. enumerable: true,
  48803. configurable: true
  48804. });
  48805. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48806. get: function () {
  48807. var pointers = this.inputs.attached["pointers"];
  48808. if (pointers)
  48809. return pointers.panningSensibility;
  48810. return 0;
  48811. },
  48812. set: function (value) {
  48813. var pointers = this.inputs.attached["pointers"];
  48814. if (pointers) {
  48815. pointers.panningSensibility = value;
  48816. }
  48817. },
  48818. enumerable: true,
  48819. configurable: true
  48820. });
  48821. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48822. get: function () {
  48823. var keyboard = this.inputs.attached["keyboard"];
  48824. if (keyboard)
  48825. return keyboard.keysUp;
  48826. return [];
  48827. },
  48828. set: function (value) {
  48829. var keyboard = this.inputs.attached["keyboard"];
  48830. if (keyboard)
  48831. keyboard.keysUp = value;
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48837. get: function () {
  48838. var keyboard = this.inputs.attached["keyboard"];
  48839. if (keyboard)
  48840. return keyboard.keysDown;
  48841. return [];
  48842. },
  48843. set: function (value) {
  48844. var keyboard = this.inputs.attached["keyboard"];
  48845. if (keyboard)
  48846. keyboard.keysDown = value;
  48847. },
  48848. enumerable: true,
  48849. configurable: true
  48850. });
  48851. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48852. get: function () {
  48853. var keyboard = this.inputs.attached["keyboard"];
  48854. if (keyboard)
  48855. return keyboard.keysLeft;
  48856. return [];
  48857. },
  48858. set: function (value) {
  48859. var keyboard = this.inputs.attached["keyboard"];
  48860. if (keyboard)
  48861. keyboard.keysLeft = value;
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48867. get: function () {
  48868. var keyboard = this.inputs.attached["keyboard"];
  48869. if (keyboard)
  48870. return keyboard.keysRight;
  48871. return [];
  48872. },
  48873. set: function (value) {
  48874. var keyboard = this.inputs.attached["keyboard"];
  48875. if (keyboard)
  48876. keyboard.keysRight = value;
  48877. },
  48878. enumerable: true,
  48879. configurable: true
  48880. });
  48881. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48882. get: function () {
  48883. var mousewheel = this.inputs.attached["mousewheel"];
  48884. if (mousewheel)
  48885. return mousewheel.wheelPrecision;
  48886. return 0;
  48887. },
  48888. set: function (value) {
  48889. var mousewheel = this.inputs.attached["mousewheel"];
  48890. if (mousewheel)
  48891. mousewheel.wheelPrecision = value;
  48892. },
  48893. enumerable: true,
  48894. configurable: true
  48895. });
  48896. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48897. get: function () {
  48898. var mousewheel = this.inputs.attached["mousewheel"];
  48899. if (mousewheel)
  48900. return mousewheel.wheelDeltaPercentage;
  48901. return 0;
  48902. },
  48903. set: function (value) {
  48904. var mousewheel = this.inputs.attached["mousewheel"];
  48905. if (mousewheel)
  48906. mousewheel.wheelDeltaPercentage = value;
  48907. },
  48908. enumerable: true,
  48909. configurable: true
  48910. });
  48911. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48912. get: function () {
  48913. return this._bouncingBehavior;
  48914. },
  48915. enumerable: true,
  48916. configurable: true
  48917. });
  48918. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48919. get: function () {
  48920. return this._bouncingBehavior != null;
  48921. },
  48922. set: function (value) {
  48923. if (value === this.useBouncingBehavior) {
  48924. return;
  48925. }
  48926. if (value) {
  48927. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48928. this.addBehavior(this._bouncingBehavior);
  48929. }
  48930. else if (this._bouncingBehavior) {
  48931. this.removeBehavior(this._bouncingBehavior);
  48932. this._bouncingBehavior = null;
  48933. }
  48934. },
  48935. enumerable: true,
  48936. configurable: true
  48937. });
  48938. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48939. get: function () {
  48940. return this._framingBehavior;
  48941. },
  48942. enumerable: true,
  48943. configurable: true
  48944. });
  48945. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48946. get: function () {
  48947. return this._framingBehavior != null;
  48948. },
  48949. set: function (value) {
  48950. if (value === this.useFramingBehavior) {
  48951. return;
  48952. }
  48953. if (value) {
  48954. this._framingBehavior = new BABYLON.FramingBehavior();
  48955. this.addBehavior(this._framingBehavior);
  48956. }
  48957. else if (this._framingBehavior) {
  48958. this.removeBehavior(this._framingBehavior);
  48959. this._framingBehavior = null;
  48960. }
  48961. },
  48962. enumerable: true,
  48963. configurable: true
  48964. });
  48965. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48966. get: function () {
  48967. return this._autoRotationBehavior;
  48968. },
  48969. enumerable: true,
  48970. configurable: true
  48971. });
  48972. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48973. get: function () {
  48974. return this._autoRotationBehavior != null;
  48975. },
  48976. set: function (value) {
  48977. if (value === this.useAutoRotationBehavior) {
  48978. return;
  48979. }
  48980. if (value) {
  48981. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48982. this.addBehavior(this._autoRotationBehavior);
  48983. }
  48984. else if (this._autoRotationBehavior) {
  48985. this.removeBehavior(this._autoRotationBehavior);
  48986. this._autoRotationBehavior = null;
  48987. }
  48988. },
  48989. enumerable: true,
  48990. configurable: true
  48991. });
  48992. // Cache
  48993. ArcRotateCamera.prototype._initCache = function () {
  48994. _super.prototype._initCache.call(this);
  48995. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48996. this._cache.alpha = undefined;
  48997. this._cache.beta = undefined;
  48998. this._cache.radius = undefined;
  48999. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49000. };
  49001. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49002. if (!ignoreParentClass) {
  49003. _super.prototype._updateCache.call(this);
  49004. }
  49005. this._cache._target.copyFrom(this._getTargetPosition());
  49006. this._cache.alpha = this.alpha;
  49007. this._cache.beta = this.beta;
  49008. this._cache.radius = this.radius;
  49009. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49010. };
  49011. ArcRotateCamera.prototype._getTargetPosition = function () {
  49012. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49013. var pos = this._targetHost.getAbsolutePosition();
  49014. if (this._targetBoundingCenter) {
  49015. pos.addToRef(this._targetBoundingCenter, this._target);
  49016. }
  49017. else {
  49018. this._target.copyFrom(pos);
  49019. }
  49020. }
  49021. var lockedTargetPosition = this._getLockedTargetPosition();
  49022. if (lockedTargetPosition) {
  49023. return lockedTargetPosition;
  49024. }
  49025. return this._target;
  49026. };
  49027. ArcRotateCamera.prototype.storeState = function () {
  49028. this._storedAlpha = this.alpha;
  49029. this._storedBeta = this.beta;
  49030. this._storedRadius = this.radius;
  49031. this._storedTarget = this._getTargetPosition().clone();
  49032. return _super.prototype.storeState.call(this);
  49033. };
  49034. /**
  49035. * Restored camera state. You must call storeState() first
  49036. */
  49037. ArcRotateCamera.prototype._restoreStateValues = function () {
  49038. if (!_super.prototype._restoreStateValues.call(this)) {
  49039. return false;
  49040. }
  49041. this.alpha = this._storedAlpha;
  49042. this.beta = this._storedBeta;
  49043. this.radius = this._storedRadius;
  49044. this.setTarget(this._storedTarget.clone());
  49045. this.inertialAlphaOffset = 0;
  49046. this.inertialBetaOffset = 0;
  49047. this.inertialRadiusOffset = 0;
  49048. this.inertialPanningX = 0;
  49049. this.inertialPanningY = 0;
  49050. return true;
  49051. };
  49052. // Synchronized
  49053. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49054. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49055. return false;
  49056. return this._cache._target.equals(this._getTargetPosition())
  49057. && this._cache.alpha === this.alpha
  49058. && this._cache.beta === this.beta
  49059. && this._cache.radius === this.radius
  49060. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49061. };
  49062. // Methods
  49063. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49064. var _this = this;
  49065. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49066. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49067. this._useCtrlForPanning = useCtrlForPanning;
  49068. this._panningMouseButton = panningMouseButton;
  49069. this.inputs.attachElement(element, noPreventDefault);
  49070. this._reset = function () {
  49071. _this.inertialAlphaOffset = 0;
  49072. _this.inertialBetaOffset = 0;
  49073. _this.inertialRadiusOffset = 0;
  49074. _this.inertialPanningX = 0;
  49075. _this.inertialPanningY = 0;
  49076. };
  49077. };
  49078. ArcRotateCamera.prototype.detachControl = function (element) {
  49079. this.inputs.detachElement(element);
  49080. if (this._reset) {
  49081. this._reset();
  49082. }
  49083. };
  49084. ArcRotateCamera.prototype._checkInputs = function () {
  49085. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49086. if (this._collisionTriggered) {
  49087. return;
  49088. }
  49089. this.inputs.checkInputs();
  49090. // Inertia
  49091. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49092. var inertialAlphaOffset = this.inertialAlphaOffset;
  49093. if (this.beta <= 0)
  49094. inertialAlphaOffset *= -1;
  49095. if (this.getScene().useRightHandedSystem)
  49096. inertialAlphaOffset *= -1;
  49097. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49098. inertialAlphaOffset *= -1;
  49099. this.alpha += inertialAlphaOffset;
  49100. this.beta += this.inertialBetaOffset;
  49101. this.radius -= this.inertialRadiusOffset;
  49102. this.inertialAlphaOffset *= this.inertia;
  49103. this.inertialBetaOffset *= this.inertia;
  49104. this.inertialRadiusOffset *= this.inertia;
  49105. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49106. this.inertialAlphaOffset = 0;
  49107. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49108. this.inertialBetaOffset = 0;
  49109. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49110. this.inertialRadiusOffset = 0;
  49111. }
  49112. // Panning inertia
  49113. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49114. if (!this._localDirection) {
  49115. this._localDirection = BABYLON.Vector3.Zero();
  49116. this._transformedDirection = BABYLON.Vector3.Zero();
  49117. }
  49118. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49119. this._localDirection.multiplyInPlace(this.panningAxis);
  49120. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49121. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49122. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49123. if (!this.panningAxis.y) {
  49124. this._transformedDirection.y = 0;
  49125. }
  49126. if (!this._targetHost) {
  49127. if (this.panningDistanceLimit) {
  49128. this._transformedDirection.addInPlace(this._target);
  49129. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49130. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49131. this._target.copyFrom(this._transformedDirection);
  49132. }
  49133. }
  49134. else {
  49135. this._target.addInPlace(this._transformedDirection);
  49136. }
  49137. }
  49138. this.inertialPanningX *= this.panningInertia;
  49139. this.inertialPanningY *= this.panningInertia;
  49140. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49141. this.inertialPanningX = 0;
  49142. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49143. this.inertialPanningY = 0;
  49144. }
  49145. // Limits
  49146. this._checkLimits();
  49147. _super.prototype._checkInputs.call(this);
  49148. };
  49149. ArcRotateCamera.prototype._checkLimits = function () {
  49150. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49151. if (this.allowUpsideDown && this.beta > Math.PI) {
  49152. this.beta = this.beta - (2 * Math.PI);
  49153. }
  49154. }
  49155. else {
  49156. if (this.beta < this.lowerBetaLimit) {
  49157. this.beta = this.lowerBetaLimit;
  49158. }
  49159. }
  49160. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49161. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49162. this.beta = this.beta + (2 * Math.PI);
  49163. }
  49164. }
  49165. else {
  49166. if (this.beta > this.upperBetaLimit) {
  49167. this.beta = this.upperBetaLimit;
  49168. }
  49169. }
  49170. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49171. this.alpha = this.lowerAlphaLimit;
  49172. }
  49173. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49174. this.alpha = this.upperAlphaLimit;
  49175. }
  49176. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49177. this.radius = this.lowerRadiusLimit;
  49178. }
  49179. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49180. this.radius = this.upperRadiusLimit;
  49181. }
  49182. };
  49183. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49184. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49185. this.radius = this._computationVector.length();
  49186. if (this.radius === 0) {
  49187. this.radius = 0.0001; // Just to avoid division by zero
  49188. }
  49189. // Alpha
  49190. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49191. if (this._computationVector.z < 0) {
  49192. this.alpha = 2 * Math.PI - this.alpha;
  49193. }
  49194. // Beta
  49195. this.beta = Math.acos(this._computationVector.y / this.radius);
  49196. this._checkLimits();
  49197. };
  49198. ArcRotateCamera.prototype.setPosition = function (position) {
  49199. if (this.position.equals(position)) {
  49200. return;
  49201. }
  49202. this.position.copyFrom(position);
  49203. this.rebuildAnglesAndRadius();
  49204. };
  49205. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49206. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49207. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49208. if (target.getBoundingInfo) {
  49209. if (toBoundingCenter) {
  49210. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49211. }
  49212. else {
  49213. this._targetBoundingCenter = null;
  49214. }
  49215. this._targetHost = target;
  49216. this._target = this._getTargetPosition();
  49217. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49218. }
  49219. else {
  49220. var newTarget = target;
  49221. var currentTarget = this._getTargetPosition();
  49222. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49223. return;
  49224. }
  49225. this._targetHost = null;
  49226. this._target = newTarget;
  49227. this._targetBoundingCenter = null;
  49228. this.onMeshTargetChangedObservable.notifyObservers(null);
  49229. }
  49230. this.rebuildAnglesAndRadius();
  49231. };
  49232. ArcRotateCamera.prototype._getViewMatrix = function () {
  49233. // Compute
  49234. var cosa = Math.cos(this.alpha);
  49235. var sina = Math.sin(this.alpha);
  49236. var cosb = Math.cos(this.beta);
  49237. var sinb = Math.sin(this.beta);
  49238. if (sinb === 0) {
  49239. sinb = 0.0001;
  49240. }
  49241. var target = this._getTargetPosition();
  49242. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49243. target.addToRef(this._computationVector, this._newPosition);
  49244. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49245. if (!this._collider) {
  49246. this._collider = new BABYLON.Collider();
  49247. }
  49248. this._collider._radius = this.collisionRadius;
  49249. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49250. this._collisionTriggered = true;
  49251. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49252. }
  49253. else {
  49254. this.position.copyFrom(this._newPosition);
  49255. var up = this.upVector;
  49256. if (this.allowUpsideDown && sinb < 0) {
  49257. up = up.clone();
  49258. up = up.negate();
  49259. }
  49260. this._computeViewMatrix(this.position, target, up);
  49261. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49262. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49263. }
  49264. this._currentTarget = target;
  49265. return this._viewMatrix;
  49266. };
  49267. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49268. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49269. meshes = meshes || this.getScene().meshes;
  49270. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49271. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49272. this.radius = distance * this.zoomOnFactor;
  49273. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49274. };
  49275. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49276. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49277. var meshesOrMinMaxVector;
  49278. var distance;
  49279. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49280. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49281. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49282. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49283. }
  49284. else { //minMaxVector and distance
  49285. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49286. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49287. distance = minMaxVectorAndDistance.distance;
  49288. }
  49289. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49290. if (!doNotUpdateMaxZ) {
  49291. this.maxZ = distance * 2;
  49292. }
  49293. };
  49294. /**
  49295. * @override
  49296. * Override Camera.createRigCamera
  49297. */
  49298. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49299. var alphaShift = 0;
  49300. switch (this.cameraRigMode) {
  49301. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49302. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49303. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49304. case BABYLON.Camera.RIG_MODE_VR:
  49305. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49306. break;
  49307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49308. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49309. break;
  49310. }
  49311. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49312. rigCam._cameraRigParams = {};
  49313. return rigCam;
  49314. };
  49315. /**
  49316. * @override
  49317. * Override Camera._updateRigCameras
  49318. */
  49319. ArcRotateCamera.prototype._updateRigCameras = function () {
  49320. var camLeft = this._rigCameras[0];
  49321. var camRight = this._rigCameras[1];
  49322. camLeft.beta = camRight.beta = this.beta;
  49323. camLeft.radius = camRight.radius = this.radius;
  49324. switch (this.cameraRigMode) {
  49325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49326. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49327. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49328. case BABYLON.Camera.RIG_MODE_VR:
  49329. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49330. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49331. break;
  49332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49333. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49334. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49335. break;
  49336. }
  49337. _super.prototype._updateRigCameras.call(this);
  49338. };
  49339. ArcRotateCamera.prototype.dispose = function () {
  49340. this.inputs.clear();
  49341. _super.prototype.dispose.call(this);
  49342. };
  49343. ArcRotateCamera.prototype.getClassName = function () {
  49344. return "ArcRotateCamera";
  49345. };
  49346. __decorate([
  49347. BABYLON.serialize()
  49348. ], ArcRotateCamera.prototype, "alpha", void 0);
  49349. __decorate([
  49350. BABYLON.serialize()
  49351. ], ArcRotateCamera.prototype, "beta", void 0);
  49352. __decorate([
  49353. BABYLON.serialize()
  49354. ], ArcRotateCamera.prototype, "radius", void 0);
  49355. __decorate([
  49356. BABYLON.serializeAsVector3("target")
  49357. ], ArcRotateCamera.prototype, "_target", void 0);
  49358. __decorate([
  49359. BABYLON.serialize()
  49360. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49361. __decorate([
  49362. BABYLON.serialize()
  49363. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49367. __decorate([
  49368. BABYLON.serialize()
  49369. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49370. __decorate([
  49371. BABYLON.serialize()
  49372. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49373. __decorate([
  49374. BABYLON.serialize()
  49375. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49376. __decorate([
  49377. BABYLON.serialize()
  49378. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49379. __decorate([
  49380. BABYLON.serialize()
  49381. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49382. __decorate([
  49383. BABYLON.serialize()
  49384. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49385. __decorate([
  49386. BABYLON.serialize()
  49387. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49388. __decorate([
  49389. BABYLON.serialize()
  49390. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49391. __decorate([
  49392. BABYLON.serialize()
  49393. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49394. __decorate([
  49395. BABYLON.serialize()
  49396. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49397. __decorate([
  49398. BABYLON.serializeAsVector3()
  49399. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49400. __decorate([
  49401. BABYLON.serialize()
  49402. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49403. __decorate([
  49404. BABYLON.serialize()
  49405. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49406. __decorate([
  49407. BABYLON.serialize()
  49408. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49409. return ArcRotateCamera;
  49410. }(BABYLON.TargetCamera));
  49411. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49412. })(BABYLON || (BABYLON = {}));
  49413. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49414. var BABYLON;
  49415. (function (BABYLON) {
  49416. /**
  49417. * The HemisphericLight simulates the ambient environment light,
  49418. * so the passed direction is the light reflection direction, not the incoming direction.
  49419. */
  49420. var HemisphericLight = /** @class */ (function (_super) {
  49421. __extends(HemisphericLight, _super);
  49422. /**
  49423. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49424. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49425. * The HemisphericLight can't cast shadows.
  49426. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49427. * @param name The friendly name of the light
  49428. * @param direction The direction of the light reflection
  49429. * @param scene The scene the light belongs to
  49430. */
  49431. function HemisphericLight(name, direction, scene) {
  49432. var _this = _super.call(this, name, scene) || this;
  49433. /**
  49434. * The groundColor is the light in the opposite direction to the one specified during creation.
  49435. * 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.
  49436. */
  49437. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49438. _this.direction = direction || BABYLON.Vector3.Up();
  49439. return _this;
  49440. }
  49441. HemisphericLight.prototype._buildUniformLayout = function () {
  49442. this._uniformBuffer.addUniform("vLightData", 4);
  49443. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49444. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49445. this._uniformBuffer.addUniform("vLightGround", 3);
  49446. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49447. this._uniformBuffer.addUniform("depthValues", 2);
  49448. this._uniformBuffer.create();
  49449. };
  49450. /**
  49451. * Returns the string "HemisphericLight".
  49452. * @return The class name
  49453. */
  49454. HemisphericLight.prototype.getClassName = function () {
  49455. return "HemisphericLight";
  49456. };
  49457. /**
  49458. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49459. * Returns the updated direction.
  49460. * @param target The target the direction should point to
  49461. * @return The computed direction
  49462. */
  49463. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49464. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49465. return this.direction;
  49466. };
  49467. /**
  49468. * Returns the shadow generator associated to the light.
  49469. * @returns Always null for hemispheric lights because it does not support shadows.
  49470. */
  49471. HemisphericLight.prototype.getShadowGenerator = function () {
  49472. return null;
  49473. };
  49474. /**
  49475. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49476. * @param effect The effect to update
  49477. * @param lightIndex The index of the light in the effect to update
  49478. * @returns The hemispheric light
  49479. */
  49480. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49481. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49482. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49483. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49484. return this;
  49485. };
  49486. /**
  49487. * @hidden internal use only.
  49488. */
  49489. HemisphericLight.prototype._getWorldMatrix = function () {
  49490. if (!this._worldMatrix) {
  49491. this._worldMatrix = BABYLON.Matrix.Identity();
  49492. }
  49493. return this._worldMatrix;
  49494. };
  49495. /**
  49496. * Returns the integer 3.
  49497. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49498. */
  49499. HemisphericLight.prototype.getTypeID = function () {
  49500. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49501. };
  49502. __decorate([
  49503. BABYLON.serializeAsColor3()
  49504. ], HemisphericLight.prototype, "groundColor", void 0);
  49505. __decorate([
  49506. BABYLON.serializeAsVector3()
  49507. ], HemisphericLight.prototype, "direction", void 0);
  49508. return HemisphericLight;
  49509. }(BABYLON.Light));
  49510. BABYLON.HemisphericLight = HemisphericLight;
  49511. })(BABYLON || (BABYLON = {}));
  49512. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49513. var BABYLON;
  49514. (function (BABYLON) {
  49515. /**
  49516. * Base implementation IShadowLight
  49517. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49518. */
  49519. var ShadowLight = /** @class */ (function (_super) {
  49520. __extends(ShadowLight, _super);
  49521. function ShadowLight() {
  49522. var _this = _super !== null && _super.apply(this, arguments) || this;
  49523. _this._needProjectionMatrixCompute = true;
  49524. return _this;
  49525. }
  49526. ShadowLight.prototype._setPosition = function (value) {
  49527. this._position = value;
  49528. };
  49529. Object.defineProperty(ShadowLight.prototype, "position", {
  49530. /**
  49531. * Sets the position the shadow will be casted from. Also use as the light position for both
  49532. * point and spot lights.
  49533. */
  49534. get: function () {
  49535. return this._position;
  49536. },
  49537. /**
  49538. * Sets the position the shadow will be casted from. Also use as the light position for both
  49539. * point and spot lights.
  49540. */
  49541. set: function (value) {
  49542. this._setPosition(value);
  49543. },
  49544. enumerable: true,
  49545. configurable: true
  49546. });
  49547. ShadowLight.prototype._setDirection = function (value) {
  49548. this._direction = value;
  49549. };
  49550. Object.defineProperty(ShadowLight.prototype, "direction", {
  49551. /**
  49552. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49553. * Also use as the light direction on spot and directional lights.
  49554. */
  49555. get: function () {
  49556. return this._direction;
  49557. },
  49558. /**
  49559. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49560. * Also use as the light direction on spot and directional lights.
  49561. */
  49562. set: function (value) {
  49563. this._setDirection(value);
  49564. },
  49565. enumerable: true,
  49566. configurable: true
  49567. });
  49568. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49569. /**
  49570. * Gets the shadow projection clipping minimum z value.
  49571. */
  49572. get: function () {
  49573. return this._shadowMinZ;
  49574. },
  49575. /**
  49576. * Sets the shadow projection clipping minimum z value.
  49577. */
  49578. set: function (value) {
  49579. this._shadowMinZ = value;
  49580. this.forceProjectionMatrixCompute();
  49581. },
  49582. enumerable: true,
  49583. configurable: true
  49584. });
  49585. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49586. /**
  49587. * Sets the shadow projection clipping maximum z value.
  49588. */
  49589. get: function () {
  49590. return this._shadowMaxZ;
  49591. },
  49592. /**
  49593. * Gets the shadow projection clipping maximum z value.
  49594. */
  49595. set: function (value) {
  49596. this._shadowMaxZ = value;
  49597. this.forceProjectionMatrixCompute();
  49598. },
  49599. enumerable: true,
  49600. configurable: true
  49601. });
  49602. /**
  49603. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49604. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49605. */
  49606. ShadowLight.prototype.computeTransformedInformation = function () {
  49607. if (this.parent && this.parent.getWorldMatrix) {
  49608. if (!this.transformedPosition) {
  49609. this.transformedPosition = BABYLON.Vector3.Zero();
  49610. }
  49611. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49612. // In case the direction is present.
  49613. if (this.direction) {
  49614. if (!this.transformedDirection) {
  49615. this.transformedDirection = BABYLON.Vector3.Zero();
  49616. }
  49617. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49618. }
  49619. return true;
  49620. }
  49621. return false;
  49622. };
  49623. /**
  49624. * Return the depth scale used for the shadow map.
  49625. * @returns the depth scale.
  49626. */
  49627. ShadowLight.prototype.getDepthScale = function () {
  49628. return 50.0;
  49629. };
  49630. /**
  49631. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49632. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49633. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49634. */
  49635. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49636. return this.transformedDirection ? this.transformedDirection : this.direction;
  49637. };
  49638. /**
  49639. * Returns the ShadowLight absolute position in the World.
  49640. * @returns the position vector in world space
  49641. */
  49642. ShadowLight.prototype.getAbsolutePosition = function () {
  49643. return this.transformedPosition ? this.transformedPosition : this.position;
  49644. };
  49645. /**
  49646. * Sets the ShadowLight direction toward the passed target.
  49647. * @param target The point tot target in local space
  49648. * @returns the updated ShadowLight direction
  49649. */
  49650. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49651. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49652. return this.direction;
  49653. };
  49654. /**
  49655. * Returns the light rotation in euler definition.
  49656. * @returns the x y z rotation in local space.
  49657. */
  49658. ShadowLight.prototype.getRotation = function () {
  49659. this.direction.normalize();
  49660. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49661. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49662. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49663. };
  49664. /**
  49665. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49666. * @returns true if a cube texture needs to be use
  49667. */
  49668. ShadowLight.prototype.needCube = function () {
  49669. return false;
  49670. };
  49671. /**
  49672. * Detects if the projection matrix requires to be recomputed this frame.
  49673. * @returns true if it requires to be recomputed otherwise, false.
  49674. */
  49675. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49676. return this._needProjectionMatrixCompute;
  49677. };
  49678. /**
  49679. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49680. */
  49681. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49682. this._needProjectionMatrixCompute = true;
  49683. };
  49684. /**
  49685. * Get the world matrix of the sahdow lights.
  49686. * @hidden Internal Use Only
  49687. */
  49688. ShadowLight.prototype._getWorldMatrix = function () {
  49689. if (!this._worldMatrix) {
  49690. this._worldMatrix = BABYLON.Matrix.Identity();
  49691. }
  49692. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49693. return this._worldMatrix;
  49694. };
  49695. /**
  49696. * Gets the minZ used for shadow according to both the scene and the light.
  49697. * @param activeCamera The camera we are returning the min for
  49698. * @returns the depth min z
  49699. */
  49700. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49701. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49702. };
  49703. /**
  49704. * Gets the maxZ used for shadow according to both the scene and the light.
  49705. * @param activeCamera The camera we are returning the max for
  49706. * @returns the depth max z
  49707. */
  49708. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49709. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49710. };
  49711. /**
  49712. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49713. * @param matrix The materix to updated with the projection information
  49714. * @param viewMatrix The transform matrix of the light
  49715. * @param renderList The list of mesh to render in the map
  49716. * @returns The current light
  49717. */
  49718. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49719. if (this.customProjectionMatrixBuilder) {
  49720. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49721. }
  49722. else {
  49723. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49724. }
  49725. return this;
  49726. };
  49727. __decorate([
  49728. BABYLON.serializeAsVector3()
  49729. ], ShadowLight.prototype, "position", null);
  49730. __decorate([
  49731. BABYLON.serializeAsVector3()
  49732. ], ShadowLight.prototype, "direction", null);
  49733. __decorate([
  49734. BABYLON.serialize()
  49735. ], ShadowLight.prototype, "shadowMinZ", null);
  49736. __decorate([
  49737. BABYLON.serialize()
  49738. ], ShadowLight.prototype, "shadowMaxZ", null);
  49739. return ShadowLight;
  49740. }(BABYLON.Light));
  49741. BABYLON.ShadowLight = ShadowLight;
  49742. })(BABYLON || (BABYLON = {}));
  49743. //# sourceMappingURL=babylon.shadowLight.js.map
  49744. var BABYLON;
  49745. (function (BABYLON) {
  49746. /**
  49747. * A point light is a light defined by an unique point in world space.
  49748. * The light is emitted in every direction from this point.
  49749. * A good example of a point light is a standard light bulb.
  49750. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49751. */
  49752. var PointLight = /** @class */ (function (_super) {
  49753. __extends(PointLight, _super);
  49754. /**
  49755. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49756. * A PointLight emits the light in every direction.
  49757. * It can cast shadows.
  49758. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49759. * ```javascript
  49760. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49761. * ```
  49762. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49763. * @param name The light friendly name
  49764. * @param position The position of the point light in the scene
  49765. * @param scene The scene the lights belongs to
  49766. */
  49767. function PointLight(name, position, scene) {
  49768. var _this = _super.call(this, name, scene) || this;
  49769. _this._shadowAngle = Math.PI / 2;
  49770. _this.position = position;
  49771. return _this;
  49772. }
  49773. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49774. /**
  49775. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49776. * This specifies what angle the shadow will use to be created.
  49777. *
  49778. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49779. */
  49780. get: function () {
  49781. return this._shadowAngle;
  49782. },
  49783. /**
  49784. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49785. * This specifies what angle the shadow will use to be created.
  49786. *
  49787. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49788. */
  49789. set: function (value) {
  49790. this._shadowAngle = value;
  49791. this.forceProjectionMatrixCompute();
  49792. },
  49793. enumerable: true,
  49794. configurable: true
  49795. });
  49796. Object.defineProperty(PointLight.prototype, "direction", {
  49797. /**
  49798. * Gets the direction if it has been set.
  49799. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49800. */
  49801. get: function () {
  49802. return this._direction;
  49803. },
  49804. /**
  49805. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49806. */
  49807. set: function (value) {
  49808. var previousNeedCube = this.needCube();
  49809. this._direction = value;
  49810. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49811. this._shadowGenerator.recreateShadowMap();
  49812. }
  49813. },
  49814. enumerable: true,
  49815. configurable: true
  49816. });
  49817. /**
  49818. * Returns the string "PointLight"
  49819. * @returns the class name
  49820. */
  49821. PointLight.prototype.getClassName = function () {
  49822. return "PointLight";
  49823. };
  49824. /**
  49825. * Returns the integer 0.
  49826. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49827. */
  49828. PointLight.prototype.getTypeID = function () {
  49829. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49830. };
  49831. /**
  49832. * Specifies wether or not the shadowmap should be a cube texture.
  49833. * @returns true if the shadowmap needs to be a cube texture.
  49834. */
  49835. PointLight.prototype.needCube = function () {
  49836. return !this.direction;
  49837. };
  49838. /**
  49839. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49840. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49841. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49842. */
  49843. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49844. if (this.direction) {
  49845. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49846. }
  49847. else {
  49848. switch (faceIndex) {
  49849. case 0:
  49850. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49851. case 1:
  49852. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49853. case 2:
  49854. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49855. case 3:
  49856. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49857. case 4:
  49858. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49859. case 5:
  49860. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49861. }
  49862. }
  49863. return BABYLON.Vector3.Zero();
  49864. };
  49865. /**
  49866. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49867. * - fov = PI / 2
  49868. * - aspect ratio : 1.0
  49869. * - z-near and far equal to the active camera minZ and maxZ.
  49870. * Returns the PointLight.
  49871. */
  49872. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49873. var activeCamera = this.getScene().activeCamera;
  49874. if (!activeCamera) {
  49875. return;
  49876. }
  49877. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49878. };
  49879. PointLight.prototype._buildUniformLayout = function () {
  49880. this._uniformBuffer.addUniform("vLightData", 4);
  49881. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49882. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49883. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49884. this._uniformBuffer.addUniform("depthValues", 2);
  49885. this._uniformBuffer.create();
  49886. };
  49887. /**
  49888. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49889. * @param effect The effect to update
  49890. * @param lightIndex The index of the light in the effect to update
  49891. * @returns The point light
  49892. */
  49893. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49894. if (this.computeTransformedInformation()) {
  49895. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49896. return this;
  49897. }
  49898. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49899. return this;
  49900. };
  49901. __decorate([
  49902. BABYLON.serialize()
  49903. ], PointLight.prototype, "shadowAngle", null);
  49904. return PointLight;
  49905. }(BABYLON.ShadowLight));
  49906. BABYLON.PointLight = PointLight;
  49907. })(BABYLON || (BABYLON = {}));
  49908. //# sourceMappingURL=babylon.pointLight.js.map
  49909. var BABYLON;
  49910. (function (BABYLON) {
  49911. /**
  49912. * A directional light is defined by a direction (what a surprise!).
  49913. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49914. * 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.
  49915. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49916. */
  49917. var DirectionalLight = /** @class */ (function (_super) {
  49918. __extends(DirectionalLight, _super);
  49919. /**
  49920. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49921. * The directional light is emitted from everywhere in the given direction.
  49922. * It can cast shawdows.
  49923. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49924. * @param name The friendly name of the light
  49925. * @param direction The direction of the light
  49926. * @param scene The scene the light belongs to
  49927. */
  49928. function DirectionalLight(name, direction, scene) {
  49929. var _this = _super.call(this, name, scene) || this;
  49930. _this._shadowFrustumSize = 0;
  49931. _this._shadowOrthoScale = 0.1;
  49932. /**
  49933. * Automatically compute the projection matrix to best fit (including all the casters)
  49934. * on each frame.
  49935. */
  49936. _this.autoUpdateExtends = true;
  49937. // Cache
  49938. _this._orthoLeft = Number.MAX_VALUE;
  49939. _this._orthoRight = Number.MIN_VALUE;
  49940. _this._orthoTop = Number.MIN_VALUE;
  49941. _this._orthoBottom = Number.MAX_VALUE;
  49942. _this.position = direction.scale(-1.0);
  49943. _this.direction = direction;
  49944. return _this;
  49945. }
  49946. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49947. /**
  49948. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49949. */
  49950. get: function () {
  49951. return this._shadowFrustumSize;
  49952. },
  49953. /**
  49954. * Specifies a fix frustum size for the shadow generation.
  49955. */
  49956. set: function (value) {
  49957. this._shadowFrustumSize = value;
  49958. this.forceProjectionMatrixCompute();
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49964. /**
  49965. * Gets the shadow projection scale against the optimal computed one.
  49966. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49967. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49968. */
  49969. get: function () {
  49970. return this._shadowOrthoScale;
  49971. },
  49972. /**
  49973. * Sets the shadow projection scale against the optimal computed one.
  49974. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49975. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49976. */
  49977. set: function (value) {
  49978. this._shadowOrthoScale = value;
  49979. this.forceProjectionMatrixCompute();
  49980. },
  49981. enumerable: true,
  49982. configurable: true
  49983. });
  49984. /**
  49985. * Returns the string "DirectionalLight".
  49986. * @return The class name
  49987. */
  49988. DirectionalLight.prototype.getClassName = function () {
  49989. return "DirectionalLight";
  49990. };
  49991. /**
  49992. * Returns the integer 1.
  49993. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49994. */
  49995. DirectionalLight.prototype.getTypeID = function () {
  49996. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49997. };
  49998. /**
  49999. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50000. * Returns the DirectionalLight Shadow projection matrix.
  50001. */
  50002. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50003. if (this.shadowFrustumSize > 0) {
  50004. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50005. }
  50006. else {
  50007. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50008. }
  50009. };
  50010. /**
  50011. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50012. * Returns the DirectionalLight Shadow projection matrix.
  50013. */
  50014. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50015. var activeCamera = this.getScene().activeCamera;
  50016. if (!activeCamera) {
  50017. return;
  50018. }
  50019. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50020. };
  50021. /**
  50022. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50023. * Returns the DirectionalLight Shadow projection matrix.
  50024. */
  50025. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50026. var activeCamera = this.getScene().activeCamera;
  50027. if (!activeCamera) {
  50028. return;
  50029. }
  50030. // Check extends
  50031. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50032. var tempVector3 = BABYLON.Vector3.Zero();
  50033. this._orthoLeft = Number.MAX_VALUE;
  50034. this._orthoRight = Number.MIN_VALUE;
  50035. this._orthoTop = Number.MIN_VALUE;
  50036. this._orthoBottom = Number.MAX_VALUE;
  50037. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50038. var mesh = renderList[meshIndex];
  50039. if (!mesh) {
  50040. continue;
  50041. }
  50042. var boundingInfo = mesh.getBoundingInfo();
  50043. var boundingBox = boundingInfo.boundingBox;
  50044. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50045. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50046. if (tempVector3.x < this._orthoLeft)
  50047. this._orthoLeft = tempVector3.x;
  50048. if (tempVector3.y < this._orthoBottom)
  50049. this._orthoBottom = tempVector3.y;
  50050. if (tempVector3.x > this._orthoRight)
  50051. this._orthoRight = tempVector3.x;
  50052. if (tempVector3.y > this._orthoTop)
  50053. this._orthoTop = tempVector3.y;
  50054. }
  50055. }
  50056. }
  50057. var xOffset = this._orthoRight - this._orthoLeft;
  50058. var yOffset = this._orthoTop - this._orthoBottom;
  50059. 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);
  50060. };
  50061. DirectionalLight.prototype._buildUniformLayout = function () {
  50062. this._uniformBuffer.addUniform("vLightData", 4);
  50063. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50064. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50065. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50066. this._uniformBuffer.addUniform("depthValues", 2);
  50067. this._uniformBuffer.create();
  50068. };
  50069. /**
  50070. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50071. * @param effect The effect to update
  50072. * @param lightIndex The index of the light in the effect to update
  50073. * @returns The directional light
  50074. */
  50075. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50076. if (this.computeTransformedInformation()) {
  50077. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50078. return this;
  50079. }
  50080. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50081. return this;
  50082. };
  50083. /**
  50084. * Gets the minZ used for shadow according to both the scene and the light.
  50085. *
  50086. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50087. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50088. * @param activeCamera The camera we are returning the min for
  50089. * @returns the depth min z
  50090. */
  50091. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50092. return 1;
  50093. };
  50094. /**
  50095. * Gets the maxZ used for shadow according to both the scene and the light.
  50096. *
  50097. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50098. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50099. * @param activeCamera The camera we are returning the max for
  50100. * @returns the depth max z
  50101. */
  50102. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50103. return 1;
  50104. };
  50105. __decorate([
  50106. BABYLON.serialize()
  50107. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50108. __decorate([
  50109. BABYLON.serialize()
  50110. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50114. return DirectionalLight;
  50115. }(BABYLON.ShadowLight));
  50116. BABYLON.DirectionalLight = DirectionalLight;
  50117. })(BABYLON || (BABYLON = {}));
  50118. //# sourceMappingURL=babylon.directionalLight.js.map
  50119. var BABYLON;
  50120. (function (BABYLON) {
  50121. /**
  50122. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50123. * These values define a cone of light starting from the position, emitting toward the direction.
  50124. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50125. * and the exponent defines the speed of the decay of the light with distance (reach).
  50126. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50127. */
  50128. var SpotLight = /** @class */ (function (_super) {
  50129. __extends(SpotLight, _super);
  50130. /**
  50131. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50132. * It can cast shadows.
  50133. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50134. * @param name The light friendly name
  50135. * @param position The position of the spot light in the scene
  50136. * @param direction The direction of the light in the scene
  50137. * @param angle The cone angle of the light in Radians
  50138. * @param exponent The light decay speed with the distance from the emission spot
  50139. * @param scene The scene the lights belongs to
  50140. */
  50141. function SpotLight(name, position, direction, angle, exponent, scene) {
  50142. var _this = _super.call(this, name, scene) || this;
  50143. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50144. _this._projectionTextureLightNear = 1e-6;
  50145. _this._projectionTextureLightFar = 1000.0;
  50146. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50147. _this._projectionTextureViewLightDirty = true;
  50148. _this._projectionTextureProjectionLightDirty = true;
  50149. _this._projectionTextureDirty = true;
  50150. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50151. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50152. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50153. _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);
  50154. _this.position = position;
  50155. _this.direction = direction;
  50156. _this.angle = angle;
  50157. _this.exponent = exponent;
  50158. return _this;
  50159. }
  50160. Object.defineProperty(SpotLight.prototype, "angle", {
  50161. /**
  50162. * Gets the cone angle of the spot light in Radians.
  50163. */
  50164. get: function () {
  50165. return this._angle;
  50166. },
  50167. /**
  50168. * Sets the cone angle of the spot light in Radians.
  50169. */
  50170. set: function (value) {
  50171. this._angle = value;
  50172. this._projectionTextureProjectionLightDirty = true;
  50173. this.forceProjectionMatrixCompute();
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50179. /**
  50180. * Allows scaling the angle of the light for shadow generation only.
  50181. */
  50182. get: function () {
  50183. return this._shadowAngleScale;
  50184. },
  50185. /**
  50186. * Allows scaling the angle of the light for shadow generation only.
  50187. */
  50188. set: function (value) {
  50189. this._shadowAngleScale = value;
  50190. this.forceProjectionMatrixCompute();
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50196. /**
  50197. * Allows reading the projecton texture
  50198. */
  50199. get: function () {
  50200. return this._projectionTextureMatrix;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50206. /**
  50207. * Gets the near clip of the Spotlight for texture projection.
  50208. */
  50209. get: function () {
  50210. return this._projectionTextureLightNear;
  50211. },
  50212. /**
  50213. * Sets the near clip of the Spotlight for texture projection.
  50214. */
  50215. set: function (value) {
  50216. this._projectionTextureLightNear = value;
  50217. this._projectionTextureProjectionLightDirty = true;
  50218. },
  50219. enumerable: true,
  50220. configurable: true
  50221. });
  50222. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50223. /**
  50224. * Gets the far clip of the Spotlight for texture projection.
  50225. */
  50226. get: function () {
  50227. return this._projectionTextureLightFar;
  50228. },
  50229. /**
  50230. * Sets the far clip of the Spotlight for texture projection.
  50231. */
  50232. set: function (value) {
  50233. this._projectionTextureLightFar = value;
  50234. this._projectionTextureProjectionLightDirty = true;
  50235. },
  50236. enumerable: true,
  50237. configurable: true
  50238. });
  50239. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50240. /**
  50241. * Gets the Up vector of the Spotlight for texture projection.
  50242. */
  50243. get: function () {
  50244. return this._projectionTextureUpDirection;
  50245. },
  50246. /**
  50247. * Sets the Up vector of the Spotlight for texture projection.
  50248. */
  50249. set: function (value) {
  50250. this._projectionTextureUpDirection = value;
  50251. this._projectionTextureProjectionLightDirty = true;
  50252. },
  50253. enumerable: true,
  50254. configurable: true
  50255. });
  50256. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50257. /**
  50258. * Gets the projection texture of the light.
  50259. */
  50260. get: function () {
  50261. return this._projectionTexture;
  50262. },
  50263. /**
  50264. * Sets the projection texture of the light.
  50265. */
  50266. set: function (value) {
  50267. this._projectionTexture = value;
  50268. this._projectionTextureDirty = true;
  50269. },
  50270. enumerable: true,
  50271. configurable: true
  50272. });
  50273. /**
  50274. * Returns the string "SpotLight".
  50275. * @returns the class name
  50276. */
  50277. SpotLight.prototype.getClassName = function () {
  50278. return "SpotLight";
  50279. };
  50280. /**
  50281. * Returns the integer 2.
  50282. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50283. */
  50284. SpotLight.prototype.getTypeID = function () {
  50285. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50286. };
  50287. /**
  50288. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50289. */
  50290. SpotLight.prototype._setDirection = function (value) {
  50291. _super.prototype._setDirection.call(this, value);
  50292. this._projectionTextureViewLightDirty = true;
  50293. };
  50294. /**
  50295. * Overrides the position setter to recompute the projection texture view light Matrix.
  50296. */
  50297. SpotLight.prototype._setPosition = function (value) {
  50298. _super.prototype._setPosition.call(this, value);
  50299. this._projectionTextureViewLightDirty = true;
  50300. };
  50301. /**
  50302. * 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.
  50303. * Returns the SpotLight.
  50304. */
  50305. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50306. var activeCamera = this.getScene().activeCamera;
  50307. if (!activeCamera) {
  50308. return;
  50309. }
  50310. this._shadowAngleScale = this._shadowAngleScale || 1;
  50311. var angle = this._shadowAngleScale * this._angle;
  50312. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50313. };
  50314. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50315. this._projectionTextureViewLightDirty = false;
  50316. this._projectionTextureDirty = true;
  50317. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50318. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50319. };
  50320. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50321. this._projectionTextureProjectionLightDirty = false;
  50322. this._projectionTextureDirty = true;
  50323. var light_far = this.projectionTextureLightFar;
  50324. var light_near = this.projectionTextureLightNear;
  50325. var P = light_far / (light_far - light_near);
  50326. var Q = -P * light_near;
  50327. var S = 1.0 / Math.tan(this._angle / 2.0);
  50328. var A = 1.0;
  50329. 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);
  50330. };
  50331. /**
  50332. * Main function for light texture projection matrix computing.
  50333. */
  50334. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50335. this._projectionTextureDirty = false;
  50336. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50337. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50338. };
  50339. SpotLight.prototype._buildUniformLayout = function () {
  50340. this._uniformBuffer.addUniform("vLightData", 4);
  50341. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50342. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50343. this._uniformBuffer.addUniform("vLightDirection", 3);
  50344. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50345. this._uniformBuffer.addUniform("depthValues", 2);
  50346. this._uniformBuffer.create();
  50347. };
  50348. /**
  50349. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50350. * @param effect The effect to update
  50351. * @param lightIndex The index of the light in the effect to update
  50352. * @returns The spot light
  50353. */
  50354. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50355. var normalizeDirection;
  50356. if (this.computeTransformedInformation()) {
  50357. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50358. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50359. }
  50360. else {
  50361. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50362. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50363. }
  50364. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50365. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50366. if (this._projectionTextureViewLightDirty) {
  50367. this._computeProjectionTextureViewLightMatrix();
  50368. }
  50369. if (this._projectionTextureProjectionLightDirty) {
  50370. this._computeProjectionTextureProjectionLightMatrix();
  50371. }
  50372. if (this._projectionTextureDirty) {
  50373. this._computeProjectionTextureMatrix();
  50374. }
  50375. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50376. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50377. }
  50378. return this;
  50379. };
  50380. /**
  50381. * Disposes the light and the associated resources.
  50382. */
  50383. SpotLight.prototype.dispose = function () {
  50384. _super.prototype.dispose.call(this);
  50385. if (this._projectionTexture) {
  50386. this._projectionTexture.dispose();
  50387. }
  50388. };
  50389. __decorate([
  50390. BABYLON.serialize()
  50391. ], SpotLight.prototype, "angle", null);
  50392. __decorate([
  50393. BABYLON.serialize()
  50394. ], SpotLight.prototype, "shadowAngleScale", null);
  50395. __decorate([
  50396. BABYLON.serialize()
  50397. ], SpotLight.prototype, "exponent", void 0);
  50398. __decorate([
  50399. BABYLON.serialize()
  50400. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50401. __decorate([
  50402. BABYLON.serialize()
  50403. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50404. __decorate([
  50405. BABYLON.serialize()
  50406. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50407. __decorate([
  50408. BABYLON.serializeAsTexture("projectedLightTexture")
  50409. ], SpotLight.prototype, "_projectionTexture", void 0);
  50410. return SpotLight;
  50411. }(BABYLON.ShadowLight));
  50412. BABYLON.SpotLight = SpotLight;
  50413. })(BABYLON || (BABYLON = {}));
  50414. //# sourceMappingURL=babylon.spotLight.js.map
  50415. var BABYLON;
  50416. (function (BABYLON) {
  50417. /**
  50418. * Class used to override all child animations of a given target
  50419. */
  50420. var AnimationPropertiesOverride = /** @class */ (function () {
  50421. function AnimationPropertiesOverride() {
  50422. /**
  50423. * Gets or sets a value indicating if animation blending must be used
  50424. */
  50425. this.enableBlending = false;
  50426. /**
  50427. * Gets or sets the blending speed to use when enableBlending is true
  50428. */
  50429. this.blendingSpeed = 0.01;
  50430. /**
  50431. * Gets or sets the default loop mode to use
  50432. */
  50433. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50434. }
  50435. return AnimationPropertiesOverride;
  50436. }());
  50437. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50438. })(BABYLON || (BABYLON = {}));
  50439. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50440. var BABYLON;
  50441. (function (BABYLON) {
  50442. /**
  50443. * Represents the range of an animation
  50444. */
  50445. var AnimationRange = /** @class */ (function () {
  50446. /**
  50447. * Initializes the range of an animation
  50448. * @param name The name of the animation range
  50449. * @param from The starting frame of the animation
  50450. * @param to The ending frame of the animation
  50451. */
  50452. function AnimationRange(
  50453. /**The name of the animation range**/
  50454. name,
  50455. /**The starting frame of the animation */
  50456. from,
  50457. /**The ending frame of the animation*/
  50458. to) {
  50459. this.name = name;
  50460. this.from = from;
  50461. this.to = to;
  50462. }
  50463. /**
  50464. * Makes a copy of the animation range
  50465. * @returns A copy of the animation range
  50466. */
  50467. AnimationRange.prototype.clone = function () {
  50468. return new AnimationRange(this.name, this.from, this.to);
  50469. };
  50470. return AnimationRange;
  50471. }());
  50472. BABYLON.AnimationRange = AnimationRange;
  50473. /**
  50474. * Composed of a frame, and an action function
  50475. */
  50476. var AnimationEvent = /** @class */ (function () {
  50477. /**
  50478. * Initializes the animation event
  50479. * @param frame The frame for which the event is triggered
  50480. * @param action The event to perform when triggered
  50481. * @param onlyOnce Specifies if the event should be triggered only once
  50482. */
  50483. function AnimationEvent(
  50484. /** The frame for which the event is triggered **/
  50485. frame,
  50486. /** The event to perform when triggered **/
  50487. action,
  50488. /** Specifies if the event should be triggered only once**/
  50489. onlyOnce) {
  50490. this.frame = frame;
  50491. this.action = action;
  50492. this.onlyOnce = onlyOnce;
  50493. /**
  50494. * Specifies if the animation event is done
  50495. */
  50496. this.isDone = false;
  50497. }
  50498. /** @hidden */
  50499. AnimationEvent.prototype._clone = function () {
  50500. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50501. };
  50502. return AnimationEvent;
  50503. }());
  50504. BABYLON.AnimationEvent = AnimationEvent;
  50505. /**
  50506. * A cursor which tracks a point on a path
  50507. */
  50508. var PathCursor = /** @class */ (function () {
  50509. /**
  50510. * Initializes the path cursor
  50511. * @param path The path to track
  50512. */
  50513. function PathCursor(path) {
  50514. this.path = path;
  50515. /**
  50516. * Stores path cursor callbacks for when an onchange event is triggered
  50517. */
  50518. this._onchange = new Array();
  50519. /**
  50520. * The value of the path cursor
  50521. */
  50522. this.value = 0;
  50523. /**
  50524. * The animation array of the path cursor
  50525. */
  50526. this.animations = new Array();
  50527. }
  50528. /**
  50529. * Gets the cursor point on the path
  50530. * @returns A point on the path cursor at the cursor location
  50531. */
  50532. PathCursor.prototype.getPoint = function () {
  50533. var point = this.path.getPointAtLengthPosition(this.value);
  50534. return new BABYLON.Vector3(point.x, 0, point.y);
  50535. };
  50536. /**
  50537. * Moves the cursor ahead by the step amount
  50538. * @param step The amount to move the cursor forward
  50539. * @returns This path cursor
  50540. */
  50541. PathCursor.prototype.moveAhead = function (step) {
  50542. if (step === void 0) { step = 0.002; }
  50543. this.move(step);
  50544. return this;
  50545. };
  50546. /**
  50547. * Moves the cursor behind by the step amount
  50548. * @param step The amount to move the cursor back
  50549. * @returns This path cursor
  50550. */
  50551. PathCursor.prototype.moveBack = function (step) {
  50552. if (step === void 0) { step = 0.002; }
  50553. this.move(-step);
  50554. return this;
  50555. };
  50556. /**
  50557. * Moves the cursor by the step amount
  50558. * If the step amount is greater than one, an exception is thrown
  50559. * @param step The amount to move the cursor
  50560. * @returns This path cursor
  50561. */
  50562. PathCursor.prototype.move = function (step) {
  50563. if (Math.abs(step) > 1) {
  50564. throw "step size should be less than 1.";
  50565. }
  50566. this.value += step;
  50567. this.ensureLimits();
  50568. this.raiseOnChange();
  50569. return this;
  50570. };
  50571. /**
  50572. * Ensures that the value is limited between zero and one
  50573. * @returns This path cursor
  50574. */
  50575. PathCursor.prototype.ensureLimits = function () {
  50576. while (this.value > 1) {
  50577. this.value -= 1;
  50578. }
  50579. while (this.value < 0) {
  50580. this.value += 1;
  50581. }
  50582. return this;
  50583. };
  50584. /**
  50585. * Runs onchange callbacks on change (used by the animation engine)
  50586. * @returns This path cursor
  50587. */
  50588. PathCursor.prototype.raiseOnChange = function () {
  50589. var _this = this;
  50590. this._onchange.forEach(function (f) { return f(_this); });
  50591. return this;
  50592. };
  50593. /**
  50594. * Executes a function on change
  50595. * @param f A path cursor onchange callback
  50596. * @returns This path cursor
  50597. */
  50598. PathCursor.prototype.onchange = function (f) {
  50599. this._onchange.push(f);
  50600. return this;
  50601. };
  50602. return PathCursor;
  50603. }());
  50604. BABYLON.PathCursor = PathCursor;
  50605. /**
  50606. * Enum for the animation key frame interpolation type
  50607. */
  50608. var AnimationKeyInterpolation;
  50609. (function (AnimationKeyInterpolation) {
  50610. /**
  50611. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50612. */
  50613. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50614. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50615. /**
  50616. * Class used to store any kind of animation
  50617. */
  50618. var Animation = /** @class */ (function () {
  50619. /**
  50620. * Initializes the animation
  50621. * @param name Name of the animation
  50622. * @param targetProperty Property to animate
  50623. * @param framePerSecond The frames per second of the animation
  50624. * @param dataType The data type of the animation
  50625. * @param loopMode The loop mode of the animation
  50626. * @param enableBlendings Specifies if blending should be enabled
  50627. */
  50628. function Animation(
  50629. /**Name of the animation */
  50630. name,
  50631. /**Property to animate */
  50632. targetProperty,
  50633. /**The frames per second of the animation */
  50634. framePerSecond,
  50635. /**The data type of the animation */
  50636. dataType,
  50637. /**The loop mode of the animation */
  50638. loopMode,
  50639. /**Specifies if blending should be enabled */
  50640. enableBlending) {
  50641. this.name = name;
  50642. this.targetProperty = targetProperty;
  50643. this.framePerSecond = framePerSecond;
  50644. this.dataType = dataType;
  50645. this.loopMode = loopMode;
  50646. this.enableBlending = enableBlending;
  50647. /**
  50648. * @hidden Internal use only
  50649. */
  50650. this._runtimeAnimations = new Array();
  50651. /**
  50652. * The set of event that will be linked to this animation
  50653. */
  50654. this._events = new Array();
  50655. /**
  50656. * Stores the blending speed of the animation
  50657. */
  50658. this.blendingSpeed = 0.01;
  50659. /**
  50660. * Stores the animation ranges for the animation
  50661. */
  50662. this._ranges = {};
  50663. this.targetPropertyPath = targetProperty.split(".");
  50664. this.dataType = dataType;
  50665. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50666. }
  50667. /**
  50668. * @hidden Internal use
  50669. */
  50670. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50671. var dataType = undefined;
  50672. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50673. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50674. }
  50675. else if (from instanceof BABYLON.Quaternion) {
  50676. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50677. }
  50678. else if (from instanceof BABYLON.Vector3) {
  50679. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50680. }
  50681. else if (from instanceof BABYLON.Vector2) {
  50682. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50683. }
  50684. else if (from instanceof BABYLON.Color3) {
  50685. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50686. }
  50687. else if (from instanceof BABYLON.Size) {
  50688. dataType = Animation.ANIMATIONTYPE_SIZE;
  50689. }
  50690. if (dataType == undefined) {
  50691. return null;
  50692. }
  50693. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50694. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50695. animation.setKeys(keys);
  50696. if (easingFunction !== undefined) {
  50697. animation.setEasingFunction(easingFunction);
  50698. }
  50699. return animation;
  50700. };
  50701. /**
  50702. * Sets up an animation
  50703. * @param property The property to animate
  50704. * @param animationType The animation type to apply
  50705. * @param framePerSecond The frames per second of the animation
  50706. * @param easingFunction The easing function used in the animation
  50707. * @returns The created animation
  50708. */
  50709. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50710. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50711. animation.setEasingFunction(easingFunction);
  50712. return animation;
  50713. };
  50714. /**
  50715. * Create and start an animation on a node
  50716. * @param name defines the name of the global animation that will be run on all nodes
  50717. * @param node defines the root node where the animation will take place
  50718. * @param targetProperty defines property to animate
  50719. * @param framePerSecond defines the number of frame per second yo use
  50720. * @param totalFrame defines the number of frames in total
  50721. * @param from defines the initial value
  50722. * @param to defines the final value
  50723. * @param loopMode defines which loop mode you want to use (off by default)
  50724. * @param easingFunction defines the easing function to use (linear by default)
  50725. * @param onAnimationEnd defines the callback to call when animation end
  50726. * @returns the animatable created for this animation
  50727. */
  50728. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50729. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50730. if (!animation) {
  50731. return null;
  50732. }
  50733. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50734. };
  50735. /**
  50736. * Create and start an animation on a node and its descendants
  50737. * @param name defines the name of the global animation that will be run on all nodes
  50738. * @param node defines the root node where the animation will take place
  50739. * @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
  50740. * @param targetProperty defines property to animate
  50741. * @param framePerSecond defines the number of frame per second to use
  50742. * @param totalFrame defines the number of frames in total
  50743. * @param from defines the initial value
  50744. * @param to defines the final value
  50745. * @param loopMode defines which loop mode you want to use (off by default)
  50746. * @param easingFunction defines the easing function to use (linear by default)
  50747. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50748. * @returns the list of animatables created for all nodes
  50749. * @example https://www.babylonjs-playground.com/#MH0VLI
  50750. */
  50751. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50752. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50753. if (!animation) {
  50754. return null;
  50755. }
  50756. var scene = node.getScene();
  50757. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50758. };
  50759. /**
  50760. * Creates a new animation, merges it with the existing animations and starts it
  50761. * @param name Name of the animation
  50762. * @param node Node which contains the scene that begins the animations
  50763. * @param targetProperty Specifies which property to animate
  50764. * @param framePerSecond The frames per second of the animation
  50765. * @param totalFrame The total number of frames
  50766. * @param from The frame at the beginning of the animation
  50767. * @param to The frame at the end of the animation
  50768. * @param loopMode Specifies the loop mode of the animation
  50769. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50770. * @param onAnimationEnd Callback to run once the animation is complete
  50771. * @returns Nullable animation
  50772. */
  50773. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50774. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50775. if (!animation) {
  50776. return null;
  50777. }
  50778. node.animations.push(animation);
  50779. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50780. };
  50781. /**
  50782. * Transition property of an host to the target Value
  50783. * @param property The property to transition
  50784. * @param targetValue The target Value of the property
  50785. * @param host The object where the property to animate belongs
  50786. * @param scene Scene used to run the animation
  50787. * @param frameRate Framerate (in frame/s) to use
  50788. * @param transition The transition type we want to use
  50789. * @param duration The duration of the animation, in milliseconds
  50790. * @param onAnimationEnd Callback trigger at the end of the animation
  50791. * @returns Nullable animation
  50792. */
  50793. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50794. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50795. if (duration <= 0) {
  50796. host[property] = targetValue;
  50797. if (onAnimationEnd) {
  50798. onAnimationEnd();
  50799. }
  50800. return null;
  50801. }
  50802. var endFrame = frameRate * (duration / 1000);
  50803. transition.setKeys([{
  50804. frame: 0,
  50805. value: host[property].clone ? host[property].clone() : host[property]
  50806. },
  50807. {
  50808. frame: endFrame,
  50809. value: targetValue
  50810. }]);
  50811. if (!host.animations) {
  50812. host.animations = [];
  50813. }
  50814. host.animations.push(transition);
  50815. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50816. animation.onAnimationEnd = onAnimationEnd;
  50817. return animation;
  50818. };
  50819. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50820. /**
  50821. * Return the array of runtime animations currently using this animation
  50822. */
  50823. get: function () {
  50824. return this._runtimeAnimations;
  50825. },
  50826. enumerable: true,
  50827. configurable: true
  50828. });
  50829. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50830. /**
  50831. * Specifies if any of the runtime animations are currently running
  50832. */
  50833. get: function () {
  50834. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50835. var runtimeAnimation = _a[_i];
  50836. if (!runtimeAnimation.isStopped) {
  50837. return true;
  50838. }
  50839. }
  50840. return false;
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. // Methods
  50846. /**
  50847. * Converts the animation to a string
  50848. * @param fullDetails support for multiple levels of logging within scene loading
  50849. * @returns String form of the animation
  50850. */
  50851. Animation.prototype.toString = function (fullDetails) {
  50852. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50853. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50854. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50855. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50856. if (fullDetails) {
  50857. ret += ", Ranges: {";
  50858. var first = true;
  50859. for (var name in this._ranges) {
  50860. if (first) {
  50861. ret += ", ";
  50862. first = false;
  50863. }
  50864. ret += name;
  50865. }
  50866. ret += "}";
  50867. }
  50868. return ret;
  50869. };
  50870. /**
  50871. * Add an event to this animation
  50872. * @param event Event to add
  50873. */
  50874. Animation.prototype.addEvent = function (event) {
  50875. this._events.push(event);
  50876. };
  50877. /**
  50878. * Remove all events found at the given frame
  50879. * @param frame The frame to remove events from
  50880. */
  50881. Animation.prototype.removeEvents = function (frame) {
  50882. for (var index = 0; index < this._events.length; index++) {
  50883. if (this._events[index].frame === frame) {
  50884. this._events.splice(index, 1);
  50885. index--;
  50886. }
  50887. }
  50888. };
  50889. /**
  50890. * Retrieves all the events from the animation
  50891. * @returns Events from the animation
  50892. */
  50893. Animation.prototype.getEvents = function () {
  50894. return this._events;
  50895. };
  50896. /**
  50897. * Creates an animation range
  50898. * @param name Name of the animation range
  50899. * @param from Starting frame of the animation range
  50900. * @param to Ending frame of the animation
  50901. */
  50902. Animation.prototype.createRange = function (name, from, to) {
  50903. // check name not already in use; could happen for bones after serialized
  50904. if (!this._ranges[name]) {
  50905. this._ranges[name] = new AnimationRange(name, from, to);
  50906. }
  50907. };
  50908. /**
  50909. * Deletes an animation range by name
  50910. * @param name Name of the animation range to delete
  50911. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50912. */
  50913. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50914. if (deleteFrames === void 0) { deleteFrames = true; }
  50915. var range = this._ranges[name];
  50916. if (!range) {
  50917. return;
  50918. }
  50919. if (deleteFrames) {
  50920. var from = range.from;
  50921. var to = range.to;
  50922. // this loop MUST go high to low for multiple splices to work
  50923. for (var key = this._keys.length - 1; key >= 0; key--) {
  50924. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50925. this._keys.splice(key, 1);
  50926. }
  50927. }
  50928. }
  50929. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50930. };
  50931. /**
  50932. * Gets the animation range by name, or null if not defined
  50933. * @param name Name of the animation range
  50934. * @returns Nullable animation range
  50935. */
  50936. Animation.prototype.getRange = function (name) {
  50937. return this._ranges[name];
  50938. };
  50939. /**
  50940. * Gets the key frames from the animation
  50941. * @returns The key frames of the animation
  50942. */
  50943. Animation.prototype.getKeys = function () {
  50944. return this._keys;
  50945. };
  50946. /**
  50947. * Gets the highest frame rate of the animation
  50948. * @returns Highest frame rate of the animation
  50949. */
  50950. Animation.prototype.getHighestFrame = function () {
  50951. var ret = 0;
  50952. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50953. if (ret < this._keys[key].frame) {
  50954. ret = this._keys[key].frame;
  50955. }
  50956. }
  50957. return ret;
  50958. };
  50959. /**
  50960. * Gets the easing function of the animation
  50961. * @returns Easing function of the animation
  50962. */
  50963. Animation.prototype.getEasingFunction = function () {
  50964. return this._easingFunction;
  50965. };
  50966. /**
  50967. * Sets the easing function of the animation
  50968. * @param easingFunction A custom mathematical formula for animation
  50969. */
  50970. Animation.prototype.setEasingFunction = function (easingFunction) {
  50971. this._easingFunction = easingFunction;
  50972. };
  50973. /**
  50974. * Interpolates a scalar linearly
  50975. * @param startValue Start value of the animation curve
  50976. * @param endValue End value of the animation curve
  50977. * @param gradient Scalar amount to interpolate
  50978. * @returns Interpolated scalar value
  50979. */
  50980. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50981. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50982. };
  50983. /**
  50984. * Interpolates a scalar cubically
  50985. * @param startValue Start value of the animation curve
  50986. * @param outTangent End tangent of the animation
  50987. * @param endValue End value of the animation curve
  50988. * @param inTangent Start tangent of the animation curve
  50989. * @param gradient Scalar amount to interpolate
  50990. * @returns Interpolated scalar value
  50991. */
  50992. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50993. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50994. };
  50995. /**
  50996. * Interpolates a quaternion using a spherical linear interpolation
  50997. * @param startValue Start value of the animation curve
  50998. * @param endValue End value of the animation curve
  50999. * @param gradient Scalar amount to interpolate
  51000. * @returns Interpolated quaternion value
  51001. */
  51002. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51003. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51004. };
  51005. /**
  51006. * Interpolates a quaternion cubically
  51007. * @param startValue Start value of the animation curve
  51008. * @param outTangent End tangent of the animation curve
  51009. * @param endValue End value of the animation curve
  51010. * @param inTangent Start tangent of the animation curve
  51011. * @param gradient Scalar amount to interpolate
  51012. * @returns Interpolated quaternion value
  51013. */
  51014. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51015. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51016. };
  51017. /**
  51018. * Interpolates a Vector3 linearl
  51019. * @param startValue Start value of the animation curve
  51020. * @param endValue End value of the animation curve
  51021. * @param gradient Scalar amount to interpolate
  51022. * @returns Interpolated scalar value
  51023. */
  51024. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51025. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51026. };
  51027. /**
  51028. * Interpolates a Vector3 cubically
  51029. * @param startValue Start value of the animation curve
  51030. * @param outTangent End tangent of the animation
  51031. * @param endValue End value of the animation curve
  51032. * @param inTangent Start tangent of the animation curve
  51033. * @param gradient Scalar amount to interpolate
  51034. * @returns InterpolatedVector3 value
  51035. */
  51036. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51037. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51038. };
  51039. /**
  51040. * Interpolates a Vector2 linearly
  51041. * @param startValue Start value of the animation curve
  51042. * @param endValue End value of the animation curve
  51043. * @param gradient Scalar amount to interpolate
  51044. * @returns Interpolated Vector2 value
  51045. */
  51046. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51047. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51048. };
  51049. /**
  51050. * Interpolates a Vector2 cubically
  51051. * @param startValue Start value of the animation curve
  51052. * @param outTangent End tangent of the animation
  51053. * @param endValue End value of the animation curve
  51054. * @param inTangent Start tangent of the animation curve
  51055. * @param gradient Scalar amount to interpolate
  51056. * @returns Interpolated Vector2 value
  51057. */
  51058. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51059. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51060. };
  51061. /**
  51062. * Interpolates a size linearly
  51063. * @param startValue Start value of the animation curve
  51064. * @param endValue End value of the animation curve
  51065. * @param gradient Scalar amount to interpolate
  51066. * @returns Interpolated Size value
  51067. */
  51068. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51069. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51070. };
  51071. /**
  51072. * Interpolates a Color3 linearly
  51073. * @param startValue Start value of the animation curve
  51074. * @param endValue End value of the animation curve
  51075. * @param gradient Scalar amount to interpolate
  51076. * @returns Interpolated Color3 value
  51077. */
  51078. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51079. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51080. };
  51081. /**
  51082. * @hidden Internal use only
  51083. */
  51084. Animation.prototype._getKeyValue = function (value) {
  51085. if (typeof value === "function") {
  51086. return value();
  51087. }
  51088. return value;
  51089. };
  51090. /**
  51091. * @hidden Internal use only
  51092. */
  51093. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51094. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51095. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51096. }
  51097. var keys = this.getKeys();
  51098. // Try to get a hash to find the right key
  51099. 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));
  51100. if (keys[startKeyIndex].frame >= currentFrame) {
  51101. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51102. startKeyIndex--;
  51103. }
  51104. }
  51105. for (var key = startKeyIndex; key < keys.length; key++) {
  51106. var endKey = keys[key + 1];
  51107. if (endKey.frame >= currentFrame) {
  51108. var startKey = keys[key];
  51109. var startValue = this._getKeyValue(startKey.value);
  51110. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51111. return startValue;
  51112. }
  51113. var endValue = this._getKeyValue(endKey.value);
  51114. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51115. var frameDelta = endKey.frame - startKey.frame;
  51116. // gradient : percent of currentFrame between the frame inf and the frame sup
  51117. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51118. // check for easingFunction and correction of gradient
  51119. var easingFunction = this.getEasingFunction();
  51120. if (easingFunction != null) {
  51121. gradient = easingFunction.ease(gradient);
  51122. }
  51123. switch (this.dataType) {
  51124. // Float
  51125. case Animation.ANIMATIONTYPE_FLOAT:
  51126. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51127. switch (loopMode) {
  51128. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51129. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51130. return floatValue;
  51131. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51132. return offsetValue * repeatCount + floatValue;
  51133. }
  51134. break;
  51135. // Quaternion
  51136. case Animation.ANIMATIONTYPE_QUATERNION:
  51137. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51138. switch (loopMode) {
  51139. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51140. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51141. return quatValue;
  51142. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51143. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51144. }
  51145. return quatValue;
  51146. // Vector3
  51147. case Animation.ANIMATIONTYPE_VECTOR3:
  51148. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51149. switch (loopMode) {
  51150. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51151. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51152. return vec3Value;
  51153. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51154. return vec3Value.add(offsetValue.scale(repeatCount));
  51155. }
  51156. // Vector2
  51157. case Animation.ANIMATIONTYPE_VECTOR2:
  51158. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51159. switch (loopMode) {
  51160. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51161. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51162. return vec2Value;
  51163. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51164. return vec2Value.add(offsetValue.scale(repeatCount));
  51165. }
  51166. // Size
  51167. case Animation.ANIMATIONTYPE_SIZE:
  51168. switch (loopMode) {
  51169. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51170. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51171. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51172. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51173. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51174. }
  51175. // Color3
  51176. case Animation.ANIMATIONTYPE_COLOR3:
  51177. switch (loopMode) {
  51178. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51179. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51180. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51181. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51182. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51183. }
  51184. // Matrix
  51185. case Animation.ANIMATIONTYPE_MATRIX:
  51186. switch (loopMode) {
  51187. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51188. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51189. if (Animation.AllowMatricesInterpolation) {
  51190. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51191. }
  51192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51193. return startValue;
  51194. }
  51195. default:
  51196. break;
  51197. }
  51198. break;
  51199. }
  51200. }
  51201. return this._getKeyValue(keys[keys.length - 1].value);
  51202. };
  51203. /**
  51204. * Defines the function to use to interpolate matrices
  51205. * @param startValue defines the start matrix
  51206. * @param endValue defines the end matrix
  51207. * @param gradient defines the gradient between both matrices
  51208. * @param result defines an optional target matrix where to store the interpolation
  51209. * @returns the interpolated matrix
  51210. */
  51211. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51212. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51213. if (result) {
  51214. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51215. return result;
  51216. }
  51217. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51218. }
  51219. if (result) {
  51220. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51221. return result;
  51222. }
  51223. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51224. };
  51225. /**
  51226. * Makes a copy of the animation
  51227. * @returns Cloned animation
  51228. */
  51229. Animation.prototype.clone = function () {
  51230. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51231. clone.enableBlending = this.enableBlending;
  51232. clone.blendingSpeed = this.blendingSpeed;
  51233. if (this._keys) {
  51234. clone.setKeys(this._keys);
  51235. }
  51236. if (this._ranges) {
  51237. clone._ranges = {};
  51238. for (var name in this._ranges) {
  51239. var range = this._ranges[name];
  51240. if (!range) {
  51241. continue;
  51242. }
  51243. clone._ranges[name] = range.clone();
  51244. }
  51245. }
  51246. return clone;
  51247. };
  51248. /**
  51249. * Sets the key frames of the animation
  51250. * @param values The animation key frames to set
  51251. */
  51252. Animation.prototype.setKeys = function (values) {
  51253. this._keys = values.slice(0);
  51254. };
  51255. /**
  51256. * Serializes the animation to an object
  51257. * @returns Serialized object
  51258. */
  51259. Animation.prototype.serialize = function () {
  51260. var serializationObject = {};
  51261. serializationObject.name = this.name;
  51262. serializationObject.property = this.targetProperty;
  51263. serializationObject.framePerSecond = this.framePerSecond;
  51264. serializationObject.dataType = this.dataType;
  51265. serializationObject.loopBehavior = this.loopMode;
  51266. serializationObject.enableBlending = this.enableBlending;
  51267. serializationObject.blendingSpeed = this.blendingSpeed;
  51268. var dataType = this.dataType;
  51269. serializationObject.keys = [];
  51270. var keys = this.getKeys();
  51271. for (var index = 0; index < keys.length; index++) {
  51272. var animationKey = keys[index];
  51273. var key = {};
  51274. key.frame = animationKey.frame;
  51275. switch (dataType) {
  51276. case Animation.ANIMATIONTYPE_FLOAT:
  51277. key.values = [animationKey.value];
  51278. break;
  51279. case Animation.ANIMATIONTYPE_QUATERNION:
  51280. case Animation.ANIMATIONTYPE_MATRIX:
  51281. case Animation.ANIMATIONTYPE_VECTOR3:
  51282. case Animation.ANIMATIONTYPE_COLOR3:
  51283. key.values = animationKey.value.asArray();
  51284. break;
  51285. }
  51286. serializationObject.keys.push(key);
  51287. }
  51288. serializationObject.ranges = [];
  51289. for (var name in this._ranges) {
  51290. var source = this._ranges[name];
  51291. if (!source) {
  51292. continue;
  51293. }
  51294. var range = {};
  51295. range.name = name;
  51296. range.from = source.from;
  51297. range.to = source.to;
  51298. serializationObject.ranges.push(range);
  51299. }
  51300. return serializationObject;
  51301. };
  51302. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51303. /**
  51304. * Get the float animation type
  51305. */
  51306. get: function () {
  51307. return Animation._ANIMATIONTYPE_FLOAT;
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51313. /**
  51314. * Get the Vector3 animation type
  51315. */
  51316. get: function () {
  51317. return Animation._ANIMATIONTYPE_VECTOR3;
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51323. /**
  51324. * Get the Vectpr2 animation type
  51325. */
  51326. get: function () {
  51327. return Animation._ANIMATIONTYPE_VECTOR2;
  51328. },
  51329. enumerable: true,
  51330. configurable: true
  51331. });
  51332. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51333. /**
  51334. * Get the Size animation type
  51335. */
  51336. get: function () {
  51337. return Animation._ANIMATIONTYPE_SIZE;
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51343. /**
  51344. * Get the Quaternion animation type
  51345. */
  51346. get: function () {
  51347. return Animation._ANIMATIONTYPE_QUATERNION;
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51353. /**
  51354. * Get the Matrix animation type
  51355. */
  51356. get: function () {
  51357. return Animation._ANIMATIONTYPE_MATRIX;
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51363. /**
  51364. * Get the Color3 animation type
  51365. */
  51366. get: function () {
  51367. return Animation._ANIMATIONTYPE_COLOR3;
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51373. /**
  51374. * Get the Relative Loop Mode
  51375. */
  51376. get: function () {
  51377. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51378. },
  51379. enumerable: true,
  51380. configurable: true
  51381. });
  51382. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51383. /**
  51384. * Get the Cycle Loop Mode
  51385. */
  51386. get: function () {
  51387. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51388. },
  51389. enumerable: true,
  51390. configurable: true
  51391. });
  51392. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51393. /**
  51394. * Get the Constant Loop Mode
  51395. */
  51396. get: function () {
  51397. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51398. },
  51399. enumerable: true,
  51400. configurable: true
  51401. });
  51402. /** @hidden */
  51403. Animation._UniversalLerp = function (left, right, amount) {
  51404. var constructor = left.constructor;
  51405. if (constructor.Lerp) { // Lerp supported
  51406. return constructor.Lerp(left, right, amount);
  51407. }
  51408. else if (constructor.Slerp) { // Slerp supported
  51409. return constructor.Slerp(left, right, amount);
  51410. }
  51411. else if (left.toFixed) { // Number
  51412. return left * (1.0 - amount) + amount * right;
  51413. }
  51414. else { // Blending not supported
  51415. return right;
  51416. }
  51417. };
  51418. /**
  51419. * Parses an animation object and creates an animation
  51420. * @param parsedAnimation Parsed animation object
  51421. * @returns Animation object
  51422. */
  51423. Animation.Parse = function (parsedAnimation) {
  51424. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51425. var dataType = parsedAnimation.dataType;
  51426. var keys = [];
  51427. var data;
  51428. var index;
  51429. if (parsedAnimation.enableBlending) {
  51430. animation.enableBlending = parsedAnimation.enableBlending;
  51431. }
  51432. if (parsedAnimation.blendingSpeed) {
  51433. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51434. }
  51435. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51436. var key = parsedAnimation.keys[index];
  51437. var inTangent;
  51438. var outTangent;
  51439. switch (dataType) {
  51440. case Animation.ANIMATIONTYPE_FLOAT:
  51441. data = key.values[0];
  51442. if (key.values.length >= 1) {
  51443. inTangent = key.values[1];
  51444. }
  51445. if (key.values.length >= 2) {
  51446. outTangent = key.values[2];
  51447. }
  51448. break;
  51449. case Animation.ANIMATIONTYPE_QUATERNION:
  51450. data = BABYLON.Quaternion.FromArray(key.values);
  51451. if (key.values.length >= 8) {
  51452. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51453. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51454. inTangent = _inTangent;
  51455. }
  51456. }
  51457. if (key.values.length >= 12) {
  51458. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51459. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51460. outTangent = _outTangent;
  51461. }
  51462. }
  51463. break;
  51464. case Animation.ANIMATIONTYPE_MATRIX:
  51465. data = BABYLON.Matrix.FromArray(key.values);
  51466. break;
  51467. case Animation.ANIMATIONTYPE_COLOR3:
  51468. data = BABYLON.Color3.FromArray(key.values);
  51469. break;
  51470. case Animation.ANIMATIONTYPE_VECTOR3:
  51471. default:
  51472. data = BABYLON.Vector3.FromArray(key.values);
  51473. break;
  51474. }
  51475. var keyData = {};
  51476. keyData.frame = key.frame;
  51477. keyData.value = data;
  51478. if (inTangent != undefined) {
  51479. keyData.inTangent = inTangent;
  51480. }
  51481. if (outTangent != undefined) {
  51482. keyData.outTangent = outTangent;
  51483. }
  51484. keys.push(keyData);
  51485. }
  51486. animation.setKeys(keys);
  51487. if (parsedAnimation.ranges) {
  51488. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51489. data = parsedAnimation.ranges[index];
  51490. animation.createRange(data.name, data.from, data.to);
  51491. }
  51492. }
  51493. return animation;
  51494. };
  51495. /**
  51496. * Appends the serialized animations from the source animations
  51497. * @param source Source containing the animations
  51498. * @param destination Target to store the animations
  51499. */
  51500. Animation.AppendSerializedAnimations = function (source, destination) {
  51501. if (source.animations) {
  51502. destination.animations = [];
  51503. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51504. var animation = source.animations[animationIndex];
  51505. destination.animations.push(animation.serialize());
  51506. }
  51507. }
  51508. };
  51509. /**
  51510. * Use matrix interpolation instead of using direct key value when animating matrices
  51511. */
  51512. Animation.AllowMatricesInterpolation = false;
  51513. /**
  51514. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51515. */
  51516. Animation.AllowMatrixDecomposeForInterpolation = true;
  51517. // Statics
  51518. /**
  51519. * Float animation type
  51520. */
  51521. Animation._ANIMATIONTYPE_FLOAT = 0;
  51522. /**
  51523. * Vector3 animation type
  51524. */
  51525. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51526. /**
  51527. * Quaternion animation type
  51528. */
  51529. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51530. /**
  51531. * Matrix animation type
  51532. */
  51533. Animation._ANIMATIONTYPE_MATRIX = 3;
  51534. /**
  51535. * Color3 animation type
  51536. */
  51537. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51538. /**
  51539. * Vector2 animation type
  51540. */
  51541. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51542. /**
  51543. * Size animation type
  51544. */
  51545. Animation._ANIMATIONTYPE_SIZE = 6;
  51546. /**
  51547. * Relative Loop Mode
  51548. */
  51549. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51550. /**
  51551. * Cycle Loop Mode
  51552. */
  51553. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51554. /**
  51555. * Constant Loop Mode
  51556. */
  51557. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51558. return Animation;
  51559. }());
  51560. BABYLON.Animation = Animation;
  51561. })(BABYLON || (BABYLON = {}));
  51562. //# sourceMappingURL=babylon.animation.js.map
  51563. var BABYLON;
  51564. (function (BABYLON) {
  51565. /**
  51566. * This class defines the direct association between an animation and a target
  51567. */
  51568. var TargetedAnimation = /** @class */ (function () {
  51569. function TargetedAnimation() {
  51570. }
  51571. return TargetedAnimation;
  51572. }());
  51573. BABYLON.TargetedAnimation = TargetedAnimation;
  51574. /**
  51575. * Use this class to create coordinated animations on multiple targets
  51576. */
  51577. var AnimationGroup = /** @class */ (function () {
  51578. function AnimationGroup(name, scene) {
  51579. if (scene === void 0) { scene = null; }
  51580. this.name = name;
  51581. this._targetedAnimations = new Array();
  51582. this._animatables = new Array();
  51583. this._from = Number.MAX_VALUE;
  51584. this._to = -Number.MAX_VALUE;
  51585. this._speedRatio = 1;
  51586. this.onAnimationEndObservable = new BABYLON.Observable();
  51587. /**
  51588. * This observable will notify when all animations have ended.
  51589. */
  51590. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51591. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51592. this._scene.animationGroups.push(this);
  51593. }
  51594. Object.defineProperty(AnimationGroup.prototype, "from", {
  51595. /**
  51596. * Gets the first frame
  51597. */
  51598. get: function () {
  51599. return this._from;
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. Object.defineProperty(AnimationGroup.prototype, "to", {
  51605. /**
  51606. * Gets the last frame
  51607. */
  51608. get: function () {
  51609. return this._to;
  51610. },
  51611. enumerable: true,
  51612. configurable: true
  51613. });
  51614. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51615. /**
  51616. * Define if the animations are started
  51617. */
  51618. get: function () {
  51619. return this._isStarted;
  51620. },
  51621. enumerable: true,
  51622. configurable: true
  51623. });
  51624. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51625. /**
  51626. * Gets or sets the speed ratio to use for all animations
  51627. */
  51628. get: function () {
  51629. return this._speedRatio;
  51630. },
  51631. /**
  51632. * Gets or sets the speed ratio to use for all animations
  51633. */
  51634. set: function (value) {
  51635. if (this._speedRatio === value) {
  51636. return;
  51637. }
  51638. this._speedRatio = value;
  51639. for (var index = 0; index < this._animatables.length; index++) {
  51640. var animatable = this._animatables[index];
  51641. animatable.speedRatio = this._speedRatio;
  51642. }
  51643. },
  51644. enumerable: true,
  51645. configurable: true
  51646. });
  51647. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51648. /**
  51649. * Gets the targeted animations for this animation group
  51650. */
  51651. get: function () {
  51652. return this._targetedAnimations;
  51653. },
  51654. enumerable: true,
  51655. configurable: true
  51656. });
  51657. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51658. /**
  51659. * returning the list of animatables controlled by this animation group.
  51660. */
  51661. get: function () {
  51662. return this._animatables;
  51663. },
  51664. enumerable: true,
  51665. configurable: true
  51666. });
  51667. /**
  51668. * Add an animation (with its target) in the group
  51669. * @param animation defines the animation we want to add
  51670. * @param target defines the target of the animation
  51671. * @returns the {BABYLON.TargetedAnimation} object
  51672. */
  51673. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51674. var targetedAnimation = {
  51675. animation: animation,
  51676. target: target
  51677. };
  51678. var keys = animation.getKeys();
  51679. if (this._from > keys[0].frame) {
  51680. this._from = keys[0].frame;
  51681. }
  51682. if (this._to < keys[keys.length - 1].frame) {
  51683. this._to = keys[keys.length - 1].frame;
  51684. }
  51685. this._targetedAnimations.push(targetedAnimation);
  51686. return targetedAnimation;
  51687. };
  51688. /**
  51689. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51690. * It can add constant keys at begin or end
  51691. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51692. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51693. */
  51694. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51695. if (beginFrame === void 0) { beginFrame = null; }
  51696. if (endFrame === void 0) { endFrame = null; }
  51697. if (beginFrame == null)
  51698. beginFrame = this._from;
  51699. if (endFrame == null)
  51700. endFrame = this._to;
  51701. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51702. var targetedAnimation = this._targetedAnimations[index];
  51703. var keys = targetedAnimation.animation.getKeys();
  51704. var startKey = keys[0];
  51705. var endKey = keys[keys.length - 1];
  51706. if (startKey.frame > beginFrame) {
  51707. var newKey = {
  51708. frame: beginFrame,
  51709. value: startKey.value,
  51710. inTangent: startKey.inTangent,
  51711. outTangent: startKey.outTangent,
  51712. interpolation: startKey.interpolation
  51713. };
  51714. keys.splice(0, 0, newKey);
  51715. }
  51716. if (endKey.frame < endFrame) {
  51717. var newKey = {
  51718. frame: endFrame,
  51719. value: endKey.value,
  51720. inTangent: endKey.outTangent,
  51721. outTangent: endKey.outTangent,
  51722. interpolation: endKey.interpolation
  51723. };
  51724. keys.push(newKey);
  51725. }
  51726. }
  51727. this._from = beginFrame;
  51728. this._to = endFrame;
  51729. return this;
  51730. };
  51731. /**
  51732. * Start all animations on given targets
  51733. * @param loop defines if animations must loop
  51734. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51735. * @param from defines the from key (optional)
  51736. * @param to defines the to key (optional)
  51737. * @returns the current animation group
  51738. */
  51739. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51740. var _this = this;
  51741. if (loop === void 0) { loop = false; }
  51742. if (speedRatio === void 0) { speedRatio = 1; }
  51743. if (this._isStarted || this._targetedAnimations.length === 0) {
  51744. return this;
  51745. }
  51746. var _loop_1 = function (targetedAnimation) {
  51747. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51748. animatable.onAnimationEnd = function () {
  51749. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51750. _this._checkAnimationGroupEnded(animatable);
  51751. };
  51752. this_1._animatables.push(animatable);
  51753. };
  51754. var this_1 = this;
  51755. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51756. var targetedAnimation = _a[_i];
  51757. _loop_1(targetedAnimation);
  51758. }
  51759. this._speedRatio = speedRatio;
  51760. this._isStarted = true;
  51761. return this;
  51762. };
  51763. /**
  51764. * Pause all animations
  51765. */
  51766. AnimationGroup.prototype.pause = function () {
  51767. if (!this._isStarted) {
  51768. return this;
  51769. }
  51770. for (var index = 0; index < this._animatables.length; index++) {
  51771. var animatable = this._animatables[index];
  51772. animatable.pause();
  51773. }
  51774. return this;
  51775. };
  51776. /**
  51777. * Play all animations to initial state
  51778. * This function will start() the animations if they were not started or will restart() them if they were paused
  51779. * @param loop defines if animations must loop
  51780. */
  51781. AnimationGroup.prototype.play = function (loop) {
  51782. // only if all animatables are ready and exist
  51783. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51784. if (loop !== undefined) {
  51785. for (var index = 0; index < this._animatables.length; index++) {
  51786. var animatable = this._animatables[index];
  51787. animatable.loopAnimation = loop;
  51788. }
  51789. }
  51790. this.restart();
  51791. }
  51792. else {
  51793. this.stop();
  51794. this.start(loop, this._speedRatio);
  51795. }
  51796. return this;
  51797. };
  51798. /**
  51799. * Reset all animations to initial state
  51800. */
  51801. AnimationGroup.prototype.reset = function () {
  51802. if (!this._isStarted) {
  51803. return this;
  51804. }
  51805. for (var index = 0; index < this._animatables.length; index++) {
  51806. var animatable = this._animatables[index];
  51807. animatable.reset();
  51808. }
  51809. return this;
  51810. };
  51811. /**
  51812. * Restart animations from key 0
  51813. */
  51814. AnimationGroup.prototype.restart = function () {
  51815. if (!this._isStarted) {
  51816. return this;
  51817. }
  51818. for (var index = 0; index < this._animatables.length; index++) {
  51819. var animatable = this._animatables[index];
  51820. animatable.restart();
  51821. }
  51822. return this;
  51823. };
  51824. /**
  51825. * Stop all animations
  51826. */
  51827. AnimationGroup.prototype.stop = function () {
  51828. if (!this._isStarted) {
  51829. return this;
  51830. }
  51831. for (var index = 0; index < this._animatables.length; index++) {
  51832. var animatable = this._animatables[index];
  51833. animatable.stop();
  51834. }
  51835. this._isStarted = false;
  51836. return this;
  51837. };
  51838. /**
  51839. * Set animation weight for all animatables
  51840. * @param weight defines the weight to use
  51841. * @return the animationGroup
  51842. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51843. */
  51844. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51845. for (var index = 0; index < this._animatables.length; index++) {
  51846. var animatable = this._animatables[index];
  51847. animatable.weight = weight;
  51848. }
  51849. return this;
  51850. };
  51851. /**
  51852. * Synchronize and normalize all animatables with a source animatable
  51853. * @param root defines the root animatable to synchronize with
  51854. * @return the animationGroup
  51855. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51856. */
  51857. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51858. for (var index = 0; index < this._animatables.length; index++) {
  51859. var animatable = this._animatables[index];
  51860. animatable.syncWith(root);
  51861. }
  51862. return this;
  51863. };
  51864. /**
  51865. * Goes to a specific frame in this animation group
  51866. * @param frame the frame number to go to
  51867. * @return the animationGroup
  51868. */
  51869. AnimationGroup.prototype.goToFrame = function (frame) {
  51870. if (!this._isStarted) {
  51871. return this;
  51872. }
  51873. for (var index = 0; index < this._animatables.length; index++) {
  51874. var animatable = this._animatables[index];
  51875. animatable.goToFrame(frame);
  51876. }
  51877. return this;
  51878. };
  51879. /**
  51880. * Dispose all associated resources
  51881. */
  51882. AnimationGroup.prototype.dispose = function () {
  51883. this._targetedAnimations = [];
  51884. this._animatables = [];
  51885. var index = this._scene.animationGroups.indexOf(this);
  51886. if (index > -1) {
  51887. this._scene.animationGroups.splice(index, 1);
  51888. }
  51889. };
  51890. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51891. // animatable should be taken out of the array
  51892. var idx = this._animatables.indexOf(animatable);
  51893. if (idx > -1) {
  51894. this._animatables.splice(idx, 1);
  51895. }
  51896. // all animatables were removed? animation group ended!
  51897. if (this._animatables.length === 0) {
  51898. this._isStarted = false;
  51899. this.onAnimationGroupEndObservable.notifyObservers(this);
  51900. }
  51901. };
  51902. return AnimationGroup;
  51903. }());
  51904. BABYLON.AnimationGroup = AnimationGroup;
  51905. })(BABYLON || (BABYLON = {}));
  51906. //# sourceMappingURL=babylon.animationGroup.js.map
  51907. var BABYLON;
  51908. (function (BABYLON) {
  51909. /**
  51910. * Defines a runtime animation
  51911. */
  51912. var RuntimeAnimation = /** @class */ (function () {
  51913. /**
  51914. * Create a new RuntimeAnimation object
  51915. * @param target defines the target of the animation
  51916. * @param animation defines the source animation object
  51917. * @param scene defines the hosting scene
  51918. * @param host defines the initiating Animatable
  51919. */
  51920. function RuntimeAnimation(target, animation, scene, host) {
  51921. var _this = this;
  51922. this._events = new Array();
  51923. /**
  51924. * The current frame of the runtime animation
  51925. */
  51926. this._currentFrame = 0;
  51927. /**
  51928. * The original value of the runtime animation
  51929. */
  51930. this._originalValue = new Array();
  51931. /**
  51932. * The offsets cache of the runtime animation
  51933. */
  51934. this._offsetsCache = {};
  51935. /**
  51936. * The high limits cache of the runtime animation
  51937. */
  51938. this._highLimitsCache = {};
  51939. /**
  51940. * Specifies if the runtime animation has been stopped
  51941. */
  51942. this._stopped = false;
  51943. /**
  51944. * The blending factor of the runtime animation
  51945. */
  51946. this._blendingFactor = 0;
  51947. /**
  51948. * The target path of the runtime animation
  51949. */
  51950. this._targetPath = "";
  51951. /**
  51952. * The weight of the runtime animation
  51953. */
  51954. this._weight = 1.0;
  51955. /**
  51956. * The ratio offset of the runtime animation
  51957. */
  51958. this._ratioOffset = 0;
  51959. /**
  51960. * The previous delay of the runtime animation
  51961. */
  51962. this._previousDelay = 0;
  51963. /**
  51964. * The previous ratio of the runtime animation
  51965. */
  51966. this._previousRatio = 0;
  51967. this._animation = animation;
  51968. this._target = target;
  51969. this._scene = scene;
  51970. this._host = host;
  51971. animation._runtimeAnimations.push(this);
  51972. // Cloning events locally
  51973. var events = animation.getEvents();
  51974. if (events && events.length > 0) {
  51975. events.forEach(function (e) {
  51976. _this._events.push(e._clone());
  51977. });
  51978. }
  51979. }
  51980. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51981. /**
  51982. * Gets the current frame of the runtime animation
  51983. */
  51984. get: function () {
  51985. return this._currentFrame;
  51986. },
  51987. enumerable: true,
  51988. configurable: true
  51989. });
  51990. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51991. /**
  51992. * Gets the weight of the runtime animation
  51993. */
  51994. get: function () {
  51995. return this._weight;
  51996. },
  51997. enumerable: true,
  51998. configurable: true
  51999. });
  52000. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52001. /**
  52002. * Gets the current value of the runtime animation
  52003. */
  52004. get: function () {
  52005. return this._currentValue;
  52006. },
  52007. enumerable: true,
  52008. configurable: true
  52009. });
  52010. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52011. /**
  52012. * Gets the target path of the runtime animation
  52013. */
  52014. get: function () {
  52015. return this._targetPath;
  52016. },
  52017. enumerable: true,
  52018. configurable: true
  52019. });
  52020. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52021. /**
  52022. * Gets the actual target of the runtime animation
  52023. */
  52024. get: function () {
  52025. return this._activeTarget;
  52026. },
  52027. enumerable: true,
  52028. configurable: true
  52029. });
  52030. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52031. /**
  52032. * Gets the animation from the runtime animation
  52033. */
  52034. get: function () {
  52035. return this._animation;
  52036. },
  52037. enumerable: true,
  52038. configurable: true
  52039. });
  52040. /**
  52041. * Resets the runtime animation to the beginning
  52042. * @param restoreOriginal defines whether to restore the target property to the original value
  52043. */
  52044. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52045. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52046. if (restoreOriginal) {
  52047. if (this._target instanceof Array) {
  52048. var index = 0;
  52049. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52050. var target = _a[_i];
  52051. if (this._originalValue[index] !== undefined) {
  52052. this._setValue(target, this._originalValue[index], -1);
  52053. }
  52054. index++;
  52055. }
  52056. }
  52057. else {
  52058. if (this._originalValue[0] !== undefined) {
  52059. this._setValue(this._target, this._originalValue[0], -1);
  52060. }
  52061. }
  52062. }
  52063. this._offsetsCache = {};
  52064. this._highLimitsCache = {};
  52065. this._currentFrame = 0;
  52066. this._blendingFactor = 0;
  52067. this._originalValue = new Array();
  52068. // Events
  52069. for (var index = 0; index < this._events.length; index++) {
  52070. this._events[index].isDone = false;
  52071. }
  52072. };
  52073. /**
  52074. * Specifies if the runtime animation is stopped
  52075. * @returns Boolean specifying if the runtime animation is stopped
  52076. */
  52077. RuntimeAnimation.prototype.isStopped = function () {
  52078. return this._stopped;
  52079. };
  52080. /**
  52081. * Disposes of the runtime animation
  52082. */
  52083. RuntimeAnimation.prototype.dispose = function () {
  52084. var index = this._animation.runtimeAnimations.indexOf(this);
  52085. if (index > -1) {
  52086. this._animation.runtimeAnimations.splice(index, 1);
  52087. }
  52088. };
  52089. /**
  52090. * Interpolates the animation from the current frame
  52091. * @param currentFrame The frame to interpolate the animation to
  52092. * @param repeatCount The number of times that the animation should loop
  52093. * @param loopMode The type of looping mode to use
  52094. * @param offsetValue Animation offset value
  52095. * @param highLimitValue The high limit value
  52096. * @returns The interpolated value
  52097. */
  52098. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52099. this._currentFrame = currentFrame;
  52100. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52101. this._workValue = BABYLON.Matrix.Zero();
  52102. }
  52103. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52104. };
  52105. /**
  52106. * Apply the interpolated value to the target
  52107. * @param currentValue defines the value computed by the animation
  52108. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52109. */
  52110. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52111. if (weight === void 0) { weight = 1.0; }
  52112. if (this._target instanceof Array) {
  52113. var index = 0;
  52114. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52115. var target = _a[_i];
  52116. this._setValue(target, currentValue, weight, index);
  52117. index++;
  52118. }
  52119. }
  52120. else {
  52121. this._setValue(this._target, currentValue, weight);
  52122. }
  52123. };
  52124. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52125. if (targetIndex === void 0) { targetIndex = 0; }
  52126. // Set value
  52127. var path;
  52128. var destination;
  52129. var targetPropertyPath = this._animation.targetPropertyPath;
  52130. if (targetPropertyPath.length > 1) {
  52131. var property = target[targetPropertyPath[0]];
  52132. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52133. property = property[targetPropertyPath[index]];
  52134. }
  52135. path = targetPropertyPath[targetPropertyPath.length - 1];
  52136. destination = property;
  52137. }
  52138. else {
  52139. path = targetPropertyPath[0];
  52140. destination = target;
  52141. }
  52142. this._targetPath = path;
  52143. this._activeTarget = destination;
  52144. this._weight = weight;
  52145. if (this._originalValue[targetIndex] === undefined) {
  52146. var originalValue = void 0;
  52147. if (destination.getRestPose && path === "_matrix") { // For bones
  52148. originalValue = destination.getRestPose();
  52149. }
  52150. else {
  52151. originalValue = destination[path];
  52152. }
  52153. if (originalValue && originalValue.clone) {
  52154. this._originalValue[targetIndex] = originalValue.clone();
  52155. }
  52156. else {
  52157. this._originalValue[targetIndex] = originalValue;
  52158. }
  52159. }
  52160. // Blending
  52161. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52162. if (enableBlending && this._blendingFactor <= 1.0) {
  52163. if (!this._originalBlendValue) {
  52164. var originalValue = destination[path];
  52165. if (originalValue.clone) {
  52166. this._originalBlendValue = originalValue.clone();
  52167. }
  52168. else {
  52169. this._originalBlendValue = originalValue;
  52170. }
  52171. }
  52172. if (this._originalBlendValue.m) { // Matrix
  52173. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52174. if (this._currentValue) {
  52175. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52176. }
  52177. else {
  52178. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52179. }
  52180. }
  52181. else {
  52182. if (this._currentValue) {
  52183. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52184. }
  52185. else {
  52186. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52187. }
  52188. }
  52189. }
  52190. else {
  52191. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52192. }
  52193. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52194. this._blendingFactor += blendingSpeed;
  52195. }
  52196. else {
  52197. this._currentValue = currentValue;
  52198. }
  52199. if (weight !== -1.0) {
  52200. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52201. }
  52202. else {
  52203. destination[path] = this._currentValue;
  52204. }
  52205. if (target.markAsDirty) {
  52206. target.markAsDirty(this._animation.targetProperty);
  52207. }
  52208. };
  52209. /**
  52210. * Gets the loop pmode of the runtime animation
  52211. * @returns Loop Mode
  52212. */
  52213. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52214. if (this._target && this._target.animationPropertiesOverride) {
  52215. return this._target.animationPropertiesOverride.loopMode;
  52216. }
  52217. return this._animation.loopMode;
  52218. };
  52219. /**
  52220. * Move the current animation to a given frame
  52221. * @param frame defines the frame to move to
  52222. */
  52223. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52224. var keys = this._animation.getKeys();
  52225. if (frame < keys[0].frame) {
  52226. frame = keys[0].frame;
  52227. }
  52228. else if (frame > keys[keys.length - 1].frame) {
  52229. frame = keys[keys.length - 1].frame;
  52230. }
  52231. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52232. this.setValue(currentValue, -1);
  52233. };
  52234. /**
  52235. * @hidden Internal use only
  52236. */
  52237. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52238. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52239. this._ratioOffset = this._previousRatio - newRatio;
  52240. };
  52241. /**
  52242. * Execute the current animation
  52243. * @param delay defines the delay to add to the current frame
  52244. * @param from defines the lower bound of the animation range
  52245. * @param to defines the upper bound of the animation range
  52246. * @param loop defines if the current animation must loop
  52247. * @param speedRatio defines the current speed ratio
  52248. * @param weight defines the weight of the animation (default is -1 so no weight)
  52249. * @returns a boolean indicating if the animation has ended
  52250. */
  52251. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52252. if (weight === void 0) { weight = -1.0; }
  52253. var targetPropertyPath = this._animation.targetPropertyPath;
  52254. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52255. this._stopped = true;
  52256. return false;
  52257. }
  52258. var returnValue = true;
  52259. var keys = this._animation.getKeys();
  52260. // Adding a start key at frame 0 if missing
  52261. if (keys[0].frame !== 0) {
  52262. var newKey = { frame: 0, value: keys[0].value };
  52263. keys.splice(0, 0, newKey);
  52264. }
  52265. // Check limits
  52266. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52267. from = keys[0].frame;
  52268. }
  52269. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52270. to = keys[keys.length - 1].frame;
  52271. }
  52272. //to and from cannot be the same key
  52273. if (from === to) {
  52274. if (from > keys[0].frame) {
  52275. from--;
  52276. }
  52277. else if (to < keys[keys.length - 1].frame) {
  52278. to++;
  52279. }
  52280. }
  52281. // Compute ratio
  52282. var range = to - from;
  52283. var offsetValue;
  52284. // ratio represents the frame delta between from and to
  52285. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52286. var highLimitValue = 0;
  52287. this._previousDelay = delay;
  52288. this._previousRatio = ratio;
  52289. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52290. returnValue = false;
  52291. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52292. }
  52293. else {
  52294. // Get max value if required
  52295. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52296. var keyOffset = to.toString() + from.toString();
  52297. if (!this._offsetsCache[keyOffset]) {
  52298. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52299. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52300. switch (this._animation.dataType) {
  52301. // Float
  52302. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52303. this._offsetsCache[keyOffset] = toValue - fromValue;
  52304. break;
  52305. // Quaternion
  52306. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52307. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52308. break;
  52309. // Vector3
  52310. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52311. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52312. // Vector2
  52313. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52314. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52315. // Size
  52316. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52317. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52318. // Color3
  52319. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52320. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52321. default:
  52322. break;
  52323. }
  52324. this._highLimitsCache[keyOffset] = toValue;
  52325. }
  52326. highLimitValue = this._highLimitsCache[keyOffset];
  52327. offsetValue = this._offsetsCache[keyOffset];
  52328. }
  52329. }
  52330. if (offsetValue === undefined) {
  52331. switch (this._animation.dataType) {
  52332. // Float
  52333. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52334. offsetValue = 0;
  52335. break;
  52336. // Quaternion
  52337. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52338. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52339. break;
  52340. // Vector3
  52341. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52342. offsetValue = BABYLON.Vector3.Zero();
  52343. break;
  52344. // Vector2
  52345. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52346. offsetValue = BABYLON.Vector2.Zero();
  52347. break;
  52348. // Size
  52349. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52350. offsetValue = BABYLON.Size.Zero();
  52351. break;
  52352. // Color3
  52353. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52354. offsetValue = BABYLON.Color3.Black();
  52355. }
  52356. }
  52357. // Compute value
  52358. var repeatCount = (ratio / range) >> 0;
  52359. var currentFrame = returnValue ? from + ratio % range : to;
  52360. // Need to normalize?
  52361. if (this._host && this._host.syncRoot) {
  52362. var syncRoot = this._host.syncRoot;
  52363. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52364. currentFrame = from + (to - from) * hostNormalizedFrame;
  52365. }
  52366. // Reset events if looping
  52367. var events = this._events;
  52368. if (range > 0 && this.currentFrame > currentFrame ||
  52369. range < 0 && this.currentFrame < currentFrame) {
  52370. // Need to reset animation events
  52371. for (var index = 0; index < events.length; index++) {
  52372. if (!events[index].onlyOnce) {
  52373. // reset event, the animation is looping
  52374. events[index].isDone = false;
  52375. }
  52376. }
  52377. }
  52378. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52379. // Set value
  52380. this.setValue(currentValue, weight);
  52381. // Check events
  52382. for (var index = 0; index < events.length; index++) {
  52383. // Make sure current frame has passed event frame and that event frame is within the current range
  52384. // Also, handle both forward and reverse animations
  52385. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52386. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52387. var event = events[index];
  52388. if (!event.isDone) {
  52389. // If event should be done only once, remove it.
  52390. if (event.onlyOnce) {
  52391. events.splice(index, 1);
  52392. index--;
  52393. }
  52394. event.isDone = true;
  52395. event.action();
  52396. } // Don't do anything if the event has already be done.
  52397. }
  52398. }
  52399. if (!returnValue) {
  52400. this._stopped = true;
  52401. }
  52402. return returnValue;
  52403. };
  52404. return RuntimeAnimation;
  52405. }());
  52406. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52407. })(BABYLON || (BABYLON = {}));
  52408. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52409. var BABYLON;
  52410. (function (BABYLON) {
  52411. var Animatable = /** @class */ (function () {
  52412. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52413. if (fromFrame === void 0) { fromFrame = 0; }
  52414. if (toFrame === void 0) { toFrame = 100; }
  52415. if (loopAnimation === void 0) { loopAnimation = false; }
  52416. if (speedRatio === void 0) { speedRatio = 1.0; }
  52417. this.target = target;
  52418. this.fromFrame = fromFrame;
  52419. this.toFrame = toFrame;
  52420. this.loopAnimation = loopAnimation;
  52421. this.onAnimationEnd = onAnimationEnd;
  52422. this._localDelayOffset = null;
  52423. this._pausedDelay = null;
  52424. this._runtimeAnimations = new Array();
  52425. this._paused = false;
  52426. this._speedRatio = 1;
  52427. this._weight = -1.0;
  52428. this.animationStarted = false;
  52429. /**
  52430. * Observer raised when the animation ends
  52431. */
  52432. this.onAnimationEndObservable = new BABYLON.Observable();
  52433. this._scene = scene;
  52434. if (animations) {
  52435. this.appendAnimations(target, animations);
  52436. }
  52437. this._speedRatio = speedRatio;
  52438. scene._activeAnimatables.push(this);
  52439. }
  52440. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52441. /**
  52442. * Gets the root Animatable used to synchronize and normalize animations
  52443. */
  52444. get: function () {
  52445. return this._syncRoot;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52451. /**
  52452. * Gets the current frame of the first RuntimeAnimation
  52453. * Used to synchronize Animatables
  52454. */
  52455. get: function () {
  52456. if (this._runtimeAnimations.length === 0) {
  52457. return 0;
  52458. }
  52459. return this._runtimeAnimations[0].currentFrame;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(Animatable.prototype, "weight", {
  52465. /**
  52466. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52467. */
  52468. get: function () {
  52469. return this._weight;
  52470. },
  52471. set: function (value) {
  52472. if (value === -1) { // -1 is ok and means no weight
  52473. this._weight = -1;
  52474. return;
  52475. }
  52476. // Else weight must be in [0, 1] range
  52477. this._weight = Math.min(Math.max(value, 0), 1.0);
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52483. /**
  52484. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52485. */
  52486. get: function () {
  52487. return this._speedRatio;
  52488. },
  52489. set: function (value) {
  52490. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52491. var animation = this._runtimeAnimations[index];
  52492. animation._prepareForSpeedRatioChange(value);
  52493. }
  52494. this._speedRatio = value;
  52495. },
  52496. enumerable: true,
  52497. configurable: true
  52498. });
  52499. // Methods
  52500. /**
  52501. * Synchronize and normalize current Animatable with a source Animatable
  52502. * This is useful when using animation weights and when animations are not of the same length
  52503. * @param root defines the root Animatable to synchronize with
  52504. * @returns the current Animatable
  52505. */
  52506. Animatable.prototype.syncWith = function (root) {
  52507. this._syncRoot = root;
  52508. if (root) {
  52509. // Make sure this animatable will animate after the root
  52510. var index = this._scene._activeAnimatables.indexOf(this);
  52511. if (index > -1) {
  52512. this._scene._activeAnimatables.splice(index, 1);
  52513. this._scene._activeAnimatables.push(this);
  52514. }
  52515. }
  52516. return this;
  52517. };
  52518. Animatable.prototype.getAnimations = function () {
  52519. return this._runtimeAnimations;
  52520. };
  52521. Animatable.prototype.appendAnimations = function (target, animations) {
  52522. for (var index = 0; index < animations.length; index++) {
  52523. var animation = animations[index];
  52524. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52525. }
  52526. };
  52527. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52528. var runtimeAnimations = this._runtimeAnimations;
  52529. for (var index = 0; index < runtimeAnimations.length; index++) {
  52530. if (runtimeAnimations[index].animation.targetProperty === property) {
  52531. return runtimeAnimations[index].animation;
  52532. }
  52533. }
  52534. return null;
  52535. };
  52536. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52537. var runtimeAnimations = this._runtimeAnimations;
  52538. for (var index = 0; index < runtimeAnimations.length; index++) {
  52539. if (runtimeAnimations[index].animation.targetProperty === property) {
  52540. return runtimeAnimations[index];
  52541. }
  52542. }
  52543. return null;
  52544. };
  52545. Animatable.prototype.reset = function () {
  52546. var runtimeAnimations = this._runtimeAnimations;
  52547. for (var index = 0; index < runtimeAnimations.length; index++) {
  52548. runtimeAnimations[index].reset(true);
  52549. }
  52550. this._localDelayOffset = null;
  52551. this._pausedDelay = null;
  52552. };
  52553. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52554. var runtimeAnimations = this._runtimeAnimations;
  52555. for (var index = 0; index < runtimeAnimations.length; index++) {
  52556. runtimeAnimations[index].animation.enableBlending = true;
  52557. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52558. }
  52559. };
  52560. Animatable.prototype.disableBlending = function () {
  52561. var runtimeAnimations = this._runtimeAnimations;
  52562. for (var index = 0; index < runtimeAnimations.length; index++) {
  52563. runtimeAnimations[index].animation.enableBlending = false;
  52564. }
  52565. };
  52566. Animatable.prototype.goToFrame = function (frame) {
  52567. var runtimeAnimations = this._runtimeAnimations;
  52568. if (runtimeAnimations[0]) {
  52569. var fps = runtimeAnimations[0].animation.framePerSecond;
  52570. var currentFrame = runtimeAnimations[0].currentFrame;
  52571. var adjustTime = frame - currentFrame;
  52572. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52573. if (this._localDelayOffset === null) {
  52574. this._localDelayOffset = 0;
  52575. }
  52576. this._localDelayOffset -= delay;
  52577. }
  52578. for (var index = 0; index < runtimeAnimations.length; index++) {
  52579. runtimeAnimations[index].goToFrame(frame);
  52580. }
  52581. };
  52582. Animatable.prototype.pause = function () {
  52583. if (this._paused) {
  52584. return;
  52585. }
  52586. this._paused = true;
  52587. };
  52588. Animatable.prototype.restart = function () {
  52589. this._paused = false;
  52590. };
  52591. Animatable.prototype._raiseOnAnimationEnd = function () {
  52592. if (this.onAnimationEnd) {
  52593. this.onAnimationEnd();
  52594. }
  52595. this.onAnimationEndObservable.notifyObservers(this);
  52596. };
  52597. Animatable.prototype.stop = function (animationName) {
  52598. if (animationName) {
  52599. var idx = this._scene._activeAnimatables.indexOf(this);
  52600. if (idx > -1) {
  52601. var runtimeAnimations = this._runtimeAnimations;
  52602. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52603. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52604. continue;
  52605. }
  52606. runtimeAnimations[index].dispose();
  52607. runtimeAnimations.splice(index, 1);
  52608. }
  52609. if (runtimeAnimations.length == 0) {
  52610. this._scene._activeAnimatables.splice(idx, 1);
  52611. this._raiseOnAnimationEnd();
  52612. }
  52613. }
  52614. }
  52615. else {
  52616. var index = this._scene._activeAnimatables.indexOf(this);
  52617. if (index > -1) {
  52618. this._scene._activeAnimatables.splice(index, 1);
  52619. var runtimeAnimations = this._runtimeAnimations;
  52620. for (var index = 0; index < runtimeAnimations.length; index++) {
  52621. runtimeAnimations[index].dispose();
  52622. }
  52623. this._raiseOnAnimationEnd();
  52624. }
  52625. }
  52626. };
  52627. /**
  52628. * Wait asynchronously for the animation to end
  52629. * @returns a promise which will be fullfilled when the animation ends
  52630. */
  52631. Animatable.prototype.waitAsync = function () {
  52632. var _this = this;
  52633. return new Promise(function (resolve, reject) {
  52634. _this.onAnimationEndObservable.add(function () {
  52635. resolve(_this);
  52636. }, undefined, undefined, _this, true);
  52637. });
  52638. };
  52639. /** @hidden */
  52640. Animatable.prototype._animate = function (delay) {
  52641. if (this._paused) {
  52642. this.animationStarted = false;
  52643. if (this._pausedDelay === null) {
  52644. this._pausedDelay = delay;
  52645. }
  52646. return true;
  52647. }
  52648. if (this._localDelayOffset === null) {
  52649. this._localDelayOffset = delay;
  52650. this._pausedDelay = null;
  52651. }
  52652. else if (this._pausedDelay !== null) {
  52653. this._localDelayOffset += delay - this._pausedDelay;
  52654. this._pausedDelay = null;
  52655. }
  52656. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52657. return true;
  52658. }
  52659. // Animating
  52660. var running = false;
  52661. var runtimeAnimations = this._runtimeAnimations;
  52662. var index;
  52663. for (index = 0; index < runtimeAnimations.length; index++) {
  52664. var animation = runtimeAnimations[index];
  52665. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52666. running = running || isRunning;
  52667. }
  52668. this.animationStarted = running;
  52669. if (!running) {
  52670. // Remove from active animatables
  52671. index = this._scene._activeAnimatables.indexOf(this);
  52672. this._scene._activeAnimatables.splice(index, 1);
  52673. // Dispose all runtime animations
  52674. for (index = 0; index < runtimeAnimations.length; index++) {
  52675. runtimeAnimations[index].dispose();
  52676. }
  52677. this._raiseOnAnimationEnd();
  52678. this.onAnimationEnd = null;
  52679. this.onAnimationEndObservable.clear();
  52680. }
  52681. return running;
  52682. };
  52683. return Animatable;
  52684. }());
  52685. BABYLON.Animatable = Animatable;
  52686. })(BABYLON || (BABYLON = {}));
  52687. //# sourceMappingURL=babylon.animatable.js.map
  52688. var BABYLON;
  52689. (function (BABYLON) {
  52690. var EasingFunction = /** @class */ (function () {
  52691. function EasingFunction() {
  52692. // Properties
  52693. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52694. }
  52695. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52696. get: function () {
  52697. return EasingFunction._EASINGMODE_EASEIN;
  52698. },
  52699. enumerable: true,
  52700. configurable: true
  52701. });
  52702. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52703. get: function () {
  52704. return EasingFunction._EASINGMODE_EASEOUT;
  52705. },
  52706. enumerable: true,
  52707. configurable: true
  52708. });
  52709. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52710. get: function () {
  52711. return EasingFunction._EASINGMODE_EASEINOUT;
  52712. },
  52713. enumerable: true,
  52714. configurable: true
  52715. });
  52716. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52717. var n = Math.min(Math.max(easingMode, 0), 2);
  52718. this._easingMode = n;
  52719. };
  52720. EasingFunction.prototype.getEasingMode = function () {
  52721. return this._easingMode;
  52722. };
  52723. EasingFunction.prototype.easeInCore = function (gradient) {
  52724. throw new Error('You must implement this method');
  52725. };
  52726. EasingFunction.prototype.ease = function (gradient) {
  52727. switch (this._easingMode) {
  52728. case EasingFunction.EASINGMODE_EASEIN:
  52729. return this.easeInCore(gradient);
  52730. case EasingFunction.EASINGMODE_EASEOUT:
  52731. return (1 - this.easeInCore(1 - gradient));
  52732. }
  52733. if (gradient >= 0.5) {
  52734. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52735. }
  52736. return (this.easeInCore(gradient * 2) * 0.5);
  52737. };
  52738. //Statics
  52739. EasingFunction._EASINGMODE_EASEIN = 0;
  52740. EasingFunction._EASINGMODE_EASEOUT = 1;
  52741. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52742. return EasingFunction;
  52743. }());
  52744. BABYLON.EasingFunction = EasingFunction;
  52745. var CircleEase = /** @class */ (function (_super) {
  52746. __extends(CircleEase, _super);
  52747. function CircleEase() {
  52748. return _super !== null && _super.apply(this, arguments) || this;
  52749. }
  52750. CircleEase.prototype.easeInCore = function (gradient) {
  52751. gradient = Math.max(0, Math.min(1, gradient));
  52752. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52753. };
  52754. return CircleEase;
  52755. }(EasingFunction));
  52756. BABYLON.CircleEase = CircleEase;
  52757. var BackEase = /** @class */ (function (_super) {
  52758. __extends(BackEase, _super);
  52759. function BackEase(amplitude) {
  52760. if (amplitude === void 0) { amplitude = 1; }
  52761. var _this = _super.call(this) || this;
  52762. _this.amplitude = amplitude;
  52763. return _this;
  52764. }
  52765. BackEase.prototype.easeInCore = function (gradient) {
  52766. var num = Math.max(0, this.amplitude);
  52767. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52768. };
  52769. return BackEase;
  52770. }(EasingFunction));
  52771. BABYLON.BackEase = BackEase;
  52772. var BounceEase = /** @class */ (function (_super) {
  52773. __extends(BounceEase, _super);
  52774. function BounceEase(bounces, bounciness) {
  52775. if (bounces === void 0) { bounces = 3; }
  52776. if (bounciness === void 0) { bounciness = 2; }
  52777. var _this = _super.call(this) || this;
  52778. _this.bounces = bounces;
  52779. _this.bounciness = bounciness;
  52780. return _this;
  52781. }
  52782. BounceEase.prototype.easeInCore = function (gradient) {
  52783. var y = Math.max(0.0, this.bounces);
  52784. var bounciness = this.bounciness;
  52785. if (bounciness <= 1.0) {
  52786. bounciness = 1.001;
  52787. }
  52788. var num9 = Math.pow(bounciness, y);
  52789. var num5 = 1.0 - bounciness;
  52790. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52791. var num15 = gradient * num4;
  52792. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52793. var num3 = Math.floor(num65);
  52794. var num13 = num3 + 1.0;
  52795. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52796. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52797. var num7 = (num8 + num12) * 0.5;
  52798. var num6 = gradient - num7;
  52799. var num2 = num7 - num8;
  52800. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52801. };
  52802. return BounceEase;
  52803. }(EasingFunction));
  52804. BABYLON.BounceEase = BounceEase;
  52805. var CubicEase = /** @class */ (function (_super) {
  52806. __extends(CubicEase, _super);
  52807. function CubicEase() {
  52808. return _super !== null && _super.apply(this, arguments) || this;
  52809. }
  52810. CubicEase.prototype.easeInCore = function (gradient) {
  52811. return (gradient * gradient * gradient);
  52812. };
  52813. return CubicEase;
  52814. }(EasingFunction));
  52815. BABYLON.CubicEase = CubicEase;
  52816. var ElasticEase = /** @class */ (function (_super) {
  52817. __extends(ElasticEase, _super);
  52818. function ElasticEase(oscillations, springiness) {
  52819. if (oscillations === void 0) { oscillations = 3; }
  52820. if (springiness === void 0) { springiness = 3; }
  52821. var _this = _super.call(this) || this;
  52822. _this.oscillations = oscillations;
  52823. _this.springiness = springiness;
  52824. return _this;
  52825. }
  52826. ElasticEase.prototype.easeInCore = function (gradient) {
  52827. var num2;
  52828. var num3 = Math.max(0.0, this.oscillations);
  52829. var num = Math.max(0.0, this.springiness);
  52830. if (num == 0) {
  52831. num2 = gradient;
  52832. }
  52833. else {
  52834. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52835. }
  52836. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52837. };
  52838. return ElasticEase;
  52839. }(EasingFunction));
  52840. BABYLON.ElasticEase = ElasticEase;
  52841. var ExponentialEase = /** @class */ (function (_super) {
  52842. __extends(ExponentialEase, _super);
  52843. function ExponentialEase(exponent) {
  52844. if (exponent === void 0) { exponent = 2; }
  52845. var _this = _super.call(this) || this;
  52846. _this.exponent = exponent;
  52847. return _this;
  52848. }
  52849. ExponentialEase.prototype.easeInCore = function (gradient) {
  52850. if (this.exponent <= 0) {
  52851. return gradient;
  52852. }
  52853. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52854. };
  52855. return ExponentialEase;
  52856. }(EasingFunction));
  52857. BABYLON.ExponentialEase = ExponentialEase;
  52858. var PowerEase = /** @class */ (function (_super) {
  52859. __extends(PowerEase, _super);
  52860. function PowerEase(power) {
  52861. if (power === void 0) { power = 2; }
  52862. var _this = _super.call(this) || this;
  52863. _this.power = power;
  52864. return _this;
  52865. }
  52866. PowerEase.prototype.easeInCore = function (gradient) {
  52867. var y = Math.max(0.0, this.power);
  52868. return Math.pow(gradient, y);
  52869. };
  52870. return PowerEase;
  52871. }(EasingFunction));
  52872. BABYLON.PowerEase = PowerEase;
  52873. var QuadraticEase = /** @class */ (function (_super) {
  52874. __extends(QuadraticEase, _super);
  52875. function QuadraticEase() {
  52876. return _super !== null && _super.apply(this, arguments) || this;
  52877. }
  52878. QuadraticEase.prototype.easeInCore = function (gradient) {
  52879. return (gradient * gradient);
  52880. };
  52881. return QuadraticEase;
  52882. }(EasingFunction));
  52883. BABYLON.QuadraticEase = QuadraticEase;
  52884. var QuarticEase = /** @class */ (function (_super) {
  52885. __extends(QuarticEase, _super);
  52886. function QuarticEase() {
  52887. return _super !== null && _super.apply(this, arguments) || this;
  52888. }
  52889. QuarticEase.prototype.easeInCore = function (gradient) {
  52890. return (gradient * gradient * gradient * gradient);
  52891. };
  52892. return QuarticEase;
  52893. }(EasingFunction));
  52894. BABYLON.QuarticEase = QuarticEase;
  52895. var QuinticEase = /** @class */ (function (_super) {
  52896. __extends(QuinticEase, _super);
  52897. function QuinticEase() {
  52898. return _super !== null && _super.apply(this, arguments) || this;
  52899. }
  52900. QuinticEase.prototype.easeInCore = function (gradient) {
  52901. return (gradient * gradient * gradient * gradient * gradient);
  52902. };
  52903. return QuinticEase;
  52904. }(EasingFunction));
  52905. BABYLON.QuinticEase = QuinticEase;
  52906. var SineEase = /** @class */ (function (_super) {
  52907. __extends(SineEase, _super);
  52908. function SineEase() {
  52909. return _super !== null && _super.apply(this, arguments) || this;
  52910. }
  52911. SineEase.prototype.easeInCore = function (gradient) {
  52912. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52913. };
  52914. return SineEase;
  52915. }(EasingFunction));
  52916. BABYLON.SineEase = SineEase;
  52917. var BezierCurveEase = /** @class */ (function (_super) {
  52918. __extends(BezierCurveEase, _super);
  52919. function BezierCurveEase(x1, y1, x2, y2) {
  52920. if (x1 === void 0) { x1 = 0; }
  52921. if (y1 === void 0) { y1 = 0; }
  52922. if (x2 === void 0) { x2 = 1; }
  52923. if (y2 === void 0) { y2 = 1; }
  52924. var _this = _super.call(this) || this;
  52925. _this.x1 = x1;
  52926. _this.y1 = y1;
  52927. _this.x2 = x2;
  52928. _this.y2 = y2;
  52929. return _this;
  52930. }
  52931. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52932. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52933. };
  52934. return BezierCurveEase;
  52935. }(EasingFunction));
  52936. BABYLON.BezierCurveEase = BezierCurveEase;
  52937. })(BABYLON || (BABYLON = {}));
  52938. //# sourceMappingURL=babylon.easing.js.map
  52939. var BABYLON;
  52940. (function (BABYLON) {
  52941. /**
  52942. * A Condition applied to an Action
  52943. */
  52944. var Condition = /** @class */ (function () {
  52945. /**
  52946. * Creates a new Condition
  52947. * @param actionManager the manager of the action the condition is applied to
  52948. */
  52949. function Condition(actionManager) {
  52950. this._actionManager = actionManager;
  52951. }
  52952. /**
  52953. * Check if the current condition is valid
  52954. * @returns a boolean
  52955. */
  52956. Condition.prototype.isValid = function () {
  52957. return true;
  52958. };
  52959. /**
  52960. * Internal only
  52961. * @hidden
  52962. */
  52963. Condition.prototype._getProperty = function (propertyPath) {
  52964. return this._actionManager._getProperty(propertyPath);
  52965. };
  52966. /**
  52967. * Internal only
  52968. * @hidden
  52969. */
  52970. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52971. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52972. };
  52973. /**
  52974. * Serialize placeholder for child classes
  52975. * @returns the serialized object
  52976. */
  52977. Condition.prototype.serialize = function () {
  52978. };
  52979. /**
  52980. * Internal only
  52981. * @hidden
  52982. */
  52983. Condition.prototype._serialize = function (serializedCondition) {
  52984. return {
  52985. type: 2,
  52986. children: [],
  52987. name: serializedCondition.name,
  52988. properties: serializedCondition.properties
  52989. };
  52990. };
  52991. return Condition;
  52992. }());
  52993. BABYLON.Condition = Condition;
  52994. /**
  52995. * Defines specific conditional operators as extensions of Condition
  52996. */
  52997. var ValueCondition = /** @class */ (function (_super) {
  52998. __extends(ValueCondition, _super);
  52999. /**
  53000. * Creates a new ValueCondition
  53001. * @param actionManager manager for the action the condition applies to
  53002. * @param target for the action
  53003. * @param propertyPath path to specify the property of the target the conditional operator uses
  53004. * @param value the value compared by the conditional operator against the current value of the property
  53005. * @param operator the conditional operator, default ValueCondition.IsEqual
  53006. */
  53007. function ValueCondition(actionManager, target,
  53008. /** path to specify the property of the target the conditional operator uses */
  53009. propertyPath,
  53010. /** the value compared by the conditional operator against the current value of the property */
  53011. value,
  53012. /** the conditional operator, default ValueCondition.IsEqual */
  53013. operator) {
  53014. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53015. var _this = _super.call(this, actionManager) || this;
  53016. _this.propertyPath = propertyPath;
  53017. _this.value = value;
  53018. _this.operator = operator;
  53019. _this._target = target;
  53020. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53021. _this._property = _this._getProperty(_this.propertyPath);
  53022. return _this;
  53023. }
  53024. Object.defineProperty(ValueCondition, "IsEqual", {
  53025. /**
  53026. * returns the number for IsEqual
  53027. */
  53028. get: function () {
  53029. return ValueCondition._IsEqual;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(ValueCondition, "IsDifferent", {
  53035. /**
  53036. * Returns the number for IsDifferent
  53037. */
  53038. get: function () {
  53039. return ValueCondition._IsDifferent;
  53040. },
  53041. enumerable: true,
  53042. configurable: true
  53043. });
  53044. Object.defineProperty(ValueCondition, "IsGreater", {
  53045. /**
  53046. * Returns the number for IsGreater
  53047. */
  53048. get: function () {
  53049. return ValueCondition._IsGreater;
  53050. },
  53051. enumerable: true,
  53052. configurable: true
  53053. });
  53054. Object.defineProperty(ValueCondition, "IsLesser", {
  53055. /**
  53056. * Returns the number for IsLesser
  53057. */
  53058. get: function () {
  53059. return ValueCondition._IsLesser;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. /**
  53065. * Compares the given value with the property value for the specified conditional operator
  53066. * @returns the result of the comparison
  53067. */
  53068. ValueCondition.prototype.isValid = function () {
  53069. switch (this.operator) {
  53070. case ValueCondition.IsGreater:
  53071. return this._effectiveTarget[this._property] > this.value;
  53072. case ValueCondition.IsLesser:
  53073. return this._effectiveTarget[this._property] < this.value;
  53074. case ValueCondition.IsEqual:
  53075. case ValueCondition.IsDifferent:
  53076. var check;
  53077. if (this.value.equals) {
  53078. check = this.value.equals(this._effectiveTarget[this._property]);
  53079. }
  53080. else {
  53081. check = this.value === this._effectiveTarget[this._property];
  53082. }
  53083. return this.operator === ValueCondition.IsEqual ? check : !check;
  53084. }
  53085. return false;
  53086. };
  53087. /**
  53088. * Serialize the ValueCondition into a JSON compatible object
  53089. * @returns serialization object
  53090. */
  53091. ValueCondition.prototype.serialize = function () {
  53092. return this._serialize({
  53093. name: "ValueCondition",
  53094. properties: [
  53095. BABYLON.Action._GetTargetProperty(this._target),
  53096. { name: "propertyPath", value: this.propertyPath },
  53097. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53098. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53099. ]
  53100. });
  53101. };
  53102. /**
  53103. * Gets the name of the conditional operator for the ValueCondition
  53104. * @param operator the conditional operator
  53105. * @returns the name
  53106. */
  53107. ValueCondition.GetOperatorName = function (operator) {
  53108. switch (operator) {
  53109. case ValueCondition._IsEqual: return "IsEqual";
  53110. case ValueCondition._IsDifferent: return "IsDifferent";
  53111. case ValueCondition._IsGreater: return "IsGreater";
  53112. case ValueCondition._IsLesser: return "IsLesser";
  53113. default: return "";
  53114. }
  53115. };
  53116. /**
  53117. * Internal only
  53118. * @hidden
  53119. */
  53120. ValueCondition._IsEqual = 0;
  53121. /**
  53122. * Internal only
  53123. * @hidden
  53124. */
  53125. ValueCondition._IsDifferent = 1;
  53126. /**
  53127. * Internal only
  53128. * @hidden
  53129. */
  53130. ValueCondition._IsGreater = 2;
  53131. /**
  53132. * Internal only
  53133. * @hidden
  53134. */
  53135. ValueCondition._IsLesser = 3;
  53136. return ValueCondition;
  53137. }(Condition));
  53138. BABYLON.ValueCondition = ValueCondition;
  53139. /**
  53140. * Defines a predicate condition as an extension of Condition
  53141. */
  53142. var PredicateCondition = /** @class */ (function (_super) {
  53143. __extends(PredicateCondition, _super);
  53144. /**
  53145. * Creates a new PredicateCondition
  53146. * @param actionManager manager for the action the condition applies to
  53147. * @param predicate defines the predicate function used to validate the condition
  53148. */
  53149. function PredicateCondition(actionManager,
  53150. /** defines the predicate function used to validate the condition */
  53151. predicate) {
  53152. var _this = _super.call(this, actionManager) || this;
  53153. _this.predicate = predicate;
  53154. return _this;
  53155. }
  53156. /**
  53157. * @returns the validity of the predicate condition
  53158. */
  53159. PredicateCondition.prototype.isValid = function () {
  53160. return this.predicate();
  53161. };
  53162. return PredicateCondition;
  53163. }(Condition));
  53164. BABYLON.PredicateCondition = PredicateCondition;
  53165. /**
  53166. * Defines a state condition as an extension of Condition
  53167. */
  53168. var StateCondition = /** @class */ (function (_super) {
  53169. __extends(StateCondition, _super);
  53170. /**
  53171. * Creates a new StateCondition
  53172. * @param actionManager manager for the action the condition applies to
  53173. * @param target of the condition
  53174. * @param value to compare with target state
  53175. */
  53176. function StateCondition(actionManager, target, value) {
  53177. var _this = _super.call(this, actionManager) || this;
  53178. _this.value = value;
  53179. _this._target = target;
  53180. return _this;
  53181. }
  53182. /**
  53183. * @returns the validity of the state
  53184. */
  53185. StateCondition.prototype.isValid = function () {
  53186. return this._target.state === this.value;
  53187. };
  53188. /**
  53189. * Serialize the StateCondition into a JSON compatible object
  53190. * @returns serialization object
  53191. */
  53192. StateCondition.prototype.serialize = function () {
  53193. return this._serialize({
  53194. name: "StateCondition",
  53195. properties: [
  53196. BABYLON.Action._GetTargetProperty(this._target),
  53197. { name: "value", value: this.value }
  53198. ]
  53199. });
  53200. };
  53201. return StateCondition;
  53202. }(Condition));
  53203. BABYLON.StateCondition = StateCondition;
  53204. })(BABYLON || (BABYLON = {}));
  53205. //# sourceMappingURL=babylon.condition.js.map
  53206. var BABYLON;
  53207. (function (BABYLON) {
  53208. /**
  53209. * The action to be carried out following a trigger
  53210. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53211. */
  53212. var Action = /** @class */ (function () {
  53213. /**
  53214. * Creates a new Action
  53215. * @param triggerOptions the trigger, with or without parameters, for the action
  53216. * @param condition an optional determinant of action
  53217. */
  53218. function Action(
  53219. /** the trigger, with or without parameters, for the action */
  53220. triggerOptions, condition) {
  53221. this.triggerOptions = triggerOptions;
  53222. /**
  53223. * An event triggered prior to action being executed.
  53224. */
  53225. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53226. if (triggerOptions.parameter) {
  53227. this.trigger = triggerOptions.trigger;
  53228. this._triggerParameter = triggerOptions.parameter;
  53229. }
  53230. else {
  53231. this.trigger = triggerOptions;
  53232. }
  53233. this._nextActiveAction = this;
  53234. this._condition = condition;
  53235. }
  53236. /**
  53237. * Internal only
  53238. * @hidden
  53239. */
  53240. Action.prototype._prepare = function () {
  53241. };
  53242. /**
  53243. * Gets the trigger parameters
  53244. * @returns the trigger parameters
  53245. */
  53246. Action.prototype.getTriggerParameter = function () {
  53247. return this._triggerParameter;
  53248. };
  53249. /**
  53250. * Internal only - executes current action event
  53251. * @hidden
  53252. */
  53253. Action.prototype._executeCurrent = function (evt) {
  53254. if (this._nextActiveAction._condition) {
  53255. var condition = this._nextActiveAction._condition;
  53256. var currentRenderId = this._actionManager.getScene().getRenderId();
  53257. // We cache the current evaluation for the current frame
  53258. if (condition._evaluationId === currentRenderId) {
  53259. if (!condition._currentResult) {
  53260. return;
  53261. }
  53262. }
  53263. else {
  53264. condition._evaluationId = currentRenderId;
  53265. if (!condition.isValid()) {
  53266. condition._currentResult = false;
  53267. return;
  53268. }
  53269. condition._currentResult = true;
  53270. }
  53271. }
  53272. this.onBeforeExecuteObservable.notifyObservers(this);
  53273. this._nextActiveAction.execute(evt);
  53274. this.skipToNextActiveAction();
  53275. };
  53276. /**
  53277. * Execute placeholder for child classes
  53278. * @param evt optional action event
  53279. */
  53280. Action.prototype.execute = function (evt) {
  53281. };
  53282. /**
  53283. * Skips to next active action
  53284. */
  53285. Action.prototype.skipToNextActiveAction = function () {
  53286. if (this._nextActiveAction._child) {
  53287. if (!this._nextActiveAction._child._actionManager) {
  53288. this._nextActiveAction._child._actionManager = this._actionManager;
  53289. }
  53290. this._nextActiveAction = this._nextActiveAction._child;
  53291. }
  53292. else {
  53293. this._nextActiveAction = this;
  53294. }
  53295. };
  53296. /**
  53297. * Adds action to chain of actions, may be a DoNothingAction
  53298. * @param action defines the next action to execute
  53299. * @returns The action passed in
  53300. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53301. */
  53302. Action.prototype.then = function (action) {
  53303. this._child = action;
  53304. action._actionManager = this._actionManager;
  53305. action._prepare();
  53306. return action;
  53307. };
  53308. /**
  53309. * Internal only
  53310. * @hidden
  53311. */
  53312. Action.prototype._getProperty = function (propertyPath) {
  53313. return this._actionManager._getProperty(propertyPath);
  53314. };
  53315. /**
  53316. * Internal only
  53317. * @hidden
  53318. */
  53319. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53320. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53321. };
  53322. /**
  53323. * Serialize placeholder for child classes
  53324. * @param parent of child
  53325. * @returns the serialized object
  53326. */
  53327. Action.prototype.serialize = function (parent) {
  53328. };
  53329. /**
  53330. * Internal only called by serialize
  53331. * @hidden
  53332. */
  53333. Action.prototype._serialize = function (serializedAction, parent) {
  53334. var serializationObject = {
  53335. type: 1,
  53336. children: [],
  53337. name: serializedAction.name,
  53338. properties: serializedAction.properties || []
  53339. };
  53340. // Serialize child
  53341. if (this._child) {
  53342. this._child.serialize(serializationObject);
  53343. }
  53344. // Check if "this" has a condition
  53345. if (this._condition) {
  53346. var serializedCondition = this._condition.serialize();
  53347. serializedCondition.children.push(serializationObject);
  53348. if (parent) {
  53349. parent.children.push(serializedCondition);
  53350. }
  53351. return serializedCondition;
  53352. }
  53353. if (parent) {
  53354. parent.children.push(serializationObject);
  53355. }
  53356. return serializationObject;
  53357. };
  53358. /**
  53359. * Internal only
  53360. * @hidden
  53361. */
  53362. Action._SerializeValueAsString = function (value) {
  53363. if (typeof value === "number") {
  53364. return value.toString();
  53365. }
  53366. if (typeof value === "boolean") {
  53367. return value ? "true" : "false";
  53368. }
  53369. if (value instanceof BABYLON.Vector2) {
  53370. return value.x + ", " + value.y;
  53371. }
  53372. if (value instanceof BABYLON.Vector3) {
  53373. return value.x + ", " + value.y + ", " + value.z;
  53374. }
  53375. if (value instanceof BABYLON.Color3) {
  53376. return value.r + ", " + value.g + ", " + value.b;
  53377. }
  53378. if (value instanceof BABYLON.Color4) {
  53379. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53380. }
  53381. return value; // string
  53382. };
  53383. /**
  53384. * Internal only
  53385. * @hidden
  53386. */
  53387. Action._GetTargetProperty = function (target) {
  53388. return {
  53389. name: "target",
  53390. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53391. : target instanceof BABYLON.Light ? "LightProperties"
  53392. : target instanceof BABYLON.Camera ? "CameraProperties"
  53393. : "SceneProperties",
  53394. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53395. };
  53396. };
  53397. return Action;
  53398. }());
  53399. BABYLON.Action = Action;
  53400. })(BABYLON || (BABYLON = {}));
  53401. //# sourceMappingURL=babylon.action.js.map
  53402. var BABYLON;
  53403. (function (BABYLON) {
  53404. /**
  53405. * ActionEvent is the event being sent when an action is triggered.
  53406. */
  53407. var ActionEvent = /** @class */ (function () {
  53408. /**
  53409. * Creates a new ActionEvent
  53410. * @param source The mesh or sprite that triggered the action
  53411. * @param pointerX The X mouse cursor position at the time of the event
  53412. * @param pointerY The Y mouse cursor position at the time of the event
  53413. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53414. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53415. * @param additionalData additional data for the event
  53416. */
  53417. function ActionEvent(
  53418. /** The mesh or sprite that triggered the action */
  53419. source,
  53420. /** The X mouse cursor position at the time of the event */
  53421. pointerX,
  53422. /** The Y mouse cursor position at the time of the event */
  53423. pointerY,
  53424. /** The mesh that is currently pointed at (can be null) */
  53425. meshUnderPointer,
  53426. /** the original (browser) event that triggered the ActionEvent */
  53427. sourceEvent,
  53428. /** additional data for the event */
  53429. additionalData) {
  53430. this.source = source;
  53431. this.pointerX = pointerX;
  53432. this.pointerY = pointerY;
  53433. this.meshUnderPointer = meshUnderPointer;
  53434. this.sourceEvent = sourceEvent;
  53435. this.additionalData = additionalData;
  53436. }
  53437. /**
  53438. * Helper function to auto-create an ActionEvent from a source mesh.
  53439. * @param source The source mesh that triggered the event
  53440. * @param evt The original (browser) event
  53441. * @param additionalData additional data for the event
  53442. * @returns the new ActionEvent
  53443. */
  53444. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53445. var scene = source.getScene();
  53446. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53447. };
  53448. /**
  53449. * Helper function to auto-create an ActionEvent from a source sprite
  53450. * @param source The source sprite that triggered the event
  53451. * @param scene Scene associated with the sprite
  53452. * @param evt The original (browser) event
  53453. * @param additionalData additional data for the event
  53454. * @returns the new ActionEvent
  53455. */
  53456. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53457. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53458. };
  53459. /**
  53460. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53461. * @param scene the scene where the event occurred
  53462. * @param evt The original (browser) event
  53463. * @returns the new ActionEvent
  53464. */
  53465. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53466. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53467. };
  53468. /**
  53469. * Helper function to auto-create an ActionEvent from a primitive
  53470. * @param prim defines the target primitive
  53471. * @param pointerPos defines the pointer position
  53472. * @param evt The original (browser) event
  53473. * @param additionalData additional data for the event
  53474. * @returns the new ActionEvent
  53475. */
  53476. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53477. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53478. };
  53479. return ActionEvent;
  53480. }());
  53481. BABYLON.ActionEvent = ActionEvent;
  53482. /**
  53483. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53484. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53486. */
  53487. var ActionManager = /** @class */ (function () {
  53488. /**
  53489. * Creates a new action manager
  53490. * @param scene defines the hosting scene
  53491. */
  53492. function ActionManager(scene) {
  53493. // Members
  53494. /** Gets the list of actions */
  53495. this.actions = new Array();
  53496. /** Gets the cursor to use when hovering items */
  53497. this.hoverCursor = '';
  53498. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53499. scene._actionManagers.push(this);
  53500. }
  53501. Object.defineProperty(ActionManager, "NothingTrigger", {
  53502. /**
  53503. * Nothing
  53504. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53505. */
  53506. get: function () {
  53507. return ActionManager._NothingTrigger;
  53508. },
  53509. enumerable: true,
  53510. configurable: true
  53511. });
  53512. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53513. /**
  53514. * On pick
  53515. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53516. */
  53517. get: function () {
  53518. return ActionManager._OnPickTrigger;
  53519. },
  53520. enumerable: true,
  53521. configurable: true
  53522. });
  53523. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53524. /**
  53525. * On left pick
  53526. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53527. */
  53528. get: function () {
  53529. return ActionManager._OnLeftPickTrigger;
  53530. },
  53531. enumerable: true,
  53532. configurable: true
  53533. });
  53534. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53535. /**
  53536. * On right pick
  53537. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53538. */
  53539. get: function () {
  53540. return ActionManager._OnRightPickTrigger;
  53541. },
  53542. enumerable: true,
  53543. configurable: true
  53544. });
  53545. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53546. /**
  53547. * On center pick
  53548. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53549. */
  53550. get: function () {
  53551. return ActionManager._OnCenterPickTrigger;
  53552. },
  53553. enumerable: true,
  53554. configurable: true
  53555. });
  53556. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53557. /**
  53558. * On pick down
  53559. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53560. */
  53561. get: function () {
  53562. return ActionManager._OnPickDownTrigger;
  53563. },
  53564. enumerable: true,
  53565. configurable: true
  53566. });
  53567. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53568. /**
  53569. * On double pick
  53570. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53571. */
  53572. get: function () {
  53573. return ActionManager._OnDoublePickTrigger;
  53574. },
  53575. enumerable: true,
  53576. configurable: true
  53577. });
  53578. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53579. /**
  53580. * On pick up
  53581. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53582. */
  53583. get: function () {
  53584. return ActionManager._OnPickUpTrigger;
  53585. },
  53586. enumerable: true,
  53587. configurable: true
  53588. });
  53589. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53590. /**
  53591. * On pick out.
  53592. * This trigger will only be raised if you also declared a OnPickDown
  53593. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53594. */
  53595. get: function () {
  53596. return ActionManager._OnPickOutTrigger;
  53597. },
  53598. enumerable: true,
  53599. configurable: true
  53600. });
  53601. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53602. /**
  53603. * On long press
  53604. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53605. */
  53606. get: function () {
  53607. return ActionManager._OnLongPressTrigger;
  53608. },
  53609. enumerable: true,
  53610. configurable: true
  53611. });
  53612. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53613. /**
  53614. * On pointer over
  53615. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53616. */
  53617. get: function () {
  53618. return ActionManager._OnPointerOverTrigger;
  53619. },
  53620. enumerable: true,
  53621. configurable: true
  53622. });
  53623. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53624. /**
  53625. * On pointer out
  53626. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53627. */
  53628. get: function () {
  53629. return ActionManager._OnPointerOutTrigger;
  53630. },
  53631. enumerable: true,
  53632. configurable: true
  53633. });
  53634. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53635. /**
  53636. * On every frame
  53637. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53638. */
  53639. get: function () {
  53640. return ActionManager._OnEveryFrameTrigger;
  53641. },
  53642. enumerable: true,
  53643. configurable: true
  53644. });
  53645. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53646. /**
  53647. * On intersection enter
  53648. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53649. */
  53650. get: function () {
  53651. return ActionManager._OnIntersectionEnterTrigger;
  53652. },
  53653. enumerable: true,
  53654. configurable: true
  53655. });
  53656. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53657. /**
  53658. * On intersection exit
  53659. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53660. */
  53661. get: function () {
  53662. return ActionManager._OnIntersectionExitTrigger;
  53663. },
  53664. enumerable: true,
  53665. configurable: true
  53666. });
  53667. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53668. /**
  53669. * On key down
  53670. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53671. */
  53672. get: function () {
  53673. return ActionManager._OnKeyDownTrigger;
  53674. },
  53675. enumerable: true,
  53676. configurable: true
  53677. });
  53678. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53679. /**
  53680. * On key up
  53681. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53682. */
  53683. get: function () {
  53684. return ActionManager._OnKeyUpTrigger;
  53685. },
  53686. enumerable: true,
  53687. configurable: true
  53688. });
  53689. // Methods
  53690. /**
  53691. * Releases all associated resources
  53692. */
  53693. ActionManager.prototype.dispose = function () {
  53694. var index = this._scene._actionManagers.indexOf(this);
  53695. for (var i = 0; i < this.actions.length; i++) {
  53696. var action = this.actions[i];
  53697. ActionManager.Triggers[action.trigger]--;
  53698. if (ActionManager.Triggers[action.trigger] === 0) {
  53699. delete ActionManager.Triggers[action.trigger];
  53700. }
  53701. }
  53702. if (index > -1) {
  53703. this._scene._actionManagers.splice(index, 1);
  53704. }
  53705. };
  53706. /**
  53707. * Gets hosting scene
  53708. * @returns the hosting scene
  53709. */
  53710. ActionManager.prototype.getScene = function () {
  53711. return this._scene;
  53712. };
  53713. /**
  53714. * Does this action manager handles actions of any of the given triggers
  53715. * @param triggers defines the triggers to be tested
  53716. * @return a boolean indicating whether one (or more) of the triggers is handled
  53717. */
  53718. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53719. for (var index = 0; index < this.actions.length; index++) {
  53720. var action = this.actions[index];
  53721. if (triggers.indexOf(action.trigger) > -1) {
  53722. return true;
  53723. }
  53724. }
  53725. return false;
  53726. };
  53727. /**
  53728. * Does this action manager handles actions of a given trigger
  53729. * @param trigger defines the trigger to be tested
  53730. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53731. * @return whether the trigger is handled
  53732. */
  53733. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53734. for (var index = 0; index < this.actions.length; index++) {
  53735. var action = this.actions[index];
  53736. if (action.trigger === trigger) {
  53737. if (parameterPredicate) {
  53738. if (parameterPredicate(action.getTriggerParameter())) {
  53739. return true;
  53740. }
  53741. }
  53742. else {
  53743. return true;
  53744. }
  53745. }
  53746. }
  53747. return false;
  53748. };
  53749. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53750. /**
  53751. * Does this action manager has pointer triggers
  53752. */
  53753. get: function () {
  53754. for (var index = 0; index < this.actions.length; index++) {
  53755. var action = this.actions[index];
  53756. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53757. return true;
  53758. }
  53759. }
  53760. return false;
  53761. },
  53762. enumerable: true,
  53763. configurable: true
  53764. });
  53765. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53766. /**
  53767. * Does this action manager has pick triggers
  53768. */
  53769. get: function () {
  53770. for (var index = 0; index < this.actions.length; index++) {
  53771. var action = this.actions[index];
  53772. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53773. return true;
  53774. }
  53775. }
  53776. return false;
  53777. },
  53778. enumerable: true,
  53779. configurable: true
  53780. });
  53781. Object.defineProperty(ActionManager, "HasTriggers", {
  53782. /**
  53783. * Does exist one action manager with at least one trigger
  53784. **/
  53785. get: function () {
  53786. for (var t in ActionManager.Triggers) {
  53787. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53788. return true;
  53789. }
  53790. }
  53791. return false;
  53792. },
  53793. enumerable: true,
  53794. configurable: true
  53795. });
  53796. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53797. /**
  53798. * Does exist one action manager with at least one pick trigger
  53799. **/
  53800. get: function () {
  53801. for (var t in ActionManager.Triggers) {
  53802. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53803. var t_int = parseInt(t);
  53804. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53805. return true;
  53806. }
  53807. }
  53808. }
  53809. return false;
  53810. },
  53811. enumerable: true,
  53812. configurable: true
  53813. });
  53814. /**
  53815. * Does exist one action manager that handles actions of a given trigger
  53816. * @param trigger defines the trigger to be tested
  53817. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53818. **/
  53819. ActionManager.HasSpecificTrigger = function (trigger) {
  53820. for (var t in ActionManager.Triggers) {
  53821. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53822. var t_int = parseInt(t);
  53823. if (t_int === trigger) {
  53824. return true;
  53825. }
  53826. }
  53827. }
  53828. return false;
  53829. };
  53830. /**
  53831. * Registers an action to this action manager
  53832. * @param action defines the action to be registered
  53833. * @return the action amended (prepared) after registration
  53834. */
  53835. ActionManager.prototype.registerAction = function (action) {
  53836. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53837. if (this.getScene().actionManager !== this) {
  53838. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53839. return null;
  53840. }
  53841. }
  53842. this.actions.push(action);
  53843. if (ActionManager.Triggers[action.trigger]) {
  53844. ActionManager.Triggers[action.trigger]++;
  53845. }
  53846. else {
  53847. ActionManager.Triggers[action.trigger] = 1;
  53848. }
  53849. action._actionManager = this;
  53850. action._prepare();
  53851. return action;
  53852. };
  53853. /**
  53854. * Unregisters an action to this action manager
  53855. * @param action defines the action to be unregistered
  53856. * @return a boolean indicating whether the action has been unregistered
  53857. */
  53858. ActionManager.prototype.unregisterAction = function (action) {
  53859. var index = this.actions.indexOf(action);
  53860. if (index !== -1) {
  53861. this.actions.splice(index, 1);
  53862. ActionManager.Triggers[action.trigger] -= 1;
  53863. if (ActionManager.Triggers[action.trigger] === 0) {
  53864. delete ActionManager.Triggers[action.trigger];
  53865. }
  53866. delete action._actionManager;
  53867. return true;
  53868. }
  53869. return false;
  53870. };
  53871. /**
  53872. * Process a specific trigger
  53873. * @param trigger defines the trigger to process
  53874. * @param evt defines the event details to be processed
  53875. */
  53876. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53877. for (var index = 0; index < this.actions.length; index++) {
  53878. var action = this.actions[index];
  53879. if (action.trigger === trigger) {
  53880. if (evt) {
  53881. if (trigger === ActionManager.OnKeyUpTrigger
  53882. || trigger === ActionManager.OnKeyDownTrigger) {
  53883. var parameter = action.getTriggerParameter();
  53884. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53885. if (!parameter.toLowerCase) {
  53886. continue;
  53887. }
  53888. var lowerCase = parameter.toLowerCase();
  53889. if (lowerCase !== evt.sourceEvent.key) {
  53890. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53891. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53892. if (actualkey !== lowerCase) {
  53893. continue;
  53894. }
  53895. }
  53896. }
  53897. }
  53898. }
  53899. action._executeCurrent(evt);
  53900. }
  53901. }
  53902. };
  53903. /** @hidden */
  53904. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53905. var properties = propertyPath.split(".");
  53906. for (var index = 0; index < properties.length - 1; index++) {
  53907. target = target[properties[index]];
  53908. }
  53909. return target;
  53910. };
  53911. /** @hidden */
  53912. ActionManager.prototype._getProperty = function (propertyPath) {
  53913. var properties = propertyPath.split(".");
  53914. return properties[properties.length - 1];
  53915. };
  53916. /**
  53917. * Serialize this manager to a JSON object
  53918. * @param name defines the property name to store this manager
  53919. * @returns a JSON representation of this manager
  53920. */
  53921. ActionManager.prototype.serialize = function (name) {
  53922. var root = {
  53923. children: new Array(),
  53924. name: name,
  53925. type: 3,
  53926. properties: new Array() // Empty for root but required
  53927. };
  53928. for (var i = 0; i < this.actions.length; i++) {
  53929. var triggerObject = {
  53930. type: 0,
  53931. children: new Array(),
  53932. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53933. properties: new Array()
  53934. };
  53935. var triggerOptions = this.actions[i].triggerOptions;
  53936. if (triggerOptions && typeof triggerOptions !== "number") {
  53937. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53938. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53939. }
  53940. else {
  53941. var parameter = {};
  53942. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53943. if (triggerOptions.parameter.mesh) {
  53944. parameter._meshId = triggerOptions.parameter.mesh.id;
  53945. }
  53946. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53947. }
  53948. }
  53949. // Serialize child action, recursively
  53950. this.actions[i].serialize(triggerObject);
  53951. // Add serialized trigger
  53952. root.children.push(triggerObject);
  53953. }
  53954. return root;
  53955. };
  53956. /**
  53957. * Creates a new ActionManager from a JSON data
  53958. * @param parsedActions defines the JSON data to read from
  53959. * @param object defines the hosting mesh
  53960. * @param scene defines the hosting scene
  53961. */
  53962. ActionManager.Parse = function (parsedActions, object, scene) {
  53963. var actionManager = new ActionManager(scene);
  53964. if (object === null)
  53965. scene.actionManager = actionManager;
  53966. else
  53967. object.actionManager = actionManager;
  53968. // instanciate a new object
  53969. var instanciate = function (name, params) {
  53970. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53971. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53972. newInstance.constructor.apply(newInstance, params);
  53973. return newInstance;
  53974. };
  53975. var parseParameter = function (name, value, target, propertyPath) {
  53976. if (propertyPath === null) {
  53977. // String, boolean or float
  53978. var floatValue = parseFloat(value);
  53979. if (value === "true" || value === "false")
  53980. return value === "true";
  53981. else
  53982. return isNaN(floatValue) ? value : floatValue;
  53983. }
  53984. var effectiveTarget = propertyPath.split(".");
  53985. var values = value.split(",");
  53986. // Get effective Target
  53987. for (var i = 0; i < effectiveTarget.length; i++) {
  53988. target = target[effectiveTarget[i]];
  53989. }
  53990. // Return appropriate value with its type
  53991. if (typeof (target) === "boolean")
  53992. return values[0] === "true";
  53993. if (typeof (target) === "string")
  53994. return values[0];
  53995. // Parameters with multiple values such as Vector3 etc.
  53996. var split = new Array();
  53997. for (var i = 0; i < values.length; i++)
  53998. split.push(parseFloat(values[i]));
  53999. if (target instanceof BABYLON.Vector3)
  54000. return BABYLON.Vector3.FromArray(split);
  54001. if (target instanceof BABYLON.Vector4)
  54002. return BABYLON.Vector4.FromArray(split);
  54003. if (target instanceof BABYLON.Color3)
  54004. return BABYLON.Color3.FromArray(split);
  54005. if (target instanceof BABYLON.Color4)
  54006. return BABYLON.Color4.FromArray(split);
  54007. return parseFloat(values[0]);
  54008. };
  54009. // traverse graph per trigger
  54010. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54011. if (combineArray === void 0) { combineArray = null; }
  54012. if (parsedAction.detached)
  54013. return;
  54014. var parameters = new Array();
  54015. var target = null;
  54016. var propertyPath = null;
  54017. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54018. // Parameters
  54019. if (parsedAction.type === 2)
  54020. parameters.push(actionManager);
  54021. else
  54022. parameters.push(trigger);
  54023. if (combine) {
  54024. var actions = new Array();
  54025. for (var j = 0; j < parsedAction.combine.length; j++) {
  54026. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54027. }
  54028. parameters.push(actions);
  54029. }
  54030. else {
  54031. for (var i = 0; i < parsedAction.properties.length; i++) {
  54032. var value = parsedAction.properties[i].value;
  54033. var name = parsedAction.properties[i].name;
  54034. var targetType = parsedAction.properties[i].targetType;
  54035. if (name === "target")
  54036. if (targetType !== null && targetType === "SceneProperties")
  54037. value = target = scene;
  54038. else
  54039. value = target = scene.getNodeByName(value);
  54040. else if (name === "parent")
  54041. value = scene.getNodeByName(value);
  54042. else if (name === "sound")
  54043. value = scene.getSoundByName(value);
  54044. else if (name !== "propertyPath") {
  54045. if (parsedAction.type === 2 && name === "operator")
  54046. value = BABYLON.ValueCondition[value];
  54047. else
  54048. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54049. }
  54050. else {
  54051. propertyPath = value;
  54052. }
  54053. parameters.push(value);
  54054. }
  54055. }
  54056. if (combineArray === null) {
  54057. parameters.push(condition);
  54058. }
  54059. else {
  54060. parameters.push(null);
  54061. }
  54062. // If interpolate value action
  54063. if (parsedAction.name === "InterpolateValueAction") {
  54064. var param = parameters[parameters.length - 2];
  54065. parameters[parameters.length - 1] = param;
  54066. parameters[parameters.length - 2] = condition;
  54067. }
  54068. // Action or condition(s) and not CombineAction
  54069. var newAction = instanciate(parsedAction.name, parameters);
  54070. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54071. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54072. if (action)
  54073. action.then(nothing);
  54074. else
  54075. actionManager.registerAction(nothing);
  54076. action = nothing;
  54077. }
  54078. if (combineArray === null) {
  54079. if (newAction instanceof BABYLON.Condition) {
  54080. condition = newAction;
  54081. newAction = action;
  54082. }
  54083. else {
  54084. condition = null;
  54085. if (action)
  54086. action.then(newAction);
  54087. else
  54088. actionManager.registerAction(newAction);
  54089. }
  54090. }
  54091. else {
  54092. combineArray.push(newAction);
  54093. }
  54094. for (var i = 0; i < parsedAction.children.length; i++)
  54095. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54096. };
  54097. // triggers
  54098. for (var i = 0; i < parsedActions.children.length; i++) {
  54099. var triggerParams;
  54100. var trigger = parsedActions.children[i];
  54101. if (trigger.properties.length > 0) {
  54102. var param = trigger.properties[0].value;
  54103. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54104. if (value._meshId) {
  54105. value.mesh = scene.getMeshByID(value._meshId);
  54106. }
  54107. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54108. }
  54109. else
  54110. triggerParams = ActionManager[trigger.name];
  54111. for (var j = 0; j < trigger.children.length; j++) {
  54112. if (!trigger.detached)
  54113. traverse(trigger.children[j], triggerParams, null, null);
  54114. }
  54115. }
  54116. };
  54117. /**
  54118. * Get a trigger name by index
  54119. * @param trigger defines the trigger index
  54120. * @returns a trigger name
  54121. */
  54122. ActionManager.GetTriggerName = function (trigger) {
  54123. switch (trigger) {
  54124. case 0: return "NothingTrigger";
  54125. case 1: return "OnPickTrigger";
  54126. case 2: return "OnLeftPickTrigger";
  54127. case 3: return "OnRightPickTrigger";
  54128. case 4: return "OnCenterPickTrigger";
  54129. case 5: return "OnPickDownTrigger";
  54130. case 6: return "OnPickUpTrigger";
  54131. case 7: return "OnLongPressTrigger";
  54132. case 8: return "OnPointerOverTrigger";
  54133. case 9: return "OnPointerOutTrigger";
  54134. case 10: return "OnEveryFrameTrigger";
  54135. case 11: return "OnIntersectionEnterTrigger";
  54136. case 12: return "OnIntersectionExitTrigger";
  54137. case 13: return "OnKeyDownTrigger";
  54138. case 14: return "OnKeyUpTrigger";
  54139. case 15: return "OnPickOutTrigger";
  54140. default: return "";
  54141. }
  54142. };
  54143. // Statics
  54144. ActionManager._NothingTrigger = 0;
  54145. ActionManager._OnPickTrigger = 1;
  54146. ActionManager._OnLeftPickTrigger = 2;
  54147. ActionManager._OnRightPickTrigger = 3;
  54148. ActionManager._OnCenterPickTrigger = 4;
  54149. ActionManager._OnPickDownTrigger = 5;
  54150. ActionManager._OnDoublePickTrigger = 6;
  54151. ActionManager._OnPickUpTrigger = 7;
  54152. ActionManager._OnLongPressTrigger = 8;
  54153. ActionManager._OnPointerOverTrigger = 9;
  54154. ActionManager._OnPointerOutTrigger = 10;
  54155. ActionManager._OnEveryFrameTrigger = 11;
  54156. ActionManager._OnIntersectionEnterTrigger = 12;
  54157. ActionManager._OnIntersectionExitTrigger = 13;
  54158. ActionManager._OnKeyDownTrigger = 14;
  54159. ActionManager._OnKeyUpTrigger = 15;
  54160. ActionManager._OnPickOutTrigger = 16;
  54161. /** Gets the list of active triggers */
  54162. ActionManager.Triggers = {};
  54163. return ActionManager;
  54164. }());
  54165. BABYLON.ActionManager = ActionManager;
  54166. })(BABYLON || (BABYLON = {}));
  54167. //# sourceMappingURL=babylon.actionManager.js.map
  54168. var BABYLON;
  54169. (function (BABYLON) {
  54170. var InterpolateValueAction = /** @class */ (function (_super) {
  54171. __extends(InterpolateValueAction, _super);
  54172. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54173. if (duration === void 0) { duration = 1000; }
  54174. var _this = _super.call(this, triggerOptions, condition) || this;
  54175. _this.propertyPath = propertyPath;
  54176. _this.value = value;
  54177. _this.duration = duration;
  54178. _this.stopOtherAnimations = stopOtherAnimations;
  54179. _this.onInterpolationDone = onInterpolationDone;
  54180. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54181. _this._target = _this._effectiveTarget = target;
  54182. return _this;
  54183. }
  54184. InterpolateValueAction.prototype._prepare = function () {
  54185. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54186. this._property = this._getProperty(this.propertyPath);
  54187. };
  54188. InterpolateValueAction.prototype.execute = function () {
  54189. var _this = this;
  54190. var scene = this._actionManager.getScene();
  54191. var keys = [
  54192. {
  54193. frame: 0,
  54194. value: this._effectiveTarget[this._property]
  54195. }, {
  54196. frame: 100,
  54197. value: this.value
  54198. }
  54199. ];
  54200. var dataType;
  54201. if (typeof this.value === "number") {
  54202. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54203. }
  54204. else if (this.value instanceof BABYLON.Color3) {
  54205. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54206. }
  54207. else if (this.value instanceof BABYLON.Vector3) {
  54208. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54209. }
  54210. else if (this.value instanceof BABYLON.Matrix) {
  54211. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54212. }
  54213. else if (this.value instanceof BABYLON.Quaternion) {
  54214. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54215. }
  54216. else {
  54217. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54218. return;
  54219. }
  54220. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54221. animation.setKeys(keys);
  54222. if (this.stopOtherAnimations) {
  54223. scene.stopAnimation(this._effectiveTarget);
  54224. }
  54225. var wrapper = function () {
  54226. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54227. if (_this.onInterpolationDone) {
  54228. _this.onInterpolationDone();
  54229. }
  54230. };
  54231. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54232. };
  54233. InterpolateValueAction.prototype.serialize = function (parent) {
  54234. return _super.prototype._serialize.call(this, {
  54235. name: "InterpolateValueAction",
  54236. properties: [
  54237. BABYLON.Action._GetTargetProperty(this._target),
  54238. { name: "propertyPath", value: this.propertyPath },
  54239. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54240. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54241. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54242. ]
  54243. }, parent);
  54244. };
  54245. return InterpolateValueAction;
  54246. }(BABYLON.Action));
  54247. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54248. })(BABYLON || (BABYLON = {}));
  54249. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54250. var BABYLON;
  54251. (function (BABYLON) {
  54252. var SwitchBooleanAction = /** @class */ (function (_super) {
  54253. __extends(SwitchBooleanAction, _super);
  54254. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54255. var _this = _super.call(this, triggerOptions, condition) || this;
  54256. _this.propertyPath = propertyPath;
  54257. _this._target = _this._effectiveTarget = target;
  54258. return _this;
  54259. }
  54260. SwitchBooleanAction.prototype._prepare = function () {
  54261. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54262. this._property = this._getProperty(this.propertyPath);
  54263. };
  54264. SwitchBooleanAction.prototype.execute = function () {
  54265. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54266. };
  54267. SwitchBooleanAction.prototype.serialize = function (parent) {
  54268. return _super.prototype._serialize.call(this, {
  54269. name: "SwitchBooleanAction",
  54270. properties: [
  54271. BABYLON.Action._GetTargetProperty(this._target),
  54272. { name: "propertyPath", value: this.propertyPath }
  54273. ]
  54274. }, parent);
  54275. };
  54276. return SwitchBooleanAction;
  54277. }(BABYLON.Action));
  54278. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54279. var SetStateAction = /** @class */ (function (_super) {
  54280. __extends(SetStateAction, _super);
  54281. function SetStateAction(triggerOptions, target, value, condition) {
  54282. var _this = _super.call(this, triggerOptions, condition) || this;
  54283. _this.value = value;
  54284. _this._target = target;
  54285. return _this;
  54286. }
  54287. SetStateAction.prototype.execute = function () {
  54288. this._target.state = this.value;
  54289. };
  54290. SetStateAction.prototype.serialize = function (parent) {
  54291. return _super.prototype._serialize.call(this, {
  54292. name: "SetStateAction",
  54293. properties: [
  54294. BABYLON.Action._GetTargetProperty(this._target),
  54295. { name: "value", value: this.value }
  54296. ]
  54297. }, parent);
  54298. };
  54299. return SetStateAction;
  54300. }(BABYLON.Action));
  54301. BABYLON.SetStateAction = SetStateAction;
  54302. var SetValueAction = /** @class */ (function (_super) {
  54303. __extends(SetValueAction, _super);
  54304. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54305. var _this = _super.call(this, triggerOptions, condition) || this;
  54306. _this.propertyPath = propertyPath;
  54307. _this.value = value;
  54308. _this._target = _this._effectiveTarget = target;
  54309. return _this;
  54310. }
  54311. SetValueAction.prototype._prepare = function () {
  54312. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54313. this._property = this._getProperty(this.propertyPath);
  54314. };
  54315. SetValueAction.prototype.execute = function () {
  54316. this._effectiveTarget[this._property] = this.value;
  54317. if (this._target.markAsDirty) {
  54318. this._target.markAsDirty(this._property);
  54319. }
  54320. };
  54321. SetValueAction.prototype.serialize = function (parent) {
  54322. return _super.prototype._serialize.call(this, {
  54323. name: "SetValueAction",
  54324. properties: [
  54325. BABYLON.Action._GetTargetProperty(this._target),
  54326. { name: "propertyPath", value: this.propertyPath },
  54327. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54328. ]
  54329. }, parent);
  54330. };
  54331. return SetValueAction;
  54332. }(BABYLON.Action));
  54333. BABYLON.SetValueAction = SetValueAction;
  54334. var IncrementValueAction = /** @class */ (function (_super) {
  54335. __extends(IncrementValueAction, _super);
  54336. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54337. var _this = _super.call(this, triggerOptions, condition) || this;
  54338. _this.propertyPath = propertyPath;
  54339. _this.value = value;
  54340. _this._target = _this._effectiveTarget = target;
  54341. return _this;
  54342. }
  54343. IncrementValueAction.prototype._prepare = function () {
  54344. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54345. this._property = this._getProperty(this.propertyPath);
  54346. if (typeof this._effectiveTarget[this._property] !== "number") {
  54347. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54348. }
  54349. };
  54350. IncrementValueAction.prototype.execute = function () {
  54351. this._effectiveTarget[this._property] += this.value;
  54352. if (this._target.markAsDirty) {
  54353. this._target.markAsDirty(this._property);
  54354. }
  54355. };
  54356. IncrementValueAction.prototype.serialize = function (parent) {
  54357. return _super.prototype._serialize.call(this, {
  54358. name: "IncrementValueAction",
  54359. properties: [
  54360. BABYLON.Action._GetTargetProperty(this._target),
  54361. { name: "propertyPath", value: this.propertyPath },
  54362. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54363. ]
  54364. }, parent);
  54365. };
  54366. return IncrementValueAction;
  54367. }(BABYLON.Action));
  54368. BABYLON.IncrementValueAction = IncrementValueAction;
  54369. var PlayAnimationAction = /** @class */ (function (_super) {
  54370. __extends(PlayAnimationAction, _super);
  54371. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54372. var _this = _super.call(this, triggerOptions, condition) || this;
  54373. _this.from = from;
  54374. _this.to = to;
  54375. _this.loop = loop;
  54376. _this._target = target;
  54377. return _this;
  54378. }
  54379. PlayAnimationAction.prototype._prepare = function () {
  54380. };
  54381. PlayAnimationAction.prototype.execute = function () {
  54382. var scene = this._actionManager.getScene();
  54383. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54384. };
  54385. PlayAnimationAction.prototype.serialize = function (parent) {
  54386. return _super.prototype._serialize.call(this, {
  54387. name: "PlayAnimationAction",
  54388. properties: [
  54389. BABYLON.Action._GetTargetProperty(this._target),
  54390. { name: "from", value: String(this.from) },
  54391. { name: "to", value: String(this.to) },
  54392. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54393. ]
  54394. }, parent);
  54395. };
  54396. return PlayAnimationAction;
  54397. }(BABYLON.Action));
  54398. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54399. var StopAnimationAction = /** @class */ (function (_super) {
  54400. __extends(StopAnimationAction, _super);
  54401. function StopAnimationAction(triggerOptions, target, condition) {
  54402. var _this = _super.call(this, triggerOptions, condition) || this;
  54403. _this._target = target;
  54404. return _this;
  54405. }
  54406. StopAnimationAction.prototype._prepare = function () {
  54407. };
  54408. StopAnimationAction.prototype.execute = function () {
  54409. var scene = this._actionManager.getScene();
  54410. scene.stopAnimation(this._target);
  54411. };
  54412. StopAnimationAction.prototype.serialize = function (parent) {
  54413. return _super.prototype._serialize.call(this, {
  54414. name: "StopAnimationAction",
  54415. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54416. }, parent);
  54417. };
  54418. return StopAnimationAction;
  54419. }(BABYLON.Action));
  54420. BABYLON.StopAnimationAction = StopAnimationAction;
  54421. var DoNothingAction = /** @class */ (function (_super) {
  54422. __extends(DoNothingAction, _super);
  54423. function DoNothingAction(triggerOptions, condition) {
  54424. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54425. return _super.call(this, triggerOptions, condition) || this;
  54426. }
  54427. DoNothingAction.prototype.execute = function () {
  54428. };
  54429. DoNothingAction.prototype.serialize = function (parent) {
  54430. return _super.prototype._serialize.call(this, {
  54431. name: "DoNothingAction",
  54432. properties: []
  54433. }, parent);
  54434. };
  54435. return DoNothingAction;
  54436. }(BABYLON.Action));
  54437. BABYLON.DoNothingAction = DoNothingAction;
  54438. var CombineAction = /** @class */ (function (_super) {
  54439. __extends(CombineAction, _super);
  54440. function CombineAction(triggerOptions, children, condition) {
  54441. var _this = _super.call(this, triggerOptions, condition) || this;
  54442. _this.children = children;
  54443. return _this;
  54444. }
  54445. CombineAction.prototype._prepare = function () {
  54446. for (var index = 0; index < this.children.length; index++) {
  54447. this.children[index]._actionManager = this._actionManager;
  54448. this.children[index]._prepare();
  54449. }
  54450. };
  54451. CombineAction.prototype.execute = function (evt) {
  54452. for (var index = 0; index < this.children.length; index++) {
  54453. this.children[index].execute(evt);
  54454. }
  54455. };
  54456. CombineAction.prototype.serialize = function (parent) {
  54457. var serializationObject = _super.prototype._serialize.call(this, {
  54458. name: "CombineAction",
  54459. properties: [],
  54460. combine: []
  54461. }, parent);
  54462. for (var i = 0; i < this.children.length; i++) {
  54463. serializationObject.combine.push(this.children[i].serialize(null));
  54464. }
  54465. return serializationObject;
  54466. };
  54467. return CombineAction;
  54468. }(BABYLON.Action));
  54469. BABYLON.CombineAction = CombineAction;
  54470. var ExecuteCodeAction = /** @class */ (function (_super) {
  54471. __extends(ExecuteCodeAction, _super);
  54472. function ExecuteCodeAction(triggerOptions, func, condition) {
  54473. var _this = _super.call(this, triggerOptions, condition) || this;
  54474. _this.func = func;
  54475. return _this;
  54476. }
  54477. ExecuteCodeAction.prototype.execute = function (evt) {
  54478. this.func(evt);
  54479. };
  54480. return ExecuteCodeAction;
  54481. }(BABYLON.Action));
  54482. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54483. var SetParentAction = /** @class */ (function (_super) {
  54484. __extends(SetParentAction, _super);
  54485. function SetParentAction(triggerOptions, target, parent, condition) {
  54486. var _this = _super.call(this, triggerOptions, condition) || this;
  54487. _this._target = target;
  54488. _this._parent = parent;
  54489. return _this;
  54490. }
  54491. SetParentAction.prototype._prepare = function () {
  54492. };
  54493. SetParentAction.prototype.execute = function () {
  54494. if (this._target.parent === this._parent) {
  54495. return;
  54496. }
  54497. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54498. invertParentWorldMatrix.invert();
  54499. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54500. this._target.parent = this._parent;
  54501. };
  54502. SetParentAction.prototype.serialize = function (parent) {
  54503. return _super.prototype._serialize.call(this, {
  54504. name: "SetParentAction",
  54505. properties: [
  54506. BABYLON.Action._GetTargetProperty(this._target),
  54507. BABYLON.Action._GetTargetProperty(this._parent),
  54508. ]
  54509. }, parent);
  54510. };
  54511. return SetParentAction;
  54512. }(BABYLON.Action));
  54513. BABYLON.SetParentAction = SetParentAction;
  54514. var PlaySoundAction = /** @class */ (function (_super) {
  54515. __extends(PlaySoundAction, _super);
  54516. function PlaySoundAction(triggerOptions, sound, condition) {
  54517. var _this = _super.call(this, triggerOptions, condition) || this;
  54518. _this._sound = sound;
  54519. return _this;
  54520. }
  54521. PlaySoundAction.prototype._prepare = function () {
  54522. };
  54523. PlaySoundAction.prototype.execute = function () {
  54524. if (this._sound !== undefined)
  54525. this._sound.play();
  54526. };
  54527. PlaySoundAction.prototype.serialize = function (parent) {
  54528. return _super.prototype._serialize.call(this, {
  54529. name: "PlaySoundAction",
  54530. properties: [{ name: "sound", value: this._sound.name }]
  54531. }, parent);
  54532. };
  54533. return PlaySoundAction;
  54534. }(BABYLON.Action));
  54535. BABYLON.PlaySoundAction = PlaySoundAction;
  54536. var StopSoundAction = /** @class */ (function (_super) {
  54537. __extends(StopSoundAction, _super);
  54538. function StopSoundAction(triggerOptions, sound, condition) {
  54539. var _this = _super.call(this, triggerOptions, condition) || this;
  54540. _this._sound = sound;
  54541. return _this;
  54542. }
  54543. StopSoundAction.prototype._prepare = function () {
  54544. };
  54545. StopSoundAction.prototype.execute = function () {
  54546. if (this._sound !== undefined)
  54547. this._sound.stop();
  54548. };
  54549. StopSoundAction.prototype.serialize = function (parent) {
  54550. return _super.prototype._serialize.call(this, {
  54551. name: "StopSoundAction",
  54552. properties: [{ name: "sound", value: this._sound.name }]
  54553. }, parent);
  54554. };
  54555. return StopSoundAction;
  54556. }(BABYLON.Action));
  54557. BABYLON.StopSoundAction = StopSoundAction;
  54558. })(BABYLON || (BABYLON = {}));
  54559. //# sourceMappingURL=babylon.directActions.js.map
  54560. var BABYLON;
  54561. (function (BABYLON) {
  54562. var SpriteManager = /** @class */ (function () {
  54563. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54564. if (epsilon === void 0) { epsilon = 0.01; }
  54565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54566. this.name = name;
  54567. this.sprites = new Array();
  54568. this.renderingGroupId = 0;
  54569. this.layerMask = 0x0FFFFFFF;
  54570. this.fogEnabled = true;
  54571. this.isPickable = false;
  54572. /**
  54573. * An event triggered when the manager is disposed.
  54574. */
  54575. this.onDisposeObservable = new BABYLON.Observable();
  54576. this._vertexBuffers = {};
  54577. this._capacity = capacity;
  54578. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54579. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54580. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54581. if (cellSize.width && cellSize.height) {
  54582. this.cellWidth = cellSize.width;
  54583. this.cellHeight = cellSize.height;
  54584. }
  54585. else if (cellSize !== undefined) {
  54586. this.cellWidth = cellSize;
  54587. this.cellHeight = cellSize;
  54588. }
  54589. else {
  54590. return;
  54591. }
  54592. this._epsilon = epsilon;
  54593. this._scene = scene;
  54594. this._scene.spriteManagers.push(this);
  54595. var indices = [];
  54596. var index = 0;
  54597. for (var count = 0; count < capacity; count++) {
  54598. indices.push(index);
  54599. indices.push(index + 1);
  54600. indices.push(index + 2);
  54601. indices.push(index);
  54602. indices.push(index + 2);
  54603. indices.push(index + 3);
  54604. index += 4;
  54605. }
  54606. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54607. // VBO
  54608. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54609. this._vertexData = new Float32Array(capacity * 16 * 4);
  54610. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54611. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54612. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54613. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54614. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54615. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54616. this._vertexBuffers["options"] = options;
  54617. this._vertexBuffers["cellInfo"] = cellInfo;
  54618. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54619. // Effects
  54620. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54621. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54622. }
  54623. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54624. set: function (callback) {
  54625. if (this._onDisposeObserver) {
  54626. this.onDisposeObservable.remove(this._onDisposeObserver);
  54627. }
  54628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54629. },
  54630. enumerable: true,
  54631. configurable: true
  54632. });
  54633. Object.defineProperty(SpriteManager.prototype, "texture", {
  54634. get: function () {
  54635. return this._spriteTexture;
  54636. },
  54637. set: function (value) {
  54638. this._spriteTexture = value;
  54639. },
  54640. enumerable: true,
  54641. configurable: true
  54642. });
  54643. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54644. var arrayOffset = index * 16;
  54645. if (offsetX === 0)
  54646. offsetX = this._epsilon;
  54647. else if (offsetX === 1)
  54648. offsetX = 1 - this._epsilon;
  54649. if (offsetY === 0)
  54650. offsetY = this._epsilon;
  54651. else if (offsetY === 1)
  54652. offsetY = 1 - this._epsilon;
  54653. this._vertexData[arrayOffset] = sprite.position.x;
  54654. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54655. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54656. this._vertexData[arrayOffset + 3] = sprite.angle;
  54657. this._vertexData[arrayOffset + 4] = sprite.width;
  54658. this._vertexData[arrayOffset + 5] = sprite.height;
  54659. this._vertexData[arrayOffset + 6] = offsetX;
  54660. this._vertexData[arrayOffset + 7] = offsetY;
  54661. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54662. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54663. var offset = (sprite.cellIndex / rowSize) >> 0;
  54664. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54665. this._vertexData[arrayOffset + 11] = offset;
  54666. // Color
  54667. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54668. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54669. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54670. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54671. };
  54672. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54673. var count = Math.min(this._capacity, this.sprites.length);
  54674. var min = BABYLON.Vector3.Zero();
  54675. var max = BABYLON.Vector3.Zero();
  54676. var distance = Number.MAX_VALUE;
  54677. var currentSprite = null;
  54678. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54679. var cameraView = camera.getViewMatrix();
  54680. for (var index = 0; index < count; index++) {
  54681. var sprite = this.sprites[index];
  54682. if (!sprite) {
  54683. continue;
  54684. }
  54685. if (predicate) {
  54686. if (!predicate(sprite)) {
  54687. continue;
  54688. }
  54689. }
  54690. else if (!sprite.isPickable) {
  54691. continue;
  54692. }
  54693. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54694. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54695. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54696. if (ray.intersectsBoxMinMax(min, max)) {
  54697. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54698. if (distance > currentDistance) {
  54699. distance = currentDistance;
  54700. currentSprite = sprite;
  54701. if (fastCheck) {
  54702. break;
  54703. }
  54704. }
  54705. }
  54706. }
  54707. if (currentSprite) {
  54708. var result = new BABYLON.PickingInfo();
  54709. result.hit = true;
  54710. result.pickedSprite = currentSprite;
  54711. result.distance = distance;
  54712. return result;
  54713. }
  54714. return null;
  54715. };
  54716. SpriteManager.prototype.render = function () {
  54717. // Check
  54718. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54719. return;
  54720. var engine = this._scene.getEngine();
  54721. var baseSize = this._spriteTexture.getBaseSize();
  54722. // Sprites
  54723. var deltaTime = engine.getDeltaTime();
  54724. var max = Math.min(this._capacity, this.sprites.length);
  54725. var rowSize = baseSize.width / this.cellWidth;
  54726. var offset = 0;
  54727. for (var index = 0; index < max; index++) {
  54728. var sprite = this.sprites[index];
  54729. if (!sprite) {
  54730. continue;
  54731. }
  54732. sprite._animate(deltaTime);
  54733. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54734. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54735. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54736. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54737. }
  54738. this._buffer.update(this._vertexData);
  54739. // Render
  54740. var effect = this._effectBase;
  54741. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54742. effect = this._effectFog;
  54743. }
  54744. engine.enableEffect(effect);
  54745. var viewMatrix = this._scene.getViewMatrix();
  54746. effect.setTexture("diffuseSampler", this._spriteTexture);
  54747. effect.setMatrix("view", viewMatrix);
  54748. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54749. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54750. // Fog
  54751. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54752. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54753. effect.setColor3("vFogColor", this._scene.fogColor);
  54754. }
  54755. // VBOs
  54756. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54757. // Draw order
  54758. engine.setDepthFunctionToLessOrEqual();
  54759. effect.setBool("alphaTest", true);
  54760. engine.setColorWrite(false);
  54761. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54762. engine.setColorWrite(true);
  54763. effect.setBool("alphaTest", false);
  54764. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54765. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54766. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54767. };
  54768. SpriteManager.prototype.dispose = function () {
  54769. if (this._buffer) {
  54770. this._buffer.dispose();
  54771. this._buffer = null;
  54772. }
  54773. if (this._indexBuffer) {
  54774. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54775. this._indexBuffer = null;
  54776. }
  54777. if (this._spriteTexture) {
  54778. this._spriteTexture.dispose();
  54779. this._spriteTexture = null;
  54780. }
  54781. // Remove from scene
  54782. var index = this._scene.spriteManagers.indexOf(this);
  54783. this._scene.spriteManagers.splice(index, 1);
  54784. // Callback
  54785. this.onDisposeObservable.notifyObservers(this);
  54786. this.onDisposeObservable.clear();
  54787. };
  54788. return SpriteManager;
  54789. }());
  54790. BABYLON.SpriteManager = SpriteManager;
  54791. })(BABYLON || (BABYLON = {}));
  54792. //# sourceMappingURL=babylon.spriteManager.js.map
  54793. var BABYLON;
  54794. (function (BABYLON) {
  54795. var Sprite = /** @class */ (function () {
  54796. function Sprite(name, manager) {
  54797. this.name = name;
  54798. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54799. this.width = 1.0;
  54800. this.height = 1.0;
  54801. this.angle = 0;
  54802. this.cellIndex = 0;
  54803. this.invertU = 0;
  54804. this.invertV = 0;
  54805. this.animations = new Array();
  54806. this.isPickable = false;
  54807. this._animationStarted = false;
  54808. this._loopAnimation = false;
  54809. this._fromIndex = 0;
  54810. this._toIndex = 0;
  54811. this._delay = 0;
  54812. this._direction = 1;
  54813. this._time = 0;
  54814. this._manager = manager;
  54815. this._manager.sprites.push(this);
  54816. this.position = BABYLON.Vector3.Zero();
  54817. }
  54818. Object.defineProperty(Sprite.prototype, "size", {
  54819. get: function () {
  54820. return this.width;
  54821. },
  54822. set: function (value) {
  54823. this.width = value;
  54824. this.height = value;
  54825. },
  54826. enumerable: true,
  54827. configurable: true
  54828. });
  54829. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54830. this._fromIndex = from;
  54831. this._toIndex = to;
  54832. this._loopAnimation = loop;
  54833. this._delay = delay;
  54834. this._animationStarted = true;
  54835. this._direction = from < to ? 1 : -1;
  54836. this.cellIndex = from;
  54837. this._time = 0;
  54838. this._onAnimationEnd = onAnimationEnd;
  54839. };
  54840. Sprite.prototype.stopAnimation = function () {
  54841. this._animationStarted = false;
  54842. };
  54843. Sprite.prototype._animate = function (deltaTime) {
  54844. if (!this._animationStarted)
  54845. return;
  54846. this._time += deltaTime;
  54847. if (this._time > this._delay) {
  54848. this._time = this._time % this._delay;
  54849. this.cellIndex += this._direction;
  54850. if (this.cellIndex > this._toIndex) {
  54851. if (this._loopAnimation) {
  54852. this.cellIndex = this._fromIndex;
  54853. }
  54854. else {
  54855. this.cellIndex = this._toIndex;
  54856. this._animationStarted = false;
  54857. if (this._onAnimationEnd) {
  54858. this._onAnimationEnd();
  54859. }
  54860. if (this.disposeWhenFinishedAnimating) {
  54861. this.dispose();
  54862. }
  54863. }
  54864. }
  54865. }
  54866. };
  54867. Sprite.prototype.dispose = function () {
  54868. for (var i = 0; i < this._manager.sprites.length; i++) {
  54869. if (this._manager.sprites[i] == this) {
  54870. this._manager.sprites.splice(i, 1);
  54871. }
  54872. }
  54873. };
  54874. return Sprite;
  54875. }());
  54876. BABYLON.Sprite = Sprite;
  54877. })(BABYLON || (BABYLON = {}));
  54878. //# sourceMappingURL=babylon.sprite.js.map
  54879. var BABYLON;
  54880. (function (BABYLON) {
  54881. var IntersectionInfo = /** @class */ (function () {
  54882. function IntersectionInfo(bu, bv, distance) {
  54883. this.bu = bu;
  54884. this.bv = bv;
  54885. this.distance = distance;
  54886. this.faceId = 0;
  54887. this.subMeshId = 0;
  54888. }
  54889. return IntersectionInfo;
  54890. }());
  54891. BABYLON.IntersectionInfo = IntersectionInfo;
  54892. /**
  54893. * Information about the result of picking within a scene
  54894. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54895. */
  54896. var PickingInfo = /** @class */ (function () {
  54897. function PickingInfo() {
  54898. /**
  54899. * If the pick collided with an object
  54900. */
  54901. this.hit = false;
  54902. /**
  54903. * Distance away where the pick collided
  54904. */
  54905. this.distance = 0;
  54906. /**
  54907. * The location of pick collision
  54908. */
  54909. this.pickedPoint = null;
  54910. /**
  54911. * The mesh corrisponding the the pick collision
  54912. */
  54913. this.pickedMesh = null;
  54914. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54915. this.bu = 0;
  54916. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54917. this.bv = 0;
  54918. /** The id of the face on the mesh that was picked */
  54919. this.faceId = -1;
  54920. /** Id of the the submesh that was picked */
  54921. this.subMeshId = 0;
  54922. /** If a sprite was picked, this will be the sprite the pick collided with */
  54923. this.pickedSprite = null;
  54924. /**
  54925. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54926. */
  54927. this.originMesh = null;
  54928. /**
  54929. * The ray that was used to perform the picking.
  54930. */
  54931. this.ray = null;
  54932. }
  54933. /**
  54934. * Gets the normal corrispodning to the face the pick collided with
  54935. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54936. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54937. * @returns The normal corrispodning to the face the pick collided with
  54938. */
  54939. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54940. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54941. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54942. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54943. return null;
  54944. }
  54945. var indices = this.pickedMesh.getIndices();
  54946. if (!indices) {
  54947. return null;
  54948. }
  54949. var result;
  54950. if (useVerticesNormals) {
  54951. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54952. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54953. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54954. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54955. normal0 = normal0.scale(this.bu);
  54956. normal1 = normal1.scale(this.bv);
  54957. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54958. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54959. }
  54960. else {
  54961. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54962. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54963. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54964. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54965. var p1p2 = vertex1.subtract(vertex2);
  54966. var p3p2 = vertex3.subtract(vertex2);
  54967. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54968. }
  54969. if (useWorldCoordinates) {
  54970. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54971. }
  54972. return BABYLON.Vector3.Normalize(result);
  54973. };
  54974. /**
  54975. * Gets the texture coordinates of where the pick occured
  54976. * @returns the vector containing the coordnates of the texture
  54977. */
  54978. PickingInfo.prototype.getTextureCoordinates = function () {
  54979. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54980. return null;
  54981. }
  54982. var indices = this.pickedMesh.getIndices();
  54983. if (!indices) {
  54984. return null;
  54985. }
  54986. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54987. if (!uvs) {
  54988. return null;
  54989. }
  54990. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54991. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54992. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54993. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54994. uv1 = uv1.scale(this.bu);
  54995. uv2 = uv2.scale(this.bv);
  54996. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54997. };
  54998. return PickingInfo;
  54999. }());
  55000. BABYLON.PickingInfo = PickingInfo;
  55001. })(BABYLON || (BABYLON = {}));
  55002. //# sourceMappingURL=babylon.pickingInfo.js.map
  55003. var BABYLON;
  55004. (function (BABYLON) {
  55005. var Ray = /** @class */ (function () {
  55006. function Ray(origin, direction, length) {
  55007. if (length === void 0) { length = Number.MAX_VALUE; }
  55008. this.origin = origin;
  55009. this.direction = direction;
  55010. this.length = length;
  55011. }
  55012. // Methods
  55013. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55014. var d = 0.0;
  55015. var maxValue = Number.MAX_VALUE;
  55016. var inv;
  55017. var min;
  55018. var max;
  55019. var temp;
  55020. if (Math.abs(this.direction.x) < 0.0000001) {
  55021. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55022. return false;
  55023. }
  55024. }
  55025. else {
  55026. inv = 1.0 / this.direction.x;
  55027. min = (minimum.x - this.origin.x) * inv;
  55028. max = (maximum.x - this.origin.x) * inv;
  55029. if (max === -Infinity) {
  55030. max = Infinity;
  55031. }
  55032. if (min > max) {
  55033. temp = min;
  55034. min = max;
  55035. max = temp;
  55036. }
  55037. d = Math.max(min, d);
  55038. maxValue = Math.min(max, maxValue);
  55039. if (d > maxValue) {
  55040. return false;
  55041. }
  55042. }
  55043. if (Math.abs(this.direction.y) < 0.0000001) {
  55044. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55045. return false;
  55046. }
  55047. }
  55048. else {
  55049. inv = 1.0 / this.direction.y;
  55050. min = (minimum.y - this.origin.y) * inv;
  55051. max = (maximum.y - this.origin.y) * inv;
  55052. if (max === -Infinity) {
  55053. max = Infinity;
  55054. }
  55055. if (min > max) {
  55056. temp = min;
  55057. min = max;
  55058. max = temp;
  55059. }
  55060. d = Math.max(min, d);
  55061. maxValue = Math.min(max, maxValue);
  55062. if (d > maxValue) {
  55063. return false;
  55064. }
  55065. }
  55066. if (Math.abs(this.direction.z) < 0.0000001) {
  55067. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55068. return false;
  55069. }
  55070. }
  55071. else {
  55072. inv = 1.0 / this.direction.z;
  55073. min = (minimum.z - this.origin.z) * inv;
  55074. max = (maximum.z - this.origin.z) * inv;
  55075. if (max === -Infinity) {
  55076. max = Infinity;
  55077. }
  55078. if (min > max) {
  55079. temp = min;
  55080. min = max;
  55081. max = temp;
  55082. }
  55083. d = Math.max(min, d);
  55084. maxValue = Math.min(max, maxValue);
  55085. if (d > maxValue) {
  55086. return false;
  55087. }
  55088. }
  55089. return true;
  55090. };
  55091. Ray.prototype.intersectsBox = function (box) {
  55092. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55093. };
  55094. Ray.prototype.intersectsSphere = function (sphere) {
  55095. var x = sphere.center.x - this.origin.x;
  55096. var y = sphere.center.y - this.origin.y;
  55097. var z = sphere.center.z - this.origin.z;
  55098. var pyth = (x * x) + (y * y) + (z * z);
  55099. var rr = sphere.radius * sphere.radius;
  55100. if (pyth <= rr) {
  55101. return true;
  55102. }
  55103. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55104. if (dot < 0.0) {
  55105. return false;
  55106. }
  55107. var temp = pyth - (dot * dot);
  55108. return temp <= rr;
  55109. };
  55110. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55111. if (!this._edge1) {
  55112. this._edge1 = BABYLON.Vector3.Zero();
  55113. this._edge2 = BABYLON.Vector3.Zero();
  55114. this._pvec = BABYLON.Vector3.Zero();
  55115. this._tvec = BABYLON.Vector3.Zero();
  55116. this._qvec = BABYLON.Vector3.Zero();
  55117. }
  55118. vertex1.subtractToRef(vertex0, this._edge1);
  55119. vertex2.subtractToRef(vertex0, this._edge2);
  55120. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55121. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55122. if (det === 0) {
  55123. return null;
  55124. }
  55125. var invdet = 1 / det;
  55126. this.origin.subtractToRef(vertex0, this._tvec);
  55127. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55128. if (bu < 0 || bu > 1.0) {
  55129. return null;
  55130. }
  55131. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55132. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55133. if (bv < 0 || bu + bv > 1.0) {
  55134. return null;
  55135. }
  55136. //check if the distance is longer than the predefined length.
  55137. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55138. if (distance > this.length) {
  55139. return null;
  55140. }
  55141. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55142. };
  55143. Ray.prototype.intersectsPlane = function (plane) {
  55144. var distance;
  55145. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55146. if (Math.abs(result1) < 9.99999997475243E-07) {
  55147. return null;
  55148. }
  55149. else {
  55150. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55151. distance = (-plane.d - result2) / result1;
  55152. if (distance < 0.0) {
  55153. if (distance < -9.99999997475243E-07) {
  55154. return null;
  55155. }
  55156. else {
  55157. return 0;
  55158. }
  55159. }
  55160. return distance;
  55161. }
  55162. };
  55163. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55164. var tm = BABYLON.Tmp.Matrix[0];
  55165. mesh.getWorldMatrix().invertToRef(tm);
  55166. if (this._tmpRay) {
  55167. Ray.TransformToRef(this, tm, this._tmpRay);
  55168. }
  55169. else {
  55170. this._tmpRay = Ray.Transform(this, tm);
  55171. }
  55172. return mesh.intersects(this._tmpRay, fastCheck);
  55173. };
  55174. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55175. if (results) {
  55176. results.length = 0;
  55177. }
  55178. else {
  55179. results = [];
  55180. }
  55181. for (var i = 0; i < meshes.length; i++) {
  55182. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55183. if (pickInfo.hit) {
  55184. results.push(pickInfo);
  55185. }
  55186. }
  55187. results.sort(this._comparePickingInfo);
  55188. return results;
  55189. };
  55190. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55191. if (pickingInfoA.distance < pickingInfoB.distance) {
  55192. return -1;
  55193. }
  55194. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55195. return 1;
  55196. }
  55197. else {
  55198. return 0;
  55199. }
  55200. };
  55201. /**
  55202. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55203. * @param sega the first point of the segment to test the intersection against
  55204. * @param segb the second point of the segment to test the intersection against
  55205. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55206. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55207. */
  55208. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55209. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55210. var u = segb.subtract(sega);
  55211. var v = rsegb.subtract(this.origin);
  55212. var w = sega.subtract(this.origin);
  55213. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55214. var b = BABYLON.Vector3.Dot(u, v);
  55215. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55216. var d = BABYLON.Vector3.Dot(u, w);
  55217. var e = BABYLON.Vector3.Dot(v, w);
  55218. var D = a * c - b * b; // always >= 0
  55219. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55220. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55221. // compute the line parameters of the two closest points
  55222. if (D < Ray.smallnum) { // the lines are almost parallel
  55223. sN = 0.0; // force using point P0 on segment S1
  55224. sD = 1.0; // to prevent possible division by 0.0 later
  55225. tN = e;
  55226. tD = c;
  55227. }
  55228. else { // get the closest points on the infinite lines
  55229. sN = (b * e - c * d);
  55230. tN = (a * e - b * d);
  55231. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55232. sN = 0.0;
  55233. tN = e;
  55234. tD = c;
  55235. }
  55236. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55237. sN = sD;
  55238. tN = e + b;
  55239. tD = c;
  55240. }
  55241. }
  55242. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55243. tN = 0.0;
  55244. // recompute sc for this edge
  55245. if (-d < 0.0) {
  55246. sN = 0.0;
  55247. }
  55248. else if (-d > a)
  55249. sN = sD;
  55250. else {
  55251. sN = -d;
  55252. sD = a;
  55253. }
  55254. }
  55255. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55256. tN = tD;
  55257. // recompute sc for this edge
  55258. if ((-d + b) < 0.0) {
  55259. sN = 0;
  55260. }
  55261. else if ((-d + b) > a) {
  55262. sN = sD;
  55263. }
  55264. else {
  55265. sN = (-d + b);
  55266. sD = a;
  55267. }
  55268. }
  55269. // finally do the division to get sc and tc
  55270. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55271. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55272. // get the difference of the two closest points
  55273. var qtc = v.multiplyByFloats(tc, tc, tc);
  55274. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55275. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55276. if (isIntersected) {
  55277. return qtc.length();
  55278. }
  55279. return -1;
  55280. };
  55281. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55282. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55283. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55284. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55285. this.direction.normalize();
  55286. return this;
  55287. };
  55288. // Statics
  55289. Ray.Zero = function () {
  55290. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55291. };
  55292. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55293. var result = Ray.Zero();
  55294. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55295. };
  55296. /**
  55297. * 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
  55298. * transformed to the given world matrix.
  55299. * @param origin The origin point
  55300. * @param end The end point
  55301. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55302. */
  55303. Ray.CreateNewFromTo = function (origin, end, world) {
  55304. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55305. var direction = end.subtract(origin);
  55306. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55307. direction.normalize();
  55308. return Ray.Transform(new Ray(origin, direction, length), world);
  55309. };
  55310. Ray.Transform = function (ray, matrix) {
  55311. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55312. Ray.TransformToRef(ray, matrix, result);
  55313. return result;
  55314. };
  55315. Ray.TransformToRef = function (ray, matrix, result) {
  55316. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55317. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55318. result.length = ray.length;
  55319. var dir = result.direction;
  55320. var len = dir.length();
  55321. if (!(len === 0 || len === 1)) {
  55322. var num = 1.0 / len;
  55323. dir.x *= num;
  55324. dir.y *= num;
  55325. dir.z *= num;
  55326. result.length *= len;
  55327. }
  55328. };
  55329. Ray.smallnum = 0.00000001;
  55330. Ray.rayl = 10e8;
  55331. return Ray;
  55332. }());
  55333. BABYLON.Ray = Ray;
  55334. })(BABYLON || (BABYLON = {}));
  55335. //# sourceMappingURL=babylon.ray.js.map
  55336. var BABYLON;
  55337. (function (BABYLON) {
  55338. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55339. if (boxMin.x > sphereCenter.x + sphereRadius)
  55340. return false;
  55341. if (sphereCenter.x - sphereRadius > boxMax.x)
  55342. return false;
  55343. if (boxMin.y > sphereCenter.y + sphereRadius)
  55344. return false;
  55345. if (sphereCenter.y - sphereRadius > boxMax.y)
  55346. return false;
  55347. if (boxMin.z > sphereCenter.z + sphereRadius)
  55348. return false;
  55349. if (sphereCenter.z - sphereRadius > boxMax.z)
  55350. return false;
  55351. return true;
  55352. };
  55353. var getLowestRoot = (function () {
  55354. var result = { root: 0, found: false };
  55355. return function (a, b, c, maxR) {
  55356. result.root = 0;
  55357. result.found = false;
  55358. var determinant = b * b - 4.0 * a * c;
  55359. if (determinant < 0)
  55360. return result;
  55361. var sqrtD = Math.sqrt(determinant);
  55362. var r1 = (-b - sqrtD) / (2.0 * a);
  55363. var r2 = (-b + sqrtD) / (2.0 * a);
  55364. if (r1 > r2) {
  55365. var temp = r2;
  55366. r2 = r1;
  55367. r1 = temp;
  55368. }
  55369. if (r1 > 0 && r1 < maxR) {
  55370. result.root = r1;
  55371. result.found = true;
  55372. return result;
  55373. }
  55374. if (r2 > 0 && r2 < maxR) {
  55375. result.root = r2;
  55376. result.found = true;
  55377. return result;
  55378. }
  55379. return result;
  55380. };
  55381. })();
  55382. var Collider = /** @class */ (function () {
  55383. function Collider() {
  55384. this._collisionPoint = BABYLON.Vector3.Zero();
  55385. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55386. this._tempVector = BABYLON.Vector3.Zero();
  55387. this._tempVector2 = BABYLON.Vector3.Zero();
  55388. this._tempVector3 = BABYLON.Vector3.Zero();
  55389. this._tempVector4 = BABYLON.Vector3.Zero();
  55390. this._edge = BABYLON.Vector3.Zero();
  55391. this._baseToVertex = BABYLON.Vector3.Zero();
  55392. this._destinationPoint = BABYLON.Vector3.Zero();
  55393. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55394. this._displacementVector = BABYLON.Vector3.Zero();
  55395. this._radius = BABYLON.Vector3.One();
  55396. this._retry = 0;
  55397. this._basePointWorld = BABYLON.Vector3.Zero();
  55398. this._velocityWorld = BABYLON.Vector3.Zero();
  55399. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55400. this._collisionMask = -1;
  55401. }
  55402. Object.defineProperty(Collider.prototype, "collisionMask", {
  55403. get: function () {
  55404. return this._collisionMask;
  55405. },
  55406. set: function (mask) {
  55407. this._collisionMask = !isNaN(mask) ? mask : -1;
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55413. /**
  55414. * Gets the plane normal used to compute the sliding response (in local space)
  55415. */
  55416. get: function () {
  55417. return this._slidePlaneNormal;
  55418. },
  55419. enumerable: true,
  55420. configurable: true
  55421. });
  55422. // Methods
  55423. Collider.prototype._initialize = function (source, dir, e) {
  55424. this._velocity = dir;
  55425. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55426. this._basePoint = source;
  55427. source.multiplyToRef(this._radius, this._basePointWorld);
  55428. dir.multiplyToRef(this._radius, this._velocityWorld);
  55429. this._velocityWorldLength = this._velocityWorld.length();
  55430. this._epsilon = e;
  55431. this.collisionFound = false;
  55432. };
  55433. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55434. pa.subtractToRef(point, this._tempVector);
  55435. pb.subtractToRef(point, this._tempVector2);
  55436. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55437. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55438. if (d < 0)
  55439. return false;
  55440. pc.subtractToRef(point, this._tempVector3);
  55441. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55442. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55443. if (d < 0)
  55444. return false;
  55445. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55446. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55447. return d >= 0;
  55448. };
  55449. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55450. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55451. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55452. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55453. return false;
  55454. }
  55455. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55456. return false;
  55457. return true;
  55458. };
  55459. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55460. var t0;
  55461. var embeddedInPlane = false;
  55462. //defensive programming, actually not needed.
  55463. if (!trianglePlaneArray) {
  55464. trianglePlaneArray = [];
  55465. }
  55466. if (!trianglePlaneArray[faceIndex]) {
  55467. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55468. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55469. }
  55470. var trianglePlane = trianglePlaneArray[faceIndex];
  55471. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55472. return;
  55473. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55474. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55475. if (normalDotVelocity == 0) {
  55476. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55477. return;
  55478. embeddedInPlane = true;
  55479. t0 = 0;
  55480. }
  55481. else {
  55482. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55483. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55484. if (t0 > t1) {
  55485. var temp = t1;
  55486. t1 = t0;
  55487. t0 = temp;
  55488. }
  55489. if (t0 > 1.0 || t1 < 0.0)
  55490. return;
  55491. if (t0 < 0)
  55492. t0 = 0;
  55493. if (t0 > 1.0)
  55494. t0 = 1.0;
  55495. }
  55496. this._collisionPoint.copyFromFloats(0, 0, 0);
  55497. var found = false;
  55498. var t = 1.0;
  55499. if (!embeddedInPlane) {
  55500. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55501. this._velocity.scaleToRef(t0, this._tempVector);
  55502. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55503. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55504. found = true;
  55505. t = t0;
  55506. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55507. }
  55508. }
  55509. if (!found) {
  55510. var velocitySquaredLength = this._velocity.lengthSquared();
  55511. var a = velocitySquaredLength;
  55512. this._basePoint.subtractToRef(p1, this._tempVector);
  55513. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55514. var c = this._tempVector.lengthSquared() - 1.0;
  55515. var lowestRoot = getLowestRoot(a, b, c, t);
  55516. if (lowestRoot.found) {
  55517. t = lowestRoot.root;
  55518. found = true;
  55519. this._collisionPoint.copyFrom(p1);
  55520. }
  55521. this._basePoint.subtractToRef(p2, this._tempVector);
  55522. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55523. c = this._tempVector.lengthSquared() - 1.0;
  55524. lowestRoot = getLowestRoot(a, b, c, t);
  55525. if (lowestRoot.found) {
  55526. t = lowestRoot.root;
  55527. found = true;
  55528. this._collisionPoint.copyFrom(p2);
  55529. }
  55530. this._basePoint.subtractToRef(p3, this._tempVector);
  55531. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55532. c = this._tempVector.lengthSquared() - 1.0;
  55533. lowestRoot = getLowestRoot(a, b, c, t);
  55534. if (lowestRoot.found) {
  55535. t = lowestRoot.root;
  55536. found = true;
  55537. this._collisionPoint.copyFrom(p3);
  55538. }
  55539. p2.subtractToRef(p1, this._edge);
  55540. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55541. var edgeSquaredLength = this._edge.lengthSquared();
  55542. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55543. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55544. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55545. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55546. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55547. lowestRoot = getLowestRoot(a, b, c, t);
  55548. if (lowestRoot.found) {
  55549. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55550. if (f >= 0.0 && f <= 1.0) {
  55551. t = lowestRoot.root;
  55552. found = true;
  55553. this._edge.scaleInPlace(f);
  55554. p1.addToRef(this._edge, this._collisionPoint);
  55555. }
  55556. }
  55557. p3.subtractToRef(p2, this._edge);
  55558. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55559. edgeSquaredLength = this._edge.lengthSquared();
  55560. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55561. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55562. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55563. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55564. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55565. lowestRoot = getLowestRoot(a, b, c, t);
  55566. if (lowestRoot.found) {
  55567. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55568. if (f >= 0.0 && f <= 1.0) {
  55569. t = lowestRoot.root;
  55570. found = true;
  55571. this._edge.scaleInPlace(f);
  55572. p2.addToRef(this._edge, this._collisionPoint);
  55573. }
  55574. }
  55575. p1.subtractToRef(p3, this._edge);
  55576. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55577. edgeSquaredLength = this._edge.lengthSquared();
  55578. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55579. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55580. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55581. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55582. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55583. lowestRoot = getLowestRoot(a, b, c, t);
  55584. if (lowestRoot.found) {
  55585. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55586. if (f >= 0.0 && f <= 1.0) {
  55587. t = lowestRoot.root;
  55588. found = true;
  55589. this._edge.scaleInPlace(f);
  55590. p3.addToRef(this._edge, this._collisionPoint);
  55591. }
  55592. }
  55593. }
  55594. if (found) {
  55595. var distToCollision = t * this._velocity.length();
  55596. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55597. if (!this.intersectionPoint) {
  55598. this.intersectionPoint = this._collisionPoint.clone();
  55599. }
  55600. else {
  55601. this.intersectionPoint.copyFrom(this._collisionPoint);
  55602. }
  55603. this._nearestDistance = distToCollision;
  55604. this.collisionFound = true;
  55605. }
  55606. }
  55607. };
  55608. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55609. for (var i = indexStart; i < indexEnd; i += 3) {
  55610. var p1 = pts[indices[i] - decal];
  55611. var p2 = pts[indices[i + 1] - decal];
  55612. var p3 = pts[indices[i + 2] - decal];
  55613. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55614. }
  55615. };
  55616. Collider.prototype._getResponse = function (pos, vel) {
  55617. pos.addToRef(vel, this._destinationPoint);
  55618. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55619. this._basePoint.addToRef(vel, pos);
  55620. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55621. this._slidePlaneNormal.normalize();
  55622. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55623. pos.addInPlace(this._displacementVector);
  55624. this.intersectionPoint.addInPlace(this._displacementVector);
  55625. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55626. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55627. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55628. };
  55629. return Collider;
  55630. }());
  55631. BABYLON.Collider = Collider;
  55632. })(BABYLON || (BABYLON = {}));
  55633. //# sourceMappingURL=babylon.collider.js.map
  55634. var BABYLON;
  55635. (function (BABYLON) {
  55636. //WebWorker code will be inserted to this variable.
  55637. BABYLON.CollisionWorker = "";
  55638. /** Defines supported task for worker process */
  55639. var WorkerTaskType;
  55640. (function (WorkerTaskType) {
  55641. /** Initialization */
  55642. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55643. /** Update of geometry */
  55644. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55645. /** Evaluate collision */
  55646. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55647. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55648. /** Defines kind of replies returned by worker */
  55649. var WorkerReplyType;
  55650. (function (WorkerReplyType) {
  55651. /** Success */
  55652. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55653. /** Unkown error */
  55654. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55655. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55656. var CollisionCoordinatorWorker = /** @class */ (function () {
  55657. function CollisionCoordinatorWorker() {
  55658. var _this = this;
  55659. this._scaledPosition = BABYLON.Vector3.Zero();
  55660. this._scaledVelocity = BABYLON.Vector3.Zero();
  55661. this.onMeshUpdated = function (transformNode) {
  55662. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55663. };
  55664. this.onGeometryUpdated = function (geometry) {
  55665. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55666. };
  55667. this._afterRender = function () {
  55668. if (!_this._init)
  55669. return;
  55670. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55671. return;
  55672. }
  55673. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55674. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55675. if (_this._runningUpdated > 4) {
  55676. return;
  55677. }
  55678. ++_this._runningUpdated;
  55679. var payload = {
  55680. updatedMeshes: _this._addUpdateMeshesList,
  55681. updatedGeometries: _this._addUpdateGeometriesList,
  55682. removedGeometries: _this._toRemoveGeometryArray,
  55683. removedMeshes: _this._toRemoveMeshesArray
  55684. };
  55685. var message = {
  55686. payload: payload,
  55687. taskType: WorkerTaskType.UPDATE
  55688. };
  55689. var serializable = [];
  55690. for (var id in payload.updatedGeometries) {
  55691. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55692. //prepare transferables
  55693. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55694. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55695. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55696. }
  55697. }
  55698. _this._worker.postMessage(message, serializable);
  55699. _this._addUpdateMeshesList = {};
  55700. _this._addUpdateGeometriesList = {};
  55701. _this._toRemoveGeometryArray = [];
  55702. _this._toRemoveMeshesArray = [];
  55703. };
  55704. this._onMessageFromWorker = function (e) {
  55705. var returnData = e.data;
  55706. if (returnData.error != WorkerReplyType.SUCCESS) {
  55707. //TODO what errors can be returned from the worker?
  55708. BABYLON.Tools.Warn("error returned from worker!");
  55709. return;
  55710. }
  55711. switch (returnData.taskType) {
  55712. case WorkerTaskType.INIT:
  55713. _this._init = true;
  55714. //Update the worked with ALL of the scene's current state
  55715. _this._scene.meshes.forEach(function (mesh) {
  55716. _this.onMeshAdded(mesh);
  55717. });
  55718. _this._scene.getGeometries().forEach(function (geometry) {
  55719. _this.onGeometryAdded(geometry);
  55720. });
  55721. break;
  55722. case WorkerTaskType.UPDATE:
  55723. _this._runningUpdated--;
  55724. break;
  55725. case WorkerTaskType.COLLIDE:
  55726. var returnPayload = returnData.payload;
  55727. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55728. return;
  55729. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55730. if (callback) {
  55731. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55732. if (mesh) {
  55733. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55734. }
  55735. }
  55736. //cleanup
  55737. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55738. break;
  55739. }
  55740. };
  55741. this._collisionsCallbackArray = [];
  55742. this._init = false;
  55743. this._runningUpdated = 0;
  55744. this._addUpdateMeshesList = {};
  55745. this._addUpdateGeometriesList = {};
  55746. this._toRemoveGeometryArray = [];
  55747. this._toRemoveMeshesArray = [];
  55748. }
  55749. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55750. if (!this._init)
  55751. return;
  55752. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55753. return;
  55754. position.divideToRef(collider._radius, this._scaledPosition);
  55755. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55756. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55757. var payload = {
  55758. collider: {
  55759. position: this._scaledPosition.asArray(),
  55760. velocity: this._scaledVelocity.asArray(),
  55761. radius: collider._radius.asArray()
  55762. },
  55763. collisionId: collisionIndex,
  55764. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55765. maximumRetry: maximumRetry
  55766. };
  55767. var message = {
  55768. payload: payload,
  55769. taskType: WorkerTaskType.COLLIDE
  55770. };
  55771. this._worker.postMessage(message);
  55772. };
  55773. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55774. this._scene = scene;
  55775. this._scene.registerAfterRender(this._afterRender);
  55776. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55777. this._worker = new Worker(workerUrl);
  55778. this._worker.onmessage = this._onMessageFromWorker;
  55779. var message = {
  55780. payload: {},
  55781. taskType: WorkerTaskType.INIT
  55782. };
  55783. this._worker.postMessage(message);
  55784. };
  55785. CollisionCoordinatorWorker.prototype.destroy = function () {
  55786. this._scene.unregisterAfterRender(this._afterRender);
  55787. this._worker.terminate();
  55788. };
  55789. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55790. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55791. this.onMeshUpdated(mesh);
  55792. };
  55793. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55794. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55795. };
  55796. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55797. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55798. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55799. this.onGeometryUpdated(geometry);
  55800. };
  55801. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55802. this._toRemoveGeometryArray.push(geometry.id);
  55803. };
  55804. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55805. var submeshes = [];
  55806. if (mesh.subMeshes) {
  55807. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55808. var boundingInfo = sm.getBoundingInfo();
  55809. return {
  55810. position: idx,
  55811. verticesStart: sm.verticesStart,
  55812. verticesCount: sm.verticesCount,
  55813. indexStart: sm.indexStart,
  55814. indexCount: sm.indexCount,
  55815. hasMaterial: !!sm.getMaterial(),
  55816. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55817. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55818. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55819. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55820. };
  55821. });
  55822. }
  55823. var geometryId = null;
  55824. if (mesh instanceof BABYLON.Mesh) {
  55825. var geometry = mesh.geometry;
  55826. geometryId = geometry ? geometry.id : null;
  55827. }
  55828. else if (mesh instanceof BABYLON.InstancedMesh) {
  55829. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55830. geometryId = geometry ? geometry.id : null;
  55831. }
  55832. var boundingInfo = mesh.getBoundingInfo();
  55833. return {
  55834. uniqueId: mesh.uniqueId,
  55835. id: mesh.id,
  55836. name: mesh.name,
  55837. geometryId: geometryId,
  55838. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55839. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55840. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55841. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55842. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55843. subMeshes: submeshes,
  55844. checkCollisions: mesh.checkCollisions
  55845. };
  55846. };
  55847. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55848. return {
  55849. id: geometry.id,
  55850. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55851. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55852. indices: new Uint32Array(geometry.getIndices() || []),
  55853. };
  55854. };
  55855. return CollisionCoordinatorWorker;
  55856. }());
  55857. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55858. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55859. function CollisionCoordinatorLegacy() {
  55860. this._scaledPosition = BABYLON.Vector3.Zero();
  55861. this._scaledVelocity = BABYLON.Vector3.Zero();
  55862. this._finalPosition = BABYLON.Vector3.Zero();
  55863. }
  55864. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55865. position.divideToRef(collider._radius, this._scaledPosition);
  55866. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55867. collider.collidedMesh = null;
  55868. collider._retry = 0;
  55869. collider._initialVelocity = this._scaledVelocity;
  55870. collider._initialPosition = this._scaledPosition;
  55871. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55872. this._finalPosition.multiplyInPlace(collider._radius);
  55873. //run the callback
  55874. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55875. };
  55876. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55877. this._scene = scene;
  55878. };
  55879. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55880. //Legacy need no destruction method.
  55881. };
  55882. //No update in legacy mode
  55883. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55884. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55885. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55886. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55887. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55888. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55889. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55890. if (excludedMesh === void 0) { excludedMesh = null; }
  55891. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55892. if (collider._retry >= maximumRetry) {
  55893. finalPosition.copyFrom(position);
  55894. return;
  55895. }
  55896. // Check if this is a mesh else camera or -1
  55897. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55898. collider._initialize(position, velocity, closeDistance);
  55899. // Check all meshes
  55900. for (var index = 0; index < this._scene.meshes.length; index++) {
  55901. var mesh = this._scene.meshes[index];
  55902. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55903. mesh._checkCollision(collider);
  55904. }
  55905. }
  55906. if (!collider.collisionFound) {
  55907. position.addToRef(velocity, finalPosition);
  55908. return;
  55909. }
  55910. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55911. collider._getResponse(position, velocity);
  55912. }
  55913. if (velocity.length() <= closeDistance) {
  55914. finalPosition.copyFrom(position);
  55915. return;
  55916. }
  55917. collider._retry++;
  55918. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55919. };
  55920. return CollisionCoordinatorLegacy;
  55921. }());
  55922. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55923. })(BABYLON || (BABYLON = {}));
  55924. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55925. var BABYLON;
  55926. (function (BABYLON) {
  55927. /**
  55928. * A particle represents one of the element emitted by a particle system.
  55929. * This is mainly define by its coordinates, direction, velocity and age.
  55930. */
  55931. var Particle = /** @class */ (function () {
  55932. /**
  55933. * Creates a new instance Particle
  55934. * @param particleSystem the particle system the particle belongs to
  55935. */
  55936. function Particle(
  55937. /**
  55938. * particleSystem the particle system the particle belongs to.
  55939. */
  55940. particleSystem) {
  55941. this.particleSystem = particleSystem;
  55942. /**
  55943. * The world position of the particle in the scene.
  55944. */
  55945. this.position = BABYLON.Vector3.Zero();
  55946. /**
  55947. * The world direction of the particle in the scene.
  55948. */
  55949. this.direction = BABYLON.Vector3.Zero();
  55950. /**
  55951. * The color of the particle.
  55952. */
  55953. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55954. /**
  55955. * The color change of the particle per step.
  55956. */
  55957. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55958. /**
  55959. * Defines how long will the life of the particle be.
  55960. */
  55961. this.lifeTime = 1.0;
  55962. /**
  55963. * The current age of the particle.
  55964. */
  55965. this.age = 0;
  55966. /**
  55967. * The current size of the particle.
  55968. */
  55969. this.size = 0;
  55970. /**
  55971. * The current angle of the particle.
  55972. */
  55973. this.angle = 0;
  55974. /**
  55975. * Defines how fast is the angle changing.
  55976. */
  55977. this.angularSpeed = 0;
  55978. /**
  55979. * Defines the cell index used by the particle to be rendered from a sprite.
  55980. */
  55981. this.cellIndex = 0;
  55982. this._currentFrameCounter = 0;
  55983. if (!this.particleSystem.isAnimationSheetEnabled) {
  55984. return;
  55985. }
  55986. this.updateCellInfoFromSystem();
  55987. }
  55988. Particle.prototype.updateCellInfoFromSystem = function () {
  55989. this.cellIndex = this.particleSystem.startSpriteCellID;
  55990. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55991. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55992. }
  55993. else {
  55994. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55995. }
  55996. };
  55997. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55998. // (ageOffset / scaledUpdateSpeed) / available cells
  55999. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56000. this._currentFrameCounter += scaledUpdateSpeed;
  56001. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56002. this._currentFrameCounter = 0;
  56003. this.cellIndex++;
  56004. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56005. this.cellIndex = this.particleSystem.endSpriteCellID;
  56006. }
  56007. }
  56008. };
  56009. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56010. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56011. this.cellIndex++;
  56012. this._currentFrameCounter = 0;
  56013. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56014. if (this.particleSystem.spriteCellLoop) {
  56015. this.cellIndex = this.particleSystem.startSpriteCellID;
  56016. }
  56017. else {
  56018. this.cellIndex = this.particleSystem.endSpriteCellID;
  56019. }
  56020. }
  56021. }
  56022. else {
  56023. this._currentFrameCounter++;
  56024. }
  56025. };
  56026. /**
  56027. * Copy the properties of particle to another one.
  56028. * @param other the particle to copy the information to.
  56029. */
  56030. Particle.prototype.copyTo = function (other) {
  56031. other.position.copyFrom(this.position);
  56032. other.direction.copyFrom(this.direction);
  56033. other.color.copyFrom(this.color);
  56034. other.colorStep.copyFrom(this.colorStep);
  56035. other.lifeTime = this.lifeTime;
  56036. other.age = this.age;
  56037. other.size = this.size;
  56038. other.angle = this.angle;
  56039. other.angularSpeed = this.angularSpeed;
  56040. other.particleSystem = this.particleSystem;
  56041. other.cellIndex = this.cellIndex;
  56042. };
  56043. return Particle;
  56044. }());
  56045. BABYLON.Particle = Particle;
  56046. })(BABYLON || (BABYLON = {}));
  56047. //# sourceMappingURL=babylon.particle.js.map
  56048. var BABYLON;
  56049. (function (BABYLON) {
  56050. /**
  56051. * This represents a particle system in Babylon.
  56052. * 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.
  56053. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56054. * @example https://doc.babylonjs.com/babylon101/particles
  56055. */
  56056. var ParticleSystem = /** @class */ (function () {
  56057. /**
  56058. * Instantiates a particle system.
  56059. * 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.
  56060. * @param name The name of the particle system
  56061. * @param capacity The max number of particles alive at the same time
  56062. * @param scene The scene the particle system belongs to
  56063. * @param customEffect a custom effect used to change the way particles are rendered by default
  56064. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56065. * @param epsilon Offset used to render the particles
  56066. */
  56067. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56068. if (customEffect === void 0) { customEffect = null; }
  56069. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56070. if (epsilon === void 0) { epsilon = 0.01; }
  56071. var _this = this;
  56072. /**
  56073. * List of animations used by the particle system.
  56074. */
  56075. this.animations = [];
  56076. /**
  56077. * The rendering group used by the Particle system to chose when to render.
  56078. */
  56079. this.renderingGroupId = 0;
  56080. /**
  56081. * The emitter represents the Mesh or position we are attaching the particle system to.
  56082. */
  56083. this.emitter = null;
  56084. /**
  56085. * The maximum number of particles to emit per frame
  56086. */
  56087. this.emitRate = 10;
  56088. /**
  56089. * If you want to launch only a few particles at once, that can be done, as well.
  56090. */
  56091. this.manualEmitCount = -1;
  56092. /**
  56093. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56094. */
  56095. this.updateSpeed = 0.01;
  56096. /**
  56097. * The amount of time the particle system is running (depends of the overall update speed).
  56098. */
  56099. this.targetStopDuration = 0;
  56100. /**
  56101. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56102. */
  56103. this.disposeOnStop = false;
  56104. /**
  56105. * Minimum power of emitting particles.
  56106. */
  56107. this.minEmitPower = 1;
  56108. /**
  56109. * Maximum power of emitting particles.
  56110. */
  56111. this.maxEmitPower = 1;
  56112. /**
  56113. * Minimum life time of emitting particles.
  56114. */
  56115. this.minLifeTime = 1;
  56116. /**
  56117. * Maximum life time of emitting particles.
  56118. */
  56119. this.maxLifeTime = 1;
  56120. /**
  56121. * Minimum Size of emitting particles.
  56122. */
  56123. this.minSize = 1;
  56124. /**
  56125. * Maximum Size of emitting particles.
  56126. */
  56127. this.maxSize = 1;
  56128. /**
  56129. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56130. */
  56131. this.minAngularSpeed = 0;
  56132. /**
  56133. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56134. */
  56135. this.maxAngularSpeed = 0;
  56136. /**
  56137. * The layer mask we are rendering the particles through.
  56138. */
  56139. this.layerMask = 0x0FFFFFFF;
  56140. /**
  56141. * This can help using your own shader to render the particle system.
  56142. * The according effect will be created
  56143. */
  56144. this.customShader = null;
  56145. /**
  56146. * By default particle system starts as soon as they are created. This prevents the
  56147. * automatic start to happen and let you decide when to start emitting particles.
  56148. */
  56149. this.preventAutoStart = false;
  56150. /**
  56151. * Callback triggered when the particle animation is ending.
  56152. */
  56153. this.onAnimationEnd = null;
  56154. /**
  56155. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56156. */
  56157. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56158. /**
  56159. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56160. * to override the particles.
  56161. */
  56162. this.forceDepthWrite = false;
  56163. /**
  56164. * You can use gravity if you want to give an orientation to your particles.
  56165. */
  56166. this.gravity = BABYLON.Vector3.Zero();
  56167. /**
  56168. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56169. */
  56170. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56171. /**
  56172. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56173. */
  56174. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56175. /**
  56176. * Color the particle will have at the end of its lifetime.
  56177. */
  56178. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56179. /**
  56180. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56181. */
  56182. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56183. /**
  56184. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56185. */
  56186. this.spriteCellLoop = true;
  56187. /**
  56188. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56189. */
  56190. this.spriteCellChangeSpeed = 0;
  56191. /**
  56192. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56193. */
  56194. this.startSpriteCellID = 0;
  56195. /**
  56196. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56197. */
  56198. this.endSpriteCellID = 0;
  56199. /**
  56200. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56201. */
  56202. this.spriteCellWidth = 0;
  56203. /**
  56204. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56205. */
  56206. this.spriteCellHeight = 0;
  56207. /**
  56208. * An event triggered when the system is disposed.
  56209. */
  56210. this.onDisposeObservable = new BABYLON.Observable();
  56211. this._particles = new Array();
  56212. this._stockParticles = new Array();
  56213. this._newPartsExcess = 0;
  56214. this._vertexBuffers = {};
  56215. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56216. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56217. this._scaledDirection = BABYLON.Vector3.Zero();
  56218. this._scaledGravity = BABYLON.Vector3.Zero();
  56219. this._currentRenderId = -1;
  56220. this._started = false;
  56221. this._stopped = false;
  56222. this._actualFrame = 0;
  56223. this._vertexBufferSize = 11;
  56224. // start of sub system methods
  56225. /**
  56226. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56227. * Its lifetime will start back at 0.
  56228. */
  56229. this.recycleParticle = function (particle) {
  56230. var lastParticle = _this._particles.pop();
  56231. if (lastParticle !== particle) {
  56232. lastParticle.copyTo(particle);
  56233. }
  56234. _this._stockParticles.push(lastParticle);
  56235. };
  56236. this._createParticle = function () {
  56237. var particle;
  56238. if (_this._stockParticles.length !== 0) {
  56239. particle = _this._stockParticles.pop();
  56240. particle.age = 0;
  56241. particle.cellIndex = _this.startSpriteCellID;
  56242. }
  56243. else {
  56244. particle = new BABYLON.Particle(_this);
  56245. }
  56246. return particle;
  56247. };
  56248. this._emitFromParticle = function (particle) {
  56249. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56250. return;
  56251. }
  56252. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56253. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56254. subSystem._rootParticleSystem = _this;
  56255. _this.activeSubSystems.push(subSystem);
  56256. subSystem.start();
  56257. };
  56258. this._appendParticleVertexes = null;
  56259. this.id = name;
  56260. this.name = name;
  56261. this._capacity = capacity;
  56262. this._epsilon = epsilon;
  56263. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56264. if (isAnimationSheetEnabled) {
  56265. this._vertexBufferSize = 12;
  56266. }
  56267. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56268. this._customEffect = customEffect;
  56269. scene.particleSystems.push(this);
  56270. this._createIndexBuffer();
  56271. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56272. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56273. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56274. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56275. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56276. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56277. if (this._isAnimationSheetEnabled) {
  56278. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56279. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56280. }
  56281. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56282. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56283. this._vertexBuffers["options"] = options;
  56284. // Default emitter type
  56285. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56286. this.updateFunction = function (particles) {
  56287. for (var index = 0; index < particles.length; index++) {
  56288. var particle = particles[index];
  56289. particle.age += _this._scaledUpdateSpeed;
  56290. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56291. _this._emitFromParticle(particle);
  56292. _this.recycleParticle(particle);
  56293. index--;
  56294. continue;
  56295. }
  56296. else {
  56297. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56298. particle.color.addInPlace(_this._scaledColorStep);
  56299. if (particle.color.a < 0)
  56300. particle.color.a = 0;
  56301. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56302. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56303. particle.position.addInPlace(_this._scaledDirection);
  56304. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56305. particle.direction.addInPlace(_this._scaledGravity);
  56306. if (_this._isAnimationSheetEnabled) {
  56307. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56308. }
  56309. }
  56310. }
  56311. };
  56312. }
  56313. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56314. /**
  56315. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56316. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56317. */
  56318. get: function () {
  56319. if (this.particleEmitterType.direction1) {
  56320. return this.particleEmitterType.direction1;
  56321. }
  56322. return BABYLON.Vector3.Zero();
  56323. },
  56324. set: function (value) {
  56325. if (this.particleEmitterType.direction1) {
  56326. this.particleEmitterType.direction1 = value;
  56327. }
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56333. /**
  56334. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56335. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56336. */
  56337. get: function () {
  56338. if (this.particleEmitterType.direction2) {
  56339. return this.particleEmitterType.direction2;
  56340. }
  56341. return BABYLON.Vector3.Zero();
  56342. },
  56343. set: function (value) {
  56344. if (this.particleEmitterType.direction2) {
  56345. this.particleEmitterType.direction2 = value;
  56346. }
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56352. /**
  56353. * 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.
  56354. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56355. */
  56356. get: function () {
  56357. if (this.particleEmitterType.minEmitBox) {
  56358. return this.particleEmitterType.minEmitBox;
  56359. }
  56360. return BABYLON.Vector3.Zero();
  56361. },
  56362. set: function (value) {
  56363. if (this.particleEmitterType.minEmitBox) {
  56364. this.particleEmitterType.minEmitBox = value;
  56365. }
  56366. },
  56367. enumerable: true,
  56368. configurable: true
  56369. });
  56370. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56371. /**
  56372. * 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.
  56373. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56374. */
  56375. get: function () {
  56376. if (this.particleEmitterType.maxEmitBox) {
  56377. return this.particleEmitterType.maxEmitBox;
  56378. }
  56379. return BABYLON.Vector3.Zero();
  56380. },
  56381. set: function (value) {
  56382. if (this.particleEmitterType.maxEmitBox) {
  56383. this.particleEmitterType.maxEmitBox = value;
  56384. }
  56385. },
  56386. enumerable: true,
  56387. configurable: true
  56388. });
  56389. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56390. /**
  56391. * Sets a callback that will be triggered when the system is disposed.
  56392. */
  56393. set: function (callback) {
  56394. if (this._onDisposeObserver) {
  56395. this.onDisposeObservable.remove(this._onDisposeObserver);
  56396. }
  56397. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56398. },
  56399. enumerable: true,
  56400. configurable: true
  56401. });
  56402. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56403. /**
  56404. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56405. */
  56406. get: function () {
  56407. return this._isAnimationSheetEnabled;
  56408. },
  56409. enumerable: true,
  56410. configurable: true
  56411. });
  56412. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56413. //end of Sub-emitter
  56414. /**
  56415. * Gets the current list of active particles
  56416. */
  56417. get: function () {
  56418. return this._particles;
  56419. },
  56420. enumerable: true,
  56421. configurable: true
  56422. });
  56423. /**
  56424. * Returns the string "ParticleSystem"
  56425. * @returns a string containing the class name
  56426. */
  56427. ParticleSystem.prototype.getClassName = function () {
  56428. return "ParticleSystem";
  56429. };
  56430. ParticleSystem.prototype._createIndexBuffer = function () {
  56431. var indices = [];
  56432. var index = 0;
  56433. for (var count = 0; count < this._capacity; count++) {
  56434. indices.push(index);
  56435. indices.push(index + 1);
  56436. indices.push(index + 2);
  56437. indices.push(index);
  56438. indices.push(index + 2);
  56439. indices.push(index + 3);
  56440. index += 4;
  56441. }
  56442. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56443. };
  56444. /**
  56445. * Gets the maximum number of particles active at the same time.
  56446. * @returns The max number of active particles.
  56447. */
  56448. ParticleSystem.prototype.getCapacity = function () {
  56449. return this._capacity;
  56450. };
  56451. /**
  56452. * Gets Wether there are still active particles in the system.
  56453. * @returns True if it is alive, otherwise false.
  56454. */
  56455. ParticleSystem.prototype.isAlive = function () {
  56456. return this._alive;
  56457. };
  56458. /**
  56459. * Gets Wether the system has been started.
  56460. * @returns True if it has been started, otherwise false.
  56461. */
  56462. ParticleSystem.prototype.isStarted = function () {
  56463. return this._started;
  56464. };
  56465. /**
  56466. * Starts the particle system and begins to emit.
  56467. */
  56468. ParticleSystem.prototype.start = function () {
  56469. this._started = true;
  56470. this._stopped = false;
  56471. this._actualFrame = 0;
  56472. if (this.subEmitters && this.subEmitters.length != 0) {
  56473. this.activeSubSystems = new Array();
  56474. }
  56475. };
  56476. /**
  56477. * Stops the particle system.
  56478. * @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.
  56479. */
  56480. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56481. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56482. this._stopped = true;
  56483. if (stopSubEmitters) {
  56484. this._stopSubEmitters();
  56485. }
  56486. };
  56487. // animation sheet
  56488. /**
  56489. * Remove all active particles
  56490. */
  56491. ParticleSystem.prototype.reset = function () {
  56492. this._stockParticles = [];
  56493. this._particles = [];
  56494. };
  56495. /**
  56496. * @hidden (for internal use only)
  56497. */
  56498. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56499. var offset = index * this._vertexBufferSize;
  56500. this._vertexData[offset] = particle.position.x;
  56501. this._vertexData[offset + 1] = particle.position.y;
  56502. this._vertexData[offset + 2] = particle.position.z;
  56503. this._vertexData[offset + 3] = particle.color.r;
  56504. this._vertexData[offset + 4] = particle.color.g;
  56505. this._vertexData[offset + 5] = particle.color.b;
  56506. this._vertexData[offset + 6] = particle.color.a;
  56507. this._vertexData[offset + 7] = particle.angle;
  56508. this._vertexData[offset + 8] = particle.size;
  56509. this._vertexData[offset + 9] = offsetX;
  56510. this._vertexData[offset + 10] = offsetY;
  56511. };
  56512. /**
  56513. * @hidden (for internal use only)
  56514. */
  56515. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56516. if (offsetX === 0)
  56517. offsetX = this._epsilon;
  56518. else if (offsetX === 1)
  56519. offsetX = 1 - this._epsilon;
  56520. if (offsetY === 0)
  56521. offsetY = this._epsilon;
  56522. else if (offsetY === 1)
  56523. offsetY = 1 - this._epsilon;
  56524. var offset = index * this._vertexBufferSize;
  56525. this._vertexData[offset] = particle.position.x;
  56526. this._vertexData[offset + 1] = particle.position.y;
  56527. this._vertexData[offset + 2] = particle.position.z;
  56528. this._vertexData[offset + 3] = particle.color.r;
  56529. this._vertexData[offset + 4] = particle.color.g;
  56530. this._vertexData[offset + 5] = particle.color.b;
  56531. this._vertexData[offset + 6] = particle.color.a;
  56532. this._vertexData[offset + 7] = particle.angle;
  56533. this._vertexData[offset + 8] = particle.size;
  56534. this._vertexData[offset + 9] = offsetX;
  56535. this._vertexData[offset + 10] = offsetY;
  56536. this._vertexData[offset + 11] = particle.cellIndex;
  56537. };
  56538. ParticleSystem.prototype._stopSubEmitters = function () {
  56539. if (!this.activeSubSystems) {
  56540. return;
  56541. }
  56542. this.activeSubSystems.forEach(function (subSystem) {
  56543. subSystem.stop(true);
  56544. });
  56545. this.activeSubSystems = new Array();
  56546. };
  56547. ParticleSystem.prototype._removeFromRoot = function () {
  56548. if (!this._rootParticleSystem) {
  56549. return;
  56550. }
  56551. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56552. if (index !== -1) {
  56553. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56554. }
  56555. };
  56556. // end of sub system methods
  56557. ParticleSystem.prototype._update = function (newParticles) {
  56558. // Update current
  56559. this._alive = this._particles.length > 0;
  56560. this.updateFunction(this._particles);
  56561. // Add new ones
  56562. var worldMatrix;
  56563. if (this.emitter.position) {
  56564. var emitterMesh = this.emitter;
  56565. worldMatrix = emitterMesh.getWorldMatrix();
  56566. }
  56567. else {
  56568. var emitterPosition = this.emitter;
  56569. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56570. }
  56571. var particle;
  56572. for (var index = 0; index < newParticles; index++) {
  56573. if (this._particles.length === this._capacity) {
  56574. break;
  56575. }
  56576. particle = this._createParticle();
  56577. this._particles.push(particle);
  56578. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56579. if (this.startPositionFunction) {
  56580. this.startPositionFunction(worldMatrix, particle.position, particle);
  56581. }
  56582. else {
  56583. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56584. }
  56585. if (this.startDirectionFunction) {
  56586. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56587. }
  56588. else {
  56589. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56590. }
  56591. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56592. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56593. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56594. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56595. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56596. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56597. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56598. }
  56599. };
  56600. ParticleSystem.prototype._getEffect = function () {
  56601. if (this._customEffect) {
  56602. return this._customEffect;
  56603. }
  56604. ;
  56605. var defines = [];
  56606. if (this._scene.clipPlane) {
  56607. defines.push("#define CLIPPLANE");
  56608. }
  56609. if (this._isAnimationSheetEnabled) {
  56610. defines.push("#define ANIMATESHEET");
  56611. }
  56612. // Effect
  56613. var join = defines.join("\n");
  56614. if (this._cachedDefines !== join) {
  56615. this._cachedDefines = join;
  56616. var attributesNamesOrOptions;
  56617. var effectCreationOption;
  56618. if (this._isAnimationSheetEnabled) {
  56619. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56620. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56621. }
  56622. else {
  56623. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56624. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56625. }
  56626. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56627. }
  56628. return this._effect;
  56629. };
  56630. /**
  56631. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56632. */
  56633. ParticleSystem.prototype.animate = function () {
  56634. if (!this._started)
  56635. return;
  56636. var effect = this._getEffect();
  56637. // Check
  56638. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56639. return;
  56640. if (this._currentRenderId === this._scene.getRenderId()) {
  56641. return;
  56642. }
  56643. this._currentRenderId = this._scene.getRenderId();
  56644. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56645. // determine the number of particles we need to create
  56646. var newParticles;
  56647. if (this.manualEmitCount > -1) {
  56648. newParticles = this.manualEmitCount;
  56649. this._newPartsExcess = 0;
  56650. this.manualEmitCount = 0;
  56651. }
  56652. else {
  56653. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56654. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56655. }
  56656. if (this._newPartsExcess > 1.0) {
  56657. newParticles += this._newPartsExcess >> 0;
  56658. this._newPartsExcess -= this._newPartsExcess >> 0;
  56659. }
  56660. this._alive = false;
  56661. if (!this._stopped) {
  56662. this._actualFrame += this._scaledUpdateSpeed;
  56663. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56664. this.stop();
  56665. }
  56666. else {
  56667. newParticles = 0;
  56668. }
  56669. this._update(newParticles);
  56670. // Stopped?
  56671. if (this._stopped) {
  56672. if (!this._alive) {
  56673. this._started = false;
  56674. if (this.onAnimationEnd) {
  56675. this.onAnimationEnd();
  56676. }
  56677. if (this.disposeOnStop) {
  56678. this._scene._toBeDisposed.push(this);
  56679. }
  56680. }
  56681. }
  56682. // Animation sheet
  56683. if (this._isAnimationSheetEnabled) {
  56684. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56685. }
  56686. else {
  56687. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56688. }
  56689. // Update VBO
  56690. var offset = 0;
  56691. for (var index = 0; index < this._particles.length; index++) {
  56692. var particle = this._particles[index];
  56693. this._appendParticleVertexes(offset, particle);
  56694. offset += 4;
  56695. }
  56696. if (this._vertexBuffer) {
  56697. this._vertexBuffer.update(this._vertexData);
  56698. }
  56699. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56700. this.stop();
  56701. }
  56702. };
  56703. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56704. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56705. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56706. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56707. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56708. };
  56709. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56710. this._appendParticleVertex(offset++, particle, 0, 0);
  56711. this._appendParticleVertex(offset++, particle, 1, 0);
  56712. this._appendParticleVertex(offset++, particle, 1, 1);
  56713. this._appendParticleVertex(offset++, particle, 0, 1);
  56714. };
  56715. /**
  56716. * Rebuilds the particle system.
  56717. */
  56718. ParticleSystem.prototype.rebuild = function () {
  56719. this._createIndexBuffer();
  56720. if (this._vertexBuffer) {
  56721. this._vertexBuffer._rebuild();
  56722. }
  56723. };
  56724. /**
  56725. * Is this system ready to be used/rendered
  56726. * @return true if the system is ready
  56727. */
  56728. ParticleSystem.prototype.isReady = function () {
  56729. var effect = this._getEffect();
  56730. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56731. return false;
  56732. }
  56733. return true;
  56734. };
  56735. /**
  56736. * Renders the particle system in its current state.
  56737. * @returns the current number of particles
  56738. */
  56739. ParticleSystem.prototype.render = function () {
  56740. var effect = this._getEffect();
  56741. // Check
  56742. if (!this.isReady() || !this._particles.length) {
  56743. return 0;
  56744. }
  56745. var engine = this._scene.getEngine();
  56746. // Render
  56747. engine.enableEffect(effect);
  56748. engine.setState(false);
  56749. var viewMatrix = this._scene.getViewMatrix();
  56750. effect.setTexture("diffuseSampler", this.particleTexture);
  56751. effect.setMatrix("view", viewMatrix);
  56752. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56753. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56754. var baseSize = this.particleTexture.getBaseSize();
  56755. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56756. }
  56757. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56758. if (this._scene.clipPlane) {
  56759. var clipPlane = this._scene.clipPlane;
  56760. var invView = viewMatrix.clone();
  56761. invView.invert();
  56762. effect.setMatrix("invView", invView);
  56763. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56764. }
  56765. // VBOs
  56766. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56767. // Draw order
  56768. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56769. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56770. }
  56771. else {
  56772. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56773. }
  56774. if (this.forceDepthWrite) {
  56775. engine.setDepthWrite(true);
  56776. }
  56777. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56779. return this._particles.length;
  56780. };
  56781. /**
  56782. * Disposes the particle system and free the associated resources
  56783. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56784. */
  56785. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56786. if (disposeTexture === void 0) { disposeTexture = true; }
  56787. if (this._vertexBuffer) {
  56788. this._vertexBuffer.dispose();
  56789. this._vertexBuffer = null;
  56790. }
  56791. if (this._indexBuffer) {
  56792. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56793. this._indexBuffer = null;
  56794. }
  56795. if (disposeTexture && this.particleTexture) {
  56796. this.particleTexture.dispose();
  56797. this.particleTexture = null;
  56798. }
  56799. this._removeFromRoot();
  56800. // Remove from scene
  56801. var index = this._scene.particleSystems.indexOf(this);
  56802. if (index > -1) {
  56803. this._scene.particleSystems.splice(index, 1);
  56804. }
  56805. // Callback
  56806. this.onDisposeObservable.notifyObservers(this);
  56807. this.onDisposeObservable.clear();
  56808. };
  56809. /**
  56810. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56811. * @param radius The radius of the sphere to emit from
  56812. * @returns the emitter
  56813. */
  56814. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56815. if (radius === void 0) { radius = 1; }
  56816. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56817. this.particleEmitterType = particleEmitter;
  56818. return particleEmitter;
  56819. };
  56820. /**
  56821. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56822. * @param radius The radius of the sphere to emit from
  56823. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56824. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56825. * @returns the emitter
  56826. */
  56827. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56828. if (radius === void 0) { radius = 1; }
  56829. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56830. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56831. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56832. this.particleEmitterType = particleEmitter;
  56833. return particleEmitter;
  56834. };
  56835. /**
  56836. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56837. * @param radius The radius of the cone to emit from
  56838. * @param angle The base angle of the cone
  56839. * @returns the emitter
  56840. */
  56841. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56842. if (radius === void 0) { radius = 1; }
  56843. if (angle === void 0) { angle = Math.PI / 4; }
  56844. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56845. this.particleEmitterType = particleEmitter;
  56846. return particleEmitter;
  56847. };
  56848. // 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.
  56849. /**
  56850. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56851. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56852. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56853. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56854. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56855. * @returns the emitter
  56856. */
  56857. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56858. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56859. this.particleEmitterType = particleEmitter;
  56860. this.direction1 = direction1;
  56861. this.direction2 = direction2;
  56862. this.minEmitBox = minEmitBox;
  56863. this.maxEmitBox = maxEmitBox;
  56864. return particleEmitter;
  56865. };
  56866. // Clone
  56867. /**
  56868. * Clones the particle system.
  56869. * @param name The name of the cloned object
  56870. * @param newEmitter The new emitter to use
  56871. * @returns the cloned particle system
  56872. */
  56873. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56874. var custom = null;
  56875. var program = null;
  56876. if (this.customShader != null) {
  56877. program = this.customShader;
  56878. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56879. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56880. }
  56881. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56882. result.customShader = program;
  56883. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56884. if (newEmitter === undefined) {
  56885. newEmitter = this.emitter;
  56886. }
  56887. result.emitter = newEmitter;
  56888. if (this.particleTexture) {
  56889. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56890. }
  56891. if (!this.preventAutoStart) {
  56892. result.start();
  56893. }
  56894. return result;
  56895. };
  56896. /**
  56897. * Serializes the particle system to a JSON object.
  56898. * @returns the JSON object
  56899. */
  56900. ParticleSystem.prototype.serialize = function () {
  56901. var serializationObject = {};
  56902. serializationObject.name = this.name;
  56903. serializationObject.id = this.id;
  56904. // Emitter
  56905. if (this.emitter.position) {
  56906. var emitterMesh = this.emitter;
  56907. serializationObject.emitterId = emitterMesh.id;
  56908. }
  56909. else {
  56910. var emitterPosition = this.emitter;
  56911. serializationObject.emitter = emitterPosition.asArray();
  56912. }
  56913. serializationObject.capacity = this.getCapacity();
  56914. if (this.particleTexture) {
  56915. serializationObject.textureName = this.particleTexture.name;
  56916. }
  56917. // Animations
  56918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56919. // Particle system
  56920. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56921. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56922. serializationObject.minSize = this.minSize;
  56923. serializationObject.maxSize = this.maxSize;
  56924. serializationObject.minEmitPower = this.minEmitPower;
  56925. serializationObject.maxEmitPower = this.maxEmitPower;
  56926. serializationObject.minLifeTime = this.minLifeTime;
  56927. serializationObject.maxLifeTime = this.maxLifeTime;
  56928. serializationObject.emitRate = this.emitRate;
  56929. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56930. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56931. serializationObject.gravity = this.gravity.asArray();
  56932. serializationObject.direction1 = this.direction1.asArray();
  56933. serializationObject.direction2 = this.direction2.asArray();
  56934. serializationObject.color1 = this.color1.asArray();
  56935. serializationObject.color2 = this.color2.asArray();
  56936. serializationObject.colorDead = this.colorDead.asArray();
  56937. serializationObject.updateSpeed = this.updateSpeed;
  56938. serializationObject.targetStopDuration = this.targetStopDuration;
  56939. serializationObject.textureMask = this.textureMask.asArray();
  56940. serializationObject.blendMode = this.blendMode;
  56941. serializationObject.customShader = this.customShader;
  56942. serializationObject.preventAutoStart = this.preventAutoStart;
  56943. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56944. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56945. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56946. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56947. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56948. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56949. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56950. // Emitter
  56951. if (this.particleEmitterType) {
  56952. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56953. }
  56954. return serializationObject;
  56955. };
  56956. /**
  56957. * Parses a JSON object to create a particle system.
  56958. * @param parsedParticleSystem The JSON object to parse
  56959. * @param scene The scene to create the particle system in
  56960. * @param rootUrl The root url to use to load external dependencies like texture
  56961. * @returns the Parsed particle system
  56962. */
  56963. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56964. var name = parsedParticleSystem.name;
  56965. var custom = null;
  56966. var program = null;
  56967. if (parsedParticleSystem.customShader) {
  56968. program = parsedParticleSystem.customShader;
  56969. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56970. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56971. }
  56972. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56973. particleSystem.customShader = program;
  56974. if (parsedParticleSystem.id) {
  56975. particleSystem.id = parsedParticleSystem.id;
  56976. }
  56977. // Auto start
  56978. if (parsedParticleSystem.preventAutoStart) {
  56979. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  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. if (parsedParticleSystem.autoAnimate) {
  57001. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57002. }
  57003. // Particle system
  57004. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57005. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57006. particleSystem.minSize = parsedParticleSystem.minSize;
  57007. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57008. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57009. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57010. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57011. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57012. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57013. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57014. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57015. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57016. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57017. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57018. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57019. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57020. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57021. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57022. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57023. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57024. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57025. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57026. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57027. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57028. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57029. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57030. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57031. if (!particleSystem.preventAutoStart) {
  57032. particleSystem.start();
  57033. }
  57034. return particleSystem;
  57035. };
  57036. /**
  57037. * Source color is added to the destination color without alpha affecting the result.
  57038. */
  57039. ParticleSystem.BLENDMODE_ONEONE = 0;
  57040. /**
  57041. * Blend current color and particle color using particle’s alpha.
  57042. */
  57043. ParticleSystem.BLENDMODE_STANDARD = 1;
  57044. return ParticleSystem;
  57045. }());
  57046. BABYLON.ParticleSystem = ParticleSystem;
  57047. })(BABYLON || (BABYLON = {}));
  57048. //# sourceMappingURL=babylon.particleSystem.js.map
  57049. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57050. var BABYLON;
  57051. (function (BABYLON) {
  57052. /**
  57053. * Particle emitter emitting particles from the inside of a box.
  57054. * It emits the particles randomly between 2 given directions.
  57055. */
  57056. var BoxParticleEmitter = /** @class */ (function () {
  57057. /**
  57058. * Creates a new instance BoxParticleEmitter
  57059. */
  57060. function BoxParticleEmitter() {
  57061. /**
  57062. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57063. */
  57064. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57065. /**
  57066. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57067. */
  57068. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57069. /**
  57070. * 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.
  57071. */
  57072. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57073. /**
  57074. * 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.
  57075. */
  57076. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57077. }
  57078. /**
  57079. * Called by the particle System when the direction is computed for the created particle.
  57080. * @param emitPower is the power of the particle (speed)
  57081. * @param worldMatrix is the world matrix of the particle system
  57082. * @param directionToUpdate is the direction vector to update with the result
  57083. * @param particle is the particle we are computed the direction for
  57084. */
  57085. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57086. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57087. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57088. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57089. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57090. };
  57091. /**
  57092. * Called by the particle System when the position is computed for the created particle.
  57093. * @param worldMatrix is the world matrix of the particle system
  57094. * @param positionToUpdate is the position vector to update with the result
  57095. * @param particle is the particle we are computed the position for
  57096. */
  57097. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57098. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57099. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57100. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57102. };
  57103. /**
  57104. * Clones the current emitter and returns a copy of it
  57105. * @returns the new emitter
  57106. */
  57107. BoxParticleEmitter.prototype.clone = function () {
  57108. var newOne = new BoxParticleEmitter();
  57109. BABYLON.Tools.DeepCopy(this, newOne);
  57110. return newOne;
  57111. };
  57112. /**
  57113. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57114. * @param effect defines the update shader
  57115. */
  57116. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57117. effect.setVector3("direction1", this.direction1);
  57118. effect.setVector3("direction2", this.direction2);
  57119. effect.setVector3("minEmitBox", this.minEmitBox);
  57120. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57121. };
  57122. /**
  57123. * Returns a string to use to update the GPU particles update shader
  57124. * @returns a string containng the defines string
  57125. */
  57126. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57127. return "#define BOXEMITTER";
  57128. };
  57129. /**
  57130. * Returns the string "BoxEmitter"
  57131. * @returns a string containing the class name
  57132. */
  57133. BoxParticleEmitter.prototype.getClassName = function () {
  57134. return "BoxEmitter";
  57135. };
  57136. /**
  57137. * Serializes the particle system to a JSON object.
  57138. * @returns the JSON object
  57139. */
  57140. BoxParticleEmitter.prototype.serialize = function () {
  57141. var serializationObject = {};
  57142. serializationObject.type = this.getClassName();
  57143. serializationObject.direction1 = this.direction1.asArray();
  57144. serializationObject.direction2 = this.direction2.asArray();
  57145. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57146. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57147. return serializationObject;
  57148. };
  57149. /**
  57150. * Parse properties from a JSON object
  57151. * @param serializationObject defines the JSON object
  57152. */
  57153. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57154. this.direction1.copyFrom(serializationObject.direction1);
  57155. this.direction2.copyFrom(serializationObject.direction2);
  57156. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57157. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57158. };
  57159. return BoxParticleEmitter;
  57160. }());
  57161. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57162. })(BABYLON || (BABYLON = {}));
  57163. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57164. var BABYLON;
  57165. (function (BABYLON) {
  57166. /**
  57167. * Particle emitter emitting particles from the inside of a cone.
  57168. * It emits the particles alongside the cone volume from the base to the particle.
  57169. * The emission direction might be randomized.
  57170. */
  57171. var ConeParticleEmitter = /** @class */ (function () {
  57172. /**
  57173. * Creates a new instance ConeParticleEmitter
  57174. * @param radius the radius of the emission cone (1 by default)
  57175. * @param angles the cone base angle (PI by default)
  57176. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57177. */
  57178. function ConeParticleEmitter(radius,
  57179. /**
  57180. * The radius of the emission cone.
  57181. */
  57182. angle,
  57183. /**
  57184. * The cone base angle.
  57185. */
  57186. directionRandomizer) {
  57187. if (radius === void 0) { radius = 1; }
  57188. if (angle === void 0) { angle = Math.PI; }
  57189. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57190. this.angle = angle;
  57191. this.directionRandomizer = directionRandomizer;
  57192. this.radius = radius;
  57193. }
  57194. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57195. /**
  57196. * Gets the radius of the emission cone.
  57197. */
  57198. get: function () {
  57199. return this._radius;
  57200. },
  57201. /**
  57202. * Sets the radius of the emission cone.
  57203. */
  57204. set: function (value) {
  57205. this._radius = value;
  57206. if (this.angle !== 0) {
  57207. this._height = value / Math.tan(this.angle / 2);
  57208. }
  57209. else {
  57210. this._height = 1;
  57211. }
  57212. },
  57213. enumerable: true,
  57214. configurable: true
  57215. });
  57216. /**
  57217. * Called by the particle System when the direction is computed for the created particle.
  57218. * @param emitPower is the power of the particle (speed)
  57219. * @param worldMatrix is the world matrix of the particle system
  57220. * @param directionToUpdate is the direction vector to update with the result
  57221. * @param particle is the particle we are computed the direction for
  57222. */
  57223. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57224. if (this.angle === 0) {
  57225. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57226. }
  57227. else {
  57228. // measure the direction Vector from the emitter to the particle.
  57229. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57230. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57231. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57232. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57233. direction.x += randX;
  57234. direction.y += randY;
  57235. direction.z += randZ;
  57236. direction.normalize();
  57237. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57238. }
  57239. };
  57240. /**
  57241. * Called by the particle System when the position is computed for the created particle.
  57242. * @param worldMatrix is the world matrix of the particle system
  57243. * @param positionToUpdate is the position vector to update with the result
  57244. * @param particle is the particle we are computed the position for
  57245. */
  57246. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57247. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57248. var h = BABYLON.Scalar.RandomRange(0, 1);
  57249. // Better distribution in a cone at normal angles.
  57250. h = 1 - h * h;
  57251. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57252. radius = radius * h;
  57253. var randX = radius * Math.sin(s);
  57254. var randZ = radius * Math.cos(s);
  57255. var randY = h * this._height;
  57256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57257. };
  57258. /**
  57259. * Clones the current emitter and returns a copy of it
  57260. * @returns the new emitter
  57261. */
  57262. ConeParticleEmitter.prototype.clone = function () {
  57263. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57264. BABYLON.Tools.DeepCopy(this, newOne);
  57265. return newOne;
  57266. };
  57267. /**
  57268. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57269. * @param effect defines the update shader
  57270. */
  57271. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57272. effect.setFloat("radius", this.radius);
  57273. effect.setFloat("coneAngle", this.angle);
  57274. effect.setFloat("height", this._height);
  57275. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57276. };
  57277. /**
  57278. * Returns a string to use to update the GPU particles update shader
  57279. * @returns a string containng the defines string
  57280. */
  57281. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57282. return "#define CONEEMITTER";
  57283. };
  57284. /**
  57285. * Returns the string "BoxEmitter"
  57286. * @returns a string containing the class name
  57287. */
  57288. ConeParticleEmitter.prototype.getClassName = function () {
  57289. return "ConeEmitter";
  57290. };
  57291. /**
  57292. * Serializes the particle system to a JSON object.
  57293. * @returns the JSON object
  57294. */
  57295. ConeParticleEmitter.prototype.serialize = function () {
  57296. var serializationObject = {};
  57297. serializationObject.type = this.getClassName();
  57298. serializationObject.radius = this.radius;
  57299. serializationObject.angle = this.angle;
  57300. serializationObject.directionRandomizer = this.directionRandomizer;
  57301. return serializationObject;
  57302. };
  57303. /**
  57304. * Parse properties from a JSON object
  57305. * @param serializationObject defines the JSON object
  57306. */
  57307. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57308. this.radius = serializationObject.radius;
  57309. this.angle = serializationObject.angle;
  57310. this.directionRandomizer = serializationObject.directionRandomizer;
  57311. };
  57312. return ConeParticleEmitter;
  57313. }());
  57314. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57315. })(BABYLON || (BABYLON = {}));
  57316. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57317. var BABYLON;
  57318. (function (BABYLON) {
  57319. /**
  57320. * Particle emitter emitting particles from the inside of a sphere.
  57321. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57322. */
  57323. var SphereParticleEmitter = /** @class */ (function () {
  57324. /**
  57325. * Creates a new instance SphereParticleEmitter
  57326. * @param radius the radius of the emission sphere (1 by default)
  57327. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57328. */
  57329. function SphereParticleEmitter(
  57330. /**
  57331. * The radius of the emission sphere.
  57332. */
  57333. radius,
  57334. /**
  57335. * How much to randomize the particle direction [0-1].
  57336. */
  57337. directionRandomizer) {
  57338. if (radius === void 0) { radius = 1; }
  57339. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57340. this.radius = radius;
  57341. this.directionRandomizer = directionRandomizer;
  57342. }
  57343. /**
  57344. * Called by the particle System when the direction is computed for the created particle.
  57345. * @param emitPower is the power of the particle (speed)
  57346. * @param worldMatrix is the world matrix of the particle system
  57347. * @param directionToUpdate is the direction vector to update with the result
  57348. * @param particle is the particle we are computed the direction for
  57349. */
  57350. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57351. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57352. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57353. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57354. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57355. direction.x += randX;
  57356. direction.y += randY;
  57357. direction.z += randZ;
  57358. direction.normalize();
  57359. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57360. };
  57361. /**
  57362. * Called by the particle System when the position is computed for the created particle.
  57363. * @param worldMatrix is the world matrix of the particle system
  57364. * @param positionToUpdate is the position vector to update with the result
  57365. * @param particle is the particle we are computed the position for
  57366. */
  57367. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57368. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57369. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57370. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57371. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57372. var randY = randRadius * Math.cos(theta);
  57373. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57374. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57375. };
  57376. /**
  57377. * Clones the current emitter and returns a copy of it
  57378. * @returns the new emitter
  57379. */
  57380. SphereParticleEmitter.prototype.clone = function () {
  57381. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57382. BABYLON.Tools.DeepCopy(this, newOne);
  57383. return newOne;
  57384. };
  57385. /**
  57386. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57387. * @param effect defines the update shader
  57388. */
  57389. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57390. effect.setFloat("radius", this.radius);
  57391. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57392. };
  57393. /**
  57394. * Returns a string to use to update the GPU particles update shader
  57395. * @returns a string containng the defines string
  57396. */
  57397. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57398. return "#define SPHEREEMITTER";
  57399. };
  57400. /**
  57401. * Returns the string "SphereParticleEmitter"
  57402. * @returns a string containing the class name
  57403. */
  57404. SphereParticleEmitter.prototype.getClassName = function () {
  57405. return "SphereParticleEmitter";
  57406. };
  57407. /**
  57408. * Serializes the particle system to a JSON object.
  57409. * @returns the JSON object
  57410. */
  57411. SphereParticleEmitter.prototype.serialize = function () {
  57412. var serializationObject = {};
  57413. serializationObject.type = this.getClassName();
  57414. serializationObject.radius = this.radius;
  57415. serializationObject.directionRandomizer = this.directionRandomizer;
  57416. return serializationObject;
  57417. };
  57418. /**
  57419. * Parse properties from a JSON object
  57420. * @param serializationObject defines the JSON object
  57421. */
  57422. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57423. this.radius = serializationObject.radius;
  57424. this.directionRandomizer = serializationObject.directionRandomizer;
  57425. };
  57426. return SphereParticleEmitter;
  57427. }());
  57428. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57429. /**
  57430. * Particle emitter emitting particles from the inside of a sphere.
  57431. * It emits the particles randomly between two vectors.
  57432. */
  57433. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57434. __extends(SphereDirectedParticleEmitter, _super);
  57435. /**
  57436. * Creates a new instance SphereDirectedParticleEmitter
  57437. * @param radius the radius of the emission sphere (1 by default)
  57438. * @param direction1 the min limit of the emission direction (up vector by default)
  57439. * @param direction2 the max limit of the emission direction (up vector by default)
  57440. */
  57441. function SphereDirectedParticleEmitter(radius,
  57442. /**
  57443. * The min limit of the emission direction.
  57444. */
  57445. direction1,
  57446. /**
  57447. * The max limit of the emission direction.
  57448. */
  57449. direction2) {
  57450. if (radius === void 0) { radius = 1; }
  57451. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57452. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57453. var _this = _super.call(this, radius) || this;
  57454. _this.direction1 = direction1;
  57455. _this.direction2 = direction2;
  57456. return _this;
  57457. }
  57458. /**
  57459. * Called by the particle System when the direction is computed for the created particle.
  57460. * @param emitPower is the power of the particle (speed)
  57461. * @param worldMatrix is the world matrix of the particle system
  57462. * @param directionToUpdate is the direction vector to update with the result
  57463. * @param particle is the particle we are computed the direction for
  57464. */
  57465. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57466. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57467. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57468. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57469. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57470. };
  57471. /**
  57472. * Clones the current emitter and returns a copy of it
  57473. * @returns the new emitter
  57474. */
  57475. SphereDirectedParticleEmitter.prototype.clone = function () {
  57476. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57477. BABYLON.Tools.DeepCopy(this, newOne);
  57478. return newOne;
  57479. };
  57480. /**
  57481. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57482. * @param effect defines the update shader
  57483. */
  57484. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57485. effect.setFloat("radius", this.radius);
  57486. effect.setVector3("direction1", this.direction1);
  57487. effect.setVector3("direction2", this.direction2);
  57488. };
  57489. /**
  57490. * Returns a string to use to update the GPU particles update shader
  57491. * @returns a string containng the defines string
  57492. */
  57493. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57494. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57495. };
  57496. /**
  57497. * Returns the string "SphereDirectedParticleEmitter"
  57498. * @returns a string containing the class name
  57499. */
  57500. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57501. return "SphereDirectedParticleEmitter";
  57502. };
  57503. /**
  57504. * Serializes the particle system to a JSON object.
  57505. * @returns the JSON object
  57506. */
  57507. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57508. var serializationObject = _super.prototype.serialize.call(this);
  57509. serializationObject.direction1 = this.direction1.asArray();
  57510. serializationObject.direction2 = this.direction2.asArray();
  57511. return serializationObject;
  57512. };
  57513. /**
  57514. * Parse properties from a JSON object
  57515. * @param serializationObject defines the JSON object
  57516. */
  57517. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57518. _super.prototype.parse.call(this, serializationObject);
  57519. this.direction1.copyFrom(serializationObject.direction1);
  57520. this.direction2.copyFrom(serializationObject.direction2);
  57521. };
  57522. return SphereDirectedParticleEmitter;
  57523. }(SphereParticleEmitter));
  57524. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57525. })(BABYLON || (BABYLON = {}));
  57526. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57527. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57528. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57529. s = arguments[i];
  57530. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57531. t[p] = s[p];
  57532. }
  57533. return t;
  57534. };
  57535. var BABYLON;
  57536. (function (BABYLON) {
  57537. /**
  57538. * This represents a GPU particle system in Babylon
  57539. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57540. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57541. */
  57542. var GPUParticleSystem = /** @class */ (function () {
  57543. /**
  57544. * Instantiates a GPU particle system.
  57545. * 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.
  57546. * @param name The name of the particle system
  57547. * @param capacity The max number of particles alive at the same time
  57548. * @param scene The scene the particle system belongs to
  57549. */
  57550. function GPUParticleSystem(name, options, scene) {
  57551. /**
  57552. * The emitter represents the Mesh or position we are attaching the particle system to.
  57553. */
  57554. this.emitter = null;
  57555. /**
  57556. * The rendering group used by the Particle system to chose when to render.
  57557. */
  57558. this.renderingGroupId = 0;
  57559. /**
  57560. * The layer mask we are rendering the particles through.
  57561. */
  57562. this.layerMask = 0x0FFFFFFF;
  57563. this._targetIndex = 0;
  57564. this._currentRenderId = -1;
  57565. this._started = false;
  57566. this._stopped = false;
  57567. this._timeDelta = 0;
  57568. this._attributesStrideSize = 16;
  57569. this._actualFrame = 0;
  57570. /**
  57571. * List of animations used by the particle system.
  57572. */
  57573. this.animations = [];
  57574. /**
  57575. * An event triggered when the system is disposed.
  57576. */
  57577. this.onDisposeObservable = new BABYLON.Observable();
  57578. /**
  57579. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57580. */
  57581. this.updateSpeed = 0.01;
  57582. /**
  57583. * The amount of time the particle system is running (depends of the overall update speed).
  57584. */
  57585. this.targetStopDuration = 0;
  57586. /**
  57587. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57588. */
  57589. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57590. /**
  57591. * Minimum life time of emitting particles.
  57592. */
  57593. this.minLifeTime = 1;
  57594. /**
  57595. * Maximum life time of emitting particles.
  57596. */
  57597. this.maxLifeTime = 1;
  57598. /**
  57599. * Minimum Size of emitting particles.
  57600. */
  57601. this.minSize = 1;
  57602. /**
  57603. * Maximum Size of emitting particles.
  57604. */
  57605. this.maxSize = 1;
  57606. /**
  57607. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57608. */
  57609. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57610. /**
  57611. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57612. */
  57613. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57614. /**
  57615. * Color the particle will have at the end of its lifetime.
  57616. */
  57617. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57618. /**
  57619. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57620. */
  57621. this.emitRate = 100;
  57622. /**
  57623. * You can use gravity if you want to give an orientation to your particles.
  57624. */
  57625. this.gravity = BABYLON.Vector3.Zero();
  57626. /**
  57627. * Minimum power of emitting particles.
  57628. */
  57629. this.minEmitPower = 1;
  57630. /**
  57631. * Maximum power of emitting particles.
  57632. */
  57633. this.maxEmitPower = 1;
  57634. /**
  57635. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57636. */
  57637. this.minAngularSpeed = 0;
  57638. /**
  57639. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57640. */
  57641. this.maxAngularSpeed = 0;
  57642. /**
  57643. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57644. * to override the particles.
  57645. */
  57646. this.forceDepthWrite = false;
  57647. this.id = name;
  57648. this.name = name;
  57649. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57650. this._engine = this._scene.getEngine();
  57651. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57652. this._capacity = fullOptions.capacity;
  57653. this._activeCount = fullOptions.capacity;
  57654. this._currentActiveCount = 0;
  57655. this._scene.particleSystems.push(this);
  57656. this._updateEffectOptions = {
  57657. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57658. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57659. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57660. "angleRange"],
  57661. uniformBuffersNames: [],
  57662. samplers: ["randomSampler"],
  57663. defines: "",
  57664. fallbacks: null,
  57665. onCompiled: null,
  57666. onError: null,
  57667. indexParameters: null,
  57668. maxSimultaneousLights: 0,
  57669. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57670. };
  57671. // Random data
  57672. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57673. var d = [];
  57674. for (var i = 0; i < maxTextureSize; ++i) {
  57675. d.push(Math.random());
  57676. d.push(Math.random());
  57677. d.push(Math.random());
  57678. d.push(Math.random());
  57679. }
  57680. 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);
  57681. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57682. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57683. this._randomTextureSize = maxTextureSize;
  57684. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57685. }
  57686. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57687. /**
  57688. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57689. */
  57690. get: function () {
  57691. if (!BABYLON.Engine.LastCreatedEngine) {
  57692. return false;
  57693. }
  57694. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57695. },
  57696. enumerable: true,
  57697. configurable: true
  57698. });
  57699. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57700. /**
  57701. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57702. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57703. */
  57704. get: function () {
  57705. if (this.particleEmitterType.direction1) {
  57706. return this.particleEmitterType.direction1;
  57707. }
  57708. return BABYLON.Vector3.Zero();
  57709. },
  57710. set: function (value) {
  57711. if (this.particleEmitterType.direction1) {
  57712. this.particleEmitterType.direction1 = value;
  57713. }
  57714. },
  57715. enumerable: true,
  57716. configurable: true
  57717. });
  57718. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57719. /**
  57720. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57721. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57722. */
  57723. get: function () {
  57724. if (this.particleEmitterType.direction2) {
  57725. return this.particleEmitterType.direction2;
  57726. }
  57727. return BABYLON.Vector3.Zero();
  57728. },
  57729. set: function (value) {
  57730. if (this.particleEmitterType.direction2) {
  57731. this.particleEmitterType.direction2 = value;
  57732. }
  57733. },
  57734. enumerable: true,
  57735. configurable: true
  57736. });
  57737. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57738. /**
  57739. * 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.
  57740. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57741. */
  57742. get: function () {
  57743. if (this.particleEmitterType.minEmitBox) {
  57744. return this.particleEmitterType.minEmitBox;
  57745. }
  57746. return BABYLON.Vector3.Zero();
  57747. },
  57748. set: function (value) {
  57749. if (this.particleEmitterType.minEmitBox) {
  57750. this.particleEmitterType.minEmitBox = value;
  57751. }
  57752. },
  57753. enumerable: true,
  57754. configurable: true
  57755. });
  57756. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57757. /**
  57758. * 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.
  57759. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57760. */
  57761. get: function () {
  57762. if (this.particleEmitterType.maxEmitBox) {
  57763. return this.particleEmitterType.maxEmitBox;
  57764. }
  57765. return BABYLON.Vector3.Zero();
  57766. },
  57767. set: function (value) {
  57768. if (this.particleEmitterType.maxEmitBox) {
  57769. this.particleEmitterType.maxEmitBox = value;
  57770. }
  57771. },
  57772. enumerable: true,
  57773. configurable: true
  57774. });
  57775. /**
  57776. * Gets the maximum number of particles active at the same time.
  57777. * @returns The max number of active particles.
  57778. */
  57779. GPUParticleSystem.prototype.getCapacity = function () {
  57780. return this._capacity;
  57781. };
  57782. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57783. /**
  57784. * Gets or set the number of active particles
  57785. */
  57786. get: function () {
  57787. return this._activeCount;
  57788. },
  57789. set: function (value) {
  57790. this._activeCount = Math.min(value, this._capacity);
  57791. },
  57792. enumerable: true,
  57793. configurable: true
  57794. });
  57795. /**
  57796. * Is this system ready to be used/rendered
  57797. * @return true if the system is ready
  57798. */
  57799. GPUParticleSystem.prototype.isReady = function () {
  57800. if (!this._updateEffect) {
  57801. this._recreateUpdateEffect();
  57802. this._recreateRenderEffect();
  57803. return false;
  57804. }
  57805. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57806. return false;
  57807. }
  57808. return true;
  57809. };
  57810. /**
  57811. * Gets Wether the system has been started.
  57812. * @returns True if it has been started, otherwise false.
  57813. */
  57814. GPUParticleSystem.prototype.isStarted = function () {
  57815. return this._started;
  57816. };
  57817. /**
  57818. * Starts the particle system and begins to emit.
  57819. */
  57820. GPUParticleSystem.prototype.start = function () {
  57821. this._started = true;
  57822. this._stopped = false;
  57823. };
  57824. /**
  57825. * Stops the particle system.
  57826. */
  57827. GPUParticleSystem.prototype.stop = function () {
  57828. this._stopped = true;
  57829. };
  57830. /**
  57831. * Remove all active particles
  57832. */
  57833. GPUParticleSystem.prototype.reset = function () {
  57834. this._releaseBuffers();
  57835. this._releaseVAOs();
  57836. this._currentActiveCount = 0;
  57837. this._targetIndex = 0;
  57838. };
  57839. /**
  57840. * Returns the string "GPUParticleSystem"
  57841. * @returns a string containing the class name
  57842. */
  57843. GPUParticleSystem.prototype.getClassName = function () {
  57844. return "GPUParticleSystem";
  57845. };
  57846. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57847. var updateVertexBuffers = {};
  57848. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57849. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57850. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57851. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57852. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57853. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57854. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57855. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57856. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57857. this._engine.bindArrayBuffer(null);
  57858. return vao;
  57859. };
  57860. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57861. var renderVertexBuffers = {};
  57862. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57863. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57864. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57865. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57866. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57867. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57868. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57869. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57870. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57871. this._engine.bindArrayBuffer(null);
  57872. return vao;
  57873. };
  57874. GPUParticleSystem.prototype._initialize = function (force) {
  57875. if (force === void 0) { force = false; }
  57876. if (this._buffer0 && !force) {
  57877. return;
  57878. }
  57879. var engine = this._scene.getEngine();
  57880. var data = new Array();
  57881. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57882. // position
  57883. data.push(0.0);
  57884. data.push(0.0);
  57885. data.push(0.0);
  57886. // Age and life
  57887. data.push(0.0); // create the particle as a dead one to create a new one at start
  57888. data.push(0.0);
  57889. // Seed
  57890. data.push(Math.random());
  57891. // Size
  57892. data.push(0.0);
  57893. // color
  57894. data.push(0.0);
  57895. data.push(0.0);
  57896. data.push(0.0);
  57897. data.push(0.0);
  57898. // direction
  57899. data.push(0.0);
  57900. data.push(0.0);
  57901. data.push(0.0);
  57902. // angle
  57903. data.push(0.0);
  57904. data.push(0.0);
  57905. }
  57906. // Sprite data
  57907. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57908. -0.5, 0.5, 0, 1,
  57909. -0.5, -0.5, 0, 0,
  57910. 0.5, -0.5, 1, 0]);
  57911. // Buffers
  57912. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57913. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57914. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57915. // Update VAO
  57916. this._updateVAO = [];
  57917. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57918. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57919. // Render VAO
  57920. this._renderVAO = [];
  57921. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57922. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57923. // Links
  57924. this._sourceBuffer = this._buffer0;
  57925. this._targetBuffer = this._buffer1;
  57926. };
  57927. /** @hidden */
  57928. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57929. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57930. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57931. return;
  57932. }
  57933. this._updateEffectOptions.defines = defines;
  57934. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57935. };
  57936. /** @hidden */
  57937. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57938. var defines = "";
  57939. if (this._scene.clipPlane) {
  57940. defines = "\n#define CLIPPLANE";
  57941. }
  57942. if (this._renderEffect && this._renderEffect.defines === defines) {
  57943. return;
  57944. }
  57945. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57946. };
  57947. /**
  57948. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57949. */
  57950. GPUParticleSystem.prototype.animate = function () {
  57951. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57952. this._actualFrame += this._timeDelta;
  57953. if (!this._stopped) {
  57954. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57955. this.stop();
  57956. }
  57957. }
  57958. };
  57959. /**
  57960. * Renders the particle system in its current state.
  57961. * @returns the current number of particles
  57962. */
  57963. GPUParticleSystem.prototype.render = function () {
  57964. if (!this._started) {
  57965. return 0;
  57966. }
  57967. this._recreateUpdateEffect();
  57968. this._recreateRenderEffect();
  57969. if (!this.isReady()) {
  57970. return 0;
  57971. }
  57972. if (this._currentRenderId === this._scene.getRenderId()) {
  57973. return 0;
  57974. }
  57975. this._currentRenderId = this._scene.getRenderId();
  57976. // Get everything ready to render
  57977. this._initialize();
  57978. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57979. // Enable update effect
  57980. this._engine.enableEffect(this._updateEffect);
  57981. this._engine.setState(false);
  57982. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57983. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57984. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57985. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57986. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57987. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57988. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57989. this._updateEffect.setDirectColor4("color1", this.color1);
  57990. this._updateEffect.setDirectColor4("color2", this.color2);
  57991. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57992. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57993. this._updateEffect.setVector3("gravity", this.gravity);
  57994. if (this.particleEmitterType) {
  57995. this.particleEmitterType.applyToShader(this._updateEffect);
  57996. }
  57997. var emitterWM;
  57998. if (this.emitter.position) {
  57999. var emitterMesh = this.emitter;
  58000. emitterWM = emitterMesh.getWorldMatrix();
  58001. }
  58002. else {
  58003. var emitterPosition = this.emitter;
  58004. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58005. }
  58006. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58007. // Bind source VAO
  58008. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58009. // Update
  58010. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58011. this._engine.setRasterizerState(false);
  58012. this._engine.beginTransformFeedback();
  58013. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58014. this._engine.endTransformFeedback();
  58015. this._engine.setRasterizerState(true);
  58016. this._engine.bindTransformFeedbackBuffer(null);
  58017. // Enable render effect
  58018. this._engine.enableEffect(this._renderEffect);
  58019. var viewMatrix = this._scene.getViewMatrix();
  58020. this._renderEffect.setMatrix("view", viewMatrix);
  58021. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58022. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58023. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58024. if (this._scene.clipPlane) {
  58025. var clipPlane = this._scene.clipPlane;
  58026. var invView = viewMatrix.clone();
  58027. invView.invert();
  58028. this._renderEffect.setMatrix("invView", invView);
  58029. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58030. }
  58031. // Draw order
  58032. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58033. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58034. }
  58035. else {
  58036. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58037. }
  58038. if (this.forceDepthWrite) {
  58039. this._engine.setDepthWrite(true);
  58040. }
  58041. // Bind source VAO
  58042. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58043. // Render
  58044. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58045. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58046. // Switch VAOs
  58047. this._targetIndex++;
  58048. if (this._targetIndex === 2) {
  58049. this._targetIndex = 0;
  58050. }
  58051. // Switch buffers
  58052. var tmpBuffer = this._sourceBuffer;
  58053. this._sourceBuffer = this._targetBuffer;
  58054. this._targetBuffer = tmpBuffer;
  58055. return this._currentActiveCount;
  58056. };
  58057. /**
  58058. * Rebuilds the particle system
  58059. */
  58060. GPUParticleSystem.prototype.rebuild = function () {
  58061. this._initialize(true);
  58062. };
  58063. GPUParticleSystem.prototype._releaseBuffers = function () {
  58064. if (this._buffer0) {
  58065. this._buffer0.dispose();
  58066. this._buffer0 = null;
  58067. }
  58068. if (this._buffer1) {
  58069. this._buffer1.dispose();
  58070. this._buffer1 = null;
  58071. }
  58072. if (this._spriteBuffer) {
  58073. this._spriteBuffer.dispose();
  58074. this._spriteBuffer = null;
  58075. }
  58076. };
  58077. GPUParticleSystem.prototype._releaseVAOs = function () {
  58078. if (!this._updateVAO) {
  58079. return;
  58080. }
  58081. for (var index = 0; index < this._updateVAO.length; index++) {
  58082. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58083. }
  58084. this._updateVAO = [];
  58085. for (var index = 0; index < this._renderVAO.length; index++) {
  58086. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58087. }
  58088. this._renderVAO = [];
  58089. };
  58090. /**
  58091. * Disposes the particle system and free the associated resources
  58092. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58093. */
  58094. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58095. if (disposeTexture === void 0) { disposeTexture = true; }
  58096. var index = this._scene.particleSystems.indexOf(this);
  58097. if (index > -1) {
  58098. this._scene.particleSystems.splice(index, 1);
  58099. }
  58100. this._releaseBuffers();
  58101. this._releaseVAOs();
  58102. if (this._randomTexture) {
  58103. this._randomTexture.dispose();
  58104. this._randomTexture = null;
  58105. }
  58106. if (disposeTexture && this.particleTexture) {
  58107. this.particleTexture.dispose();
  58108. this.particleTexture = null;
  58109. }
  58110. // Callback
  58111. this.onDisposeObservable.notifyObservers(this);
  58112. this.onDisposeObservable.clear();
  58113. };
  58114. /**
  58115. * Clones the particle system.
  58116. * @param name The name of the cloned object
  58117. * @param newEmitter The new emitter to use
  58118. * @returns the cloned particle system
  58119. */
  58120. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58121. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58122. BABYLON.Tools.DeepCopy(this, result);
  58123. if (newEmitter === undefined) {
  58124. newEmitter = this.emitter;
  58125. }
  58126. result.emitter = newEmitter;
  58127. if (this.particleTexture) {
  58128. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58129. }
  58130. return result;
  58131. };
  58132. /**
  58133. * Serializes the particle system to a JSON object.
  58134. * @returns the JSON object
  58135. */
  58136. GPUParticleSystem.prototype.serialize = function () {
  58137. var serializationObject = {};
  58138. serializationObject.name = this.name;
  58139. serializationObject.id = this.id;
  58140. // Emitter
  58141. if (this.emitter.position) {
  58142. var emitterMesh = this.emitter;
  58143. serializationObject.emitterId = emitterMesh.id;
  58144. }
  58145. else {
  58146. var emitterPosition = this.emitter;
  58147. serializationObject.emitter = emitterPosition.asArray();
  58148. }
  58149. serializationObject.capacity = this.getCapacity();
  58150. if (this.particleTexture) {
  58151. serializationObject.textureName = this.particleTexture.name;
  58152. }
  58153. // Animations
  58154. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58155. // Particle system
  58156. serializationObject.activeParticleCount = this.activeParticleCount;
  58157. serializationObject.randomTextureSize = this._randomTextureSize;
  58158. serializationObject.minSize = this.minSize;
  58159. serializationObject.maxSize = this.maxSize;
  58160. serializationObject.minEmitPower = this.minEmitPower;
  58161. serializationObject.maxEmitPower = this.maxEmitPower;
  58162. serializationObject.minLifeTime = this.minLifeTime;
  58163. serializationObject.maxLifeTime = this.maxLifeTime;
  58164. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58165. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58166. serializationObject.emitRate = this.emitRate;
  58167. serializationObject.gravity = this.gravity.asArray();
  58168. serializationObject.color1 = this.color1.asArray();
  58169. serializationObject.color2 = this.color2.asArray();
  58170. serializationObject.colorDead = this.colorDead.asArray();
  58171. serializationObject.updateSpeed = this.updateSpeed;
  58172. serializationObject.targetStopDuration = this.targetStopDuration;
  58173. serializationObject.blendMode = this.blendMode;
  58174. // Emitter
  58175. if (this.particleEmitterType) {
  58176. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58177. }
  58178. return serializationObject;
  58179. };
  58180. /**
  58181. * Parses a JSON object to create a GPU particle system.
  58182. * @param parsedParticleSystem The JSON object to parse
  58183. * @param scene The scene to create the particle system in
  58184. * @param rootUrl The root url to use to load external dependencies like texture
  58185. * @returns the parsed GPU particle system
  58186. */
  58187. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58188. var name = parsedParticleSystem.name;
  58189. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58190. if (parsedParticleSystem.id) {
  58191. particleSystem.id = parsedParticleSystem.id;
  58192. }
  58193. // Texture
  58194. if (parsedParticleSystem.textureName) {
  58195. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58196. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58197. }
  58198. // Emitter
  58199. if (parsedParticleSystem.emitterId) {
  58200. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58201. }
  58202. else {
  58203. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58204. }
  58205. // Animations
  58206. if (parsedParticleSystem.animations) {
  58207. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58208. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58209. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58210. }
  58211. }
  58212. // Particle system
  58213. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58214. particleSystem.minSize = parsedParticleSystem.minSize;
  58215. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58216. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58217. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58218. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58219. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58220. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58221. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58222. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58223. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58224. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58225. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58226. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58227. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58228. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58229. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58230. // Emitter
  58231. if (parsedParticleSystem.particleEmitterType) {
  58232. var emitterType = void 0;
  58233. switch (parsedParticleSystem.particleEmitterType.type) {
  58234. case "SphereEmitter":
  58235. emitterType = new BABYLON.SphereParticleEmitter();
  58236. break;
  58237. case "SphereDirectedParticleEmitter":
  58238. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58239. break;
  58240. case "ConeEmitter":
  58241. emitterType = new BABYLON.ConeParticleEmitter();
  58242. break;
  58243. case "BoxEmitter":
  58244. default:
  58245. emitterType = new BABYLON.BoxParticleEmitter();
  58246. break;
  58247. }
  58248. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58249. particleSystem.particleEmitterType = emitterType;
  58250. }
  58251. return particleSystem;
  58252. };
  58253. return GPUParticleSystem;
  58254. }());
  58255. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58256. })(BABYLON || (BABYLON = {}));
  58257. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58258. var BABYLON;
  58259. (function (BABYLON) {
  58260. /**
  58261. * Represents one particle of a solid particle system.
  58262. */
  58263. var SolidParticle = /** @class */ (function () {
  58264. /**
  58265. * Creates a Solid Particle object.
  58266. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58267. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58268. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58269. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58270. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58271. * @param shapeId (integer) is the model shape identifier in the SPS.
  58272. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58273. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58274. */
  58275. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58276. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58277. /**
  58278. * particle global index
  58279. */
  58280. this.idx = 0;
  58281. /**
  58282. * The color of the particle
  58283. */
  58284. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58285. /**
  58286. * The world space position of the particle.
  58287. */
  58288. this.position = BABYLON.Vector3.Zero();
  58289. /**
  58290. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58291. */
  58292. this.rotation = BABYLON.Vector3.Zero();
  58293. /**
  58294. * The scaling of the particle.
  58295. */
  58296. this.scaling = BABYLON.Vector3.One();
  58297. /**
  58298. * The uvs of the particle.
  58299. */
  58300. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58301. /**
  58302. * The current speed of the particle.
  58303. */
  58304. this.velocity = BABYLON.Vector3.Zero();
  58305. /**
  58306. * The pivot point in the particle local space.
  58307. */
  58308. this.pivot = BABYLON.Vector3.Zero();
  58309. /**
  58310. * Must the particle be translated from its pivot point in its local space ?
  58311. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58312. * Default : false
  58313. */
  58314. this.translateFromPivot = false;
  58315. /**
  58316. * Is the particle active or not ?
  58317. */
  58318. this.alive = true;
  58319. /**
  58320. * Is the particle visible or not ?
  58321. */
  58322. this.isVisible = true;
  58323. /**
  58324. * Index of this particle in the global "positions" array (Internal use)
  58325. */
  58326. this._pos = 0;
  58327. /**
  58328. * Index of this particle in the global "indices" array (Internal use)
  58329. */
  58330. this._ind = 0;
  58331. /**
  58332. * ModelShape id of this particle
  58333. */
  58334. this.shapeId = 0;
  58335. /**
  58336. * Index of the particle in its shape id (Internal use)
  58337. */
  58338. this.idxInShape = 0;
  58339. /**
  58340. * Still set as invisible in order to skip useless computations (Internal use)
  58341. */
  58342. this._stillInvisible = false;
  58343. /**
  58344. * Last computed particle rotation matrix
  58345. */
  58346. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58347. /**
  58348. * Parent particle Id, if any.
  58349. * Default null.
  58350. */
  58351. this.parentId = null;
  58352. /**
  58353. * Internal global position in the SPS.
  58354. */
  58355. this._globalPosition = BABYLON.Vector3.Zero();
  58356. this.idx = particleIndex;
  58357. this._pos = positionIndex;
  58358. this._ind = indiceIndex;
  58359. this._model = model;
  58360. this.shapeId = shapeId;
  58361. this.idxInShape = idxInShape;
  58362. this._sps = sps;
  58363. if (modelBoundingInfo) {
  58364. this._modelBoundingInfo = modelBoundingInfo;
  58365. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58366. }
  58367. }
  58368. Object.defineProperty(SolidParticle.prototype, "scale", {
  58369. /**
  58370. * Legacy support, changed scale to scaling
  58371. */
  58372. get: function () {
  58373. return this.scaling;
  58374. },
  58375. /**
  58376. * Legacy support, changed scale to scaling
  58377. */
  58378. set: function (scale) {
  58379. this.scaling = scale;
  58380. },
  58381. enumerable: true,
  58382. configurable: true
  58383. });
  58384. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58385. /**
  58386. * Legacy support, changed quaternion to rotationQuaternion
  58387. */
  58388. get: function () {
  58389. return this.rotationQuaternion;
  58390. },
  58391. /**
  58392. * Legacy support, changed quaternion to rotationQuaternion
  58393. */
  58394. set: function (q) {
  58395. this.rotationQuaternion = q;
  58396. },
  58397. enumerable: true,
  58398. configurable: true
  58399. });
  58400. /**
  58401. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58402. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58403. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58404. * @returns true if it intersects
  58405. */
  58406. SolidParticle.prototype.intersectsMesh = function (target) {
  58407. if (!this._boundingInfo || !target._boundingInfo) {
  58408. return false;
  58409. }
  58410. if (this._sps._bSphereOnly) {
  58411. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58412. }
  58413. return this._boundingInfo.intersects(target._boundingInfo, false);
  58414. };
  58415. return SolidParticle;
  58416. }());
  58417. BABYLON.SolidParticle = SolidParticle;
  58418. /**
  58419. * Represents the shape of the model used by one particle of a solid particle system.
  58420. * SPS internal tool, don't use it manually.
  58421. */
  58422. var ModelShape = /** @class */ (function () {
  58423. /**
  58424. * 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.
  58425. * SPS internal tool, don't use it manually.
  58426. * @hidden
  58427. */
  58428. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58429. /**
  58430. * length of the shape in the model indices array (internal use)
  58431. */
  58432. this._indicesLength = 0;
  58433. this.shapeID = id;
  58434. this._shape = shape;
  58435. this._indicesLength = indicesLength;
  58436. this._shapeUV = shapeUV;
  58437. this._positionFunction = posFunction;
  58438. this._vertexFunction = vtxFunction;
  58439. }
  58440. return ModelShape;
  58441. }());
  58442. BABYLON.ModelShape = ModelShape;
  58443. /**
  58444. * Represents a Depth Sorted Particle in the solid particle system.
  58445. */
  58446. var DepthSortedParticle = /** @class */ (function () {
  58447. function DepthSortedParticle() {
  58448. /**
  58449. * Index of the particle in the "indices" array
  58450. */
  58451. this.ind = 0;
  58452. /**
  58453. * Length of the particle shape in the "indices" array
  58454. */
  58455. this.indicesLength = 0;
  58456. /**
  58457. * Squared distance from the particle to the camera
  58458. */
  58459. this.sqDistance = 0.0;
  58460. }
  58461. return DepthSortedParticle;
  58462. }());
  58463. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58464. })(BABYLON || (BABYLON = {}));
  58465. //# sourceMappingURL=babylon.solidParticle.js.map
  58466. var BABYLON;
  58467. (function (BABYLON) {
  58468. /**
  58469. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58470. *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.
  58471. * The SPS is also a particle system. It provides some methods to manage the particles.
  58472. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58473. *
  58474. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58475. */
  58476. var SolidParticleSystem = /** @class */ (function () {
  58477. /**
  58478. * Creates a SPS (Solid Particle System) object.
  58479. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58480. * @param scene (Scene) is the scene in which the SPS is added.
  58481. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58482. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58483. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58484. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58485. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58486. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58487. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58488. */
  58489. function SolidParticleSystem(name, scene, options) {
  58490. /**
  58491. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58492. * Example : var p = SPS.particles[i];
  58493. */
  58494. this.particles = new Array();
  58495. /**
  58496. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58497. */
  58498. this.nbParticles = 0;
  58499. /**
  58500. * If the particles must ever face the camera (default false). Useful for planar particles.
  58501. */
  58502. this.billboard = false;
  58503. /**
  58504. * Recompute normals when adding a shape
  58505. */
  58506. this.recomputeNormals = true;
  58507. /**
  58508. * This a counter ofr your own usage. It's not set by any SPS functions.
  58509. */
  58510. this.counter = 0;
  58511. /**
  58512. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58513. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58514. */
  58515. this.vars = {};
  58516. /**
  58517. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58518. */
  58519. this._bSphereOnly = false;
  58520. /**
  58521. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58522. */
  58523. this._bSphereRadiusFactor = 1.0;
  58524. this._positions = new Array();
  58525. this._indices = new Array();
  58526. this._normals = new Array();
  58527. this._colors = new Array();
  58528. this._uvs = new Array();
  58529. this._index = 0; // indices index
  58530. this._updatable = true;
  58531. this._pickable = false;
  58532. this._isVisibilityBoxLocked = false;
  58533. this._alwaysVisible = false;
  58534. this._depthSort = false;
  58535. this._shapeCounter = 0;
  58536. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58537. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58538. this._computeParticleColor = true;
  58539. this._computeParticleTexture = true;
  58540. this._computeParticleRotation = true;
  58541. this._computeParticleVertex = false;
  58542. this._computeBoundingBox = false;
  58543. this._depthSortParticles = true;
  58544. this._cam_axisZ = BABYLON.Vector3.Zero();
  58545. this._cam_axisY = BABYLON.Vector3.Zero();
  58546. this._cam_axisX = BABYLON.Vector3.Zero();
  58547. this._axisZ = BABYLON.Axis.Z;
  58548. this._camDir = BABYLON.Vector3.Zero();
  58549. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58550. this._rotMatrix = new BABYLON.Matrix();
  58551. this._invertMatrix = new BABYLON.Matrix();
  58552. this._rotated = BABYLON.Vector3.Zero();
  58553. this._quaternion = new BABYLON.Quaternion();
  58554. this._vertex = BABYLON.Vector3.Zero();
  58555. this._normal = BABYLON.Vector3.Zero();
  58556. this._yaw = 0.0;
  58557. this._pitch = 0.0;
  58558. this._roll = 0.0;
  58559. this._halfroll = 0.0;
  58560. this._halfpitch = 0.0;
  58561. this._halfyaw = 0.0;
  58562. this._sinRoll = 0.0;
  58563. this._cosRoll = 0.0;
  58564. this._sinPitch = 0.0;
  58565. this._cosPitch = 0.0;
  58566. this._sinYaw = 0.0;
  58567. this._cosYaw = 0.0;
  58568. this._mustUnrotateFixedNormals = false;
  58569. this._minimum = BABYLON.Vector3.Zero();
  58570. this._maximum = BABYLON.Vector3.Zero();
  58571. this._minBbox = BABYLON.Vector3.Zero();
  58572. this._maxBbox = BABYLON.Vector3.Zero();
  58573. this._particlesIntersect = false;
  58574. this._depthSortFunction = function (p1, p2) {
  58575. return (p2.sqDistance - p1.sqDistance);
  58576. };
  58577. this._needs32Bits = false;
  58578. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58579. this._scaledPivot = BABYLON.Vector3.Zero();
  58580. this._particleHasParent = false;
  58581. this.name = name;
  58582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58583. this._camera = scene.activeCamera;
  58584. this._pickable = options ? options.isPickable : false;
  58585. this._depthSort = options ? options.enableDepthSort : false;
  58586. this._particlesIntersect = options ? options.particleIntersection : false;
  58587. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58588. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58589. if (options && options.updatable) {
  58590. this._updatable = options.updatable;
  58591. }
  58592. else {
  58593. this._updatable = true;
  58594. }
  58595. if (this._pickable) {
  58596. this.pickedParticles = [];
  58597. }
  58598. if (this._depthSort) {
  58599. this.depthSortedParticles = [];
  58600. }
  58601. }
  58602. /**
  58603. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58604. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58605. * @returns the created mesh
  58606. */
  58607. SolidParticleSystem.prototype.buildMesh = function () {
  58608. if (this.nbParticles === 0) {
  58609. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58610. this.addShape(triangle, 1);
  58611. triangle.dispose();
  58612. }
  58613. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58614. this._positions32 = new Float32Array(this._positions);
  58615. this._uvs32 = new Float32Array(this._uvs);
  58616. this._colors32 = new Float32Array(this._colors);
  58617. if (this.recomputeNormals) {
  58618. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58619. }
  58620. this._normals32 = new Float32Array(this._normals);
  58621. this._fixedNormal32 = new Float32Array(this._normals);
  58622. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58623. this._unrotateFixedNormals();
  58624. }
  58625. var vertexData = new BABYLON.VertexData();
  58626. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58627. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58628. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58629. if (this._uvs32.length > 0) {
  58630. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58631. }
  58632. if (this._colors32.length > 0) {
  58633. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58634. }
  58635. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58636. vertexData.applyToMesh(mesh, this._updatable);
  58637. this.mesh = mesh;
  58638. this.mesh.isPickable = this._pickable;
  58639. // free memory
  58640. if (!this._depthSort) {
  58641. this._indices = null;
  58642. }
  58643. this._positions = null;
  58644. this._normals = null;
  58645. this._uvs = null;
  58646. this._colors = null;
  58647. if (!this._updatable) {
  58648. this.particles.length = 0;
  58649. }
  58650. return mesh;
  58651. };
  58652. /**
  58653. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58654. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58655. * Thus the particles generated from `digest()` have their property `position` set yet.
  58656. * @param mesh ( Mesh ) is the mesh to be digested
  58657. * @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
  58658. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58659. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58660. * @returns the current SPS
  58661. */
  58662. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58663. var size = (options && options.facetNb) || 1;
  58664. var number = (options && options.number) || 0;
  58665. var delta = (options && options.delta) || 0;
  58666. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58667. var meshInd = mesh.getIndices();
  58668. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58669. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58670. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58671. var f = 0; // facet counter
  58672. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58673. // compute size from number
  58674. if (number) {
  58675. number = (number > totalFacets) ? totalFacets : number;
  58676. size = Math.round(totalFacets / number);
  58677. delta = 0;
  58678. }
  58679. else {
  58680. size = (size > totalFacets) ? totalFacets : size;
  58681. }
  58682. var facetPos = []; // submesh positions
  58683. var facetInd = []; // submesh indices
  58684. var facetUV = []; // submesh UV
  58685. var facetCol = []; // submesh colors
  58686. var barycenter = BABYLON.Vector3.Zero();
  58687. var sizeO = size;
  58688. while (f < totalFacets) {
  58689. size = sizeO + Math.floor((1 + delta) * Math.random());
  58690. if (f > totalFacets - size) {
  58691. size = totalFacets - f;
  58692. }
  58693. // reset temp arrays
  58694. facetPos.length = 0;
  58695. facetInd.length = 0;
  58696. facetUV.length = 0;
  58697. facetCol.length = 0;
  58698. // iterate over "size" facets
  58699. var fi = 0;
  58700. for (var j = f * 3; j < (f + size) * 3; j++) {
  58701. facetInd.push(fi);
  58702. var i = meshInd[j];
  58703. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58704. if (meshUV) {
  58705. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58706. }
  58707. if (meshCol) {
  58708. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58709. }
  58710. fi++;
  58711. }
  58712. // create a model shape for each single particle
  58713. var idx = this.nbParticles;
  58714. var shape = this._posToShape(facetPos);
  58715. var shapeUV = this._uvsToShapeUV(facetUV);
  58716. // compute the barycenter of the shape
  58717. var v;
  58718. for (v = 0; v < shape.length; v++) {
  58719. barycenter.addInPlace(shape[v]);
  58720. }
  58721. barycenter.scaleInPlace(1 / shape.length);
  58722. // shift the shape from its barycenter to the origin
  58723. for (v = 0; v < shape.length; v++) {
  58724. shape[v].subtractInPlace(barycenter);
  58725. }
  58726. var bInfo;
  58727. if (this._particlesIntersect) {
  58728. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58729. }
  58730. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58731. // add the particle in the SPS
  58732. var currentPos = this._positions.length;
  58733. var currentInd = this._indices.length;
  58734. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58735. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58736. // initialize the particle position
  58737. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58738. this._index += shape.length;
  58739. idx++;
  58740. this.nbParticles++;
  58741. this._shapeCounter++;
  58742. f += size;
  58743. }
  58744. return this;
  58745. };
  58746. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58747. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58748. var index = 0;
  58749. var idx = 0;
  58750. for (var p = 0; p < this.particles.length; p++) {
  58751. this._particle = this.particles[p];
  58752. this._shape = this._particle._model._shape;
  58753. if (this._particle.rotationQuaternion) {
  58754. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58755. }
  58756. else {
  58757. this._yaw = this._particle.rotation.y;
  58758. this._pitch = this._particle.rotation.x;
  58759. this._roll = this._particle.rotation.z;
  58760. this._quaternionRotationYPR();
  58761. }
  58762. this._quaternionToRotationMatrix();
  58763. this._rotMatrix.invertToRef(this._invertMatrix);
  58764. for (var pt = 0; pt < this._shape.length; pt++) {
  58765. idx = index + pt * 3;
  58766. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58767. this._fixedNormal32[idx] = this._normal.x;
  58768. this._fixedNormal32[idx + 1] = this._normal.y;
  58769. this._fixedNormal32[idx + 2] = this._normal.z;
  58770. }
  58771. index = idx + 3;
  58772. }
  58773. };
  58774. //reset copy
  58775. SolidParticleSystem.prototype._resetCopy = function () {
  58776. this._copy.position.x = 0;
  58777. this._copy.position.y = 0;
  58778. this._copy.position.z = 0;
  58779. this._copy.rotation.x = 0;
  58780. this._copy.rotation.y = 0;
  58781. this._copy.rotation.z = 0;
  58782. this._copy.rotationQuaternion = null;
  58783. this._copy.scaling.x = 1.0;
  58784. this._copy.scaling.y = 1.0;
  58785. this._copy.scaling.z = 1.0;
  58786. this._copy.uvs.x = 0;
  58787. this._copy.uvs.y = 0;
  58788. this._copy.uvs.z = 1.0;
  58789. this._copy.uvs.w = 1.0;
  58790. this._copy.color = null;
  58791. this._copy.translateFromPivot = false;
  58792. };
  58793. // _meshBuilder : inserts the shape model in the global SPS mesh
  58794. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58795. var i;
  58796. var u = 0;
  58797. var c = 0;
  58798. var n = 0;
  58799. this._resetCopy();
  58800. if (options && options.positionFunction) { // call to custom positionFunction
  58801. options.positionFunction(this._copy, idx, idxInShape);
  58802. this._mustUnrotateFixedNormals = true;
  58803. }
  58804. if (this._copy.rotationQuaternion) {
  58805. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58806. }
  58807. else {
  58808. this._yaw = this._copy.rotation.y;
  58809. this._pitch = this._copy.rotation.x;
  58810. this._roll = this._copy.rotation.z;
  58811. this._quaternionRotationYPR();
  58812. }
  58813. this._quaternionToRotationMatrix();
  58814. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58815. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58816. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58817. if (this._copy.translateFromPivot) {
  58818. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58819. }
  58820. else {
  58821. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58822. }
  58823. for (i = 0; i < shape.length; i++) {
  58824. this._vertex.x = shape[i].x;
  58825. this._vertex.y = shape[i].y;
  58826. this._vertex.z = shape[i].z;
  58827. if (options && options.vertexFunction) {
  58828. options.vertexFunction(this._copy, this._vertex, i);
  58829. }
  58830. this._vertex.x *= this._copy.scaling.x;
  58831. this._vertex.y *= this._copy.scaling.y;
  58832. this._vertex.z *= this._copy.scaling.z;
  58833. this._vertex.x -= this._scaledPivot.x;
  58834. this._vertex.y -= this._scaledPivot.y;
  58835. this._vertex.z -= this._scaledPivot.z;
  58836. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58837. this._rotated.addInPlace(this._pivotBackTranslation);
  58838. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58839. if (meshUV) {
  58840. 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);
  58841. u += 2;
  58842. }
  58843. if (this._copy.color) {
  58844. this._color = this._copy.color;
  58845. }
  58846. else if (meshCol && meshCol[c] !== undefined) {
  58847. this._color.r = meshCol[c];
  58848. this._color.g = meshCol[c + 1];
  58849. this._color.b = meshCol[c + 2];
  58850. this._color.a = meshCol[c + 3];
  58851. }
  58852. else {
  58853. this._color.r = 1.0;
  58854. this._color.g = 1.0;
  58855. this._color.b = 1.0;
  58856. this._color.a = 1.0;
  58857. }
  58858. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58859. c += 4;
  58860. if (!this.recomputeNormals && meshNor) {
  58861. this._normal.x = meshNor[n];
  58862. this._normal.y = meshNor[n + 1];
  58863. this._normal.z = meshNor[n + 2];
  58864. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58865. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58866. n += 3;
  58867. }
  58868. }
  58869. for (i = 0; i < meshInd.length; i++) {
  58870. var current_ind = p + meshInd[i];
  58871. indices.push(current_ind);
  58872. if (current_ind > 65535) {
  58873. this._needs32Bits = true;
  58874. }
  58875. }
  58876. if (this._pickable) {
  58877. var nbfaces = meshInd.length / 3;
  58878. for (i = 0; i < nbfaces; i++) {
  58879. this.pickedParticles.push({ idx: idx, faceId: i });
  58880. }
  58881. }
  58882. if (this._depthSort) {
  58883. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58884. }
  58885. return this._copy;
  58886. };
  58887. // returns a shape array from positions array
  58888. SolidParticleSystem.prototype._posToShape = function (positions) {
  58889. var shape = [];
  58890. for (var i = 0; i < positions.length; i += 3) {
  58891. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58892. }
  58893. return shape;
  58894. };
  58895. // returns a shapeUV array from a Vector4 uvs
  58896. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58897. var shapeUV = [];
  58898. if (uvs) {
  58899. for (var i = 0; i < uvs.length; i++)
  58900. shapeUV.push(uvs[i]);
  58901. }
  58902. return shapeUV;
  58903. };
  58904. // adds a new particle object in the particles array
  58905. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58906. if (bInfo === void 0) { bInfo = null; }
  58907. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58908. this.particles.push(sp);
  58909. return sp;
  58910. };
  58911. /**
  58912. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58913. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58914. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58915. * @param nb (positive integer) the number of particles to be created from this model
  58916. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58917. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58918. * @returns the number of shapes in the system
  58919. */
  58920. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58921. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58922. var meshInd = mesh.getIndices();
  58923. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58924. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58925. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58926. var bbInfo;
  58927. if (this._particlesIntersect) {
  58928. bbInfo = mesh.getBoundingInfo();
  58929. }
  58930. var shape = this._posToShape(meshPos);
  58931. var shapeUV = this._uvsToShapeUV(meshUV);
  58932. var posfunc = options ? options.positionFunction : null;
  58933. var vtxfunc = options ? options.vertexFunction : null;
  58934. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58935. // particles
  58936. var sp;
  58937. var currentCopy;
  58938. var idx = this.nbParticles;
  58939. for (var i = 0; i < nb; i++) {
  58940. var currentPos = this._positions.length;
  58941. var currentInd = this._indices.length;
  58942. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58943. if (this._updatable) {
  58944. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58945. sp.position.copyFrom(currentCopy.position);
  58946. sp.rotation.copyFrom(currentCopy.rotation);
  58947. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58948. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58949. }
  58950. if (currentCopy.color && sp.color) {
  58951. sp.color.copyFrom(currentCopy.color);
  58952. }
  58953. sp.scaling.copyFrom(currentCopy.scaling);
  58954. sp.uvs.copyFrom(currentCopy.uvs);
  58955. }
  58956. this._index += shape.length;
  58957. idx++;
  58958. }
  58959. this.nbParticles += nb;
  58960. this._shapeCounter++;
  58961. return this._shapeCounter - 1;
  58962. };
  58963. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58964. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58965. this._resetCopy();
  58966. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58967. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58968. }
  58969. if (this._copy.rotationQuaternion) {
  58970. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58971. }
  58972. else {
  58973. this._yaw = this._copy.rotation.y;
  58974. this._pitch = this._copy.rotation.x;
  58975. this._roll = this._copy.rotation.z;
  58976. this._quaternionRotationYPR();
  58977. }
  58978. this._quaternionToRotationMatrix();
  58979. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58980. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58981. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58982. if (this._copy.translateFromPivot) {
  58983. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58984. }
  58985. else {
  58986. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58987. }
  58988. this._shape = particle._model._shape;
  58989. for (var pt = 0; pt < this._shape.length; pt++) {
  58990. this._vertex.x = this._shape[pt].x;
  58991. this._vertex.y = this._shape[pt].y;
  58992. this._vertex.z = this._shape[pt].z;
  58993. if (particle._model._vertexFunction) {
  58994. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58995. }
  58996. this._vertex.x *= this._copy.scaling.x;
  58997. this._vertex.y *= this._copy.scaling.y;
  58998. this._vertex.z *= this._copy.scaling.z;
  58999. this._vertex.x -= this._scaledPivot.x;
  59000. this._vertex.y -= this._scaledPivot.y;
  59001. this._vertex.z -= this._scaledPivot.z;
  59002. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59003. this._rotated.addInPlace(this._pivotBackTranslation);
  59004. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59005. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59006. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59007. }
  59008. particle.position.x = 0.0;
  59009. particle.position.y = 0.0;
  59010. particle.position.z = 0.0;
  59011. particle.rotation.x = 0.0;
  59012. particle.rotation.y = 0.0;
  59013. particle.rotation.z = 0.0;
  59014. particle.rotationQuaternion = null;
  59015. particle.scaling.x = 1.0;
  59016. particle.scaling.y = 1.0;
  59017. particle.scaling.z = 1.0;
  59018. particle.uvs.x = 0.0;
  59019. particle.uvs.y = 0.0;
  59020. particle.uvs.z = 1.0;
  59021. particle.uvs.w = 1.0;
  59022. particle.pivot.x = 0.0;
  59023. particle.pivot.y = 0.0;
  59024. particle.pivot.z = 0.0;
  59025. particle.translateFromPivot = false;
  59026. particle.parentId = null;
  59027. };
  59028. /**
  59029. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59030. * @returns the SPS.
  59031. */
  59032. SolidParticleSystem.prototype.rebuildMesh = function () {
  59033. for (var p = 0; p < this.particles.length; p++) {
  59034. this._rebuildParticle(this.particles[p]);
  59035. }
  59036. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59037. return this;
  59038. };
  59039. /**
  59040. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59041. * This method calls `updateParticle()` for each particle of the SPS.
  59042. * For an animated SPS, it is usually called within the render loop.
  59043. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59044. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59045. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59046. * @returns the SPS.
  59047. */
  59048. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59049. if (start === void 0) { start = 0; }
  59050. if (end === void 0) { end = this.nbParticles - 1; }
  59051. if (update === void 0) { update = true; }
  59052. if (!this._updatable) {
  59053. return this;
  59054. }
  59055. // custom beforeUpdate
  59056. this.beforeUpdateParticles(start, end, update);
  59057. this._cam_axisX.x = 1.0;
  59058. this._cam_axisX.y = 0.0;
  59059. this._cam_axisX.z = 0.0;
  59060. this._cam_axisY.x = 0.0;
  59061. this._cam_axisY.y = 1.0;
  59062. this._cam_axisY.z = 0.0;
  59063. this._cam_axisZ.x = 0.0;
  59064. this._cam_axisZ.y = 0.0;
  59065. this._cam_axisZ.z = 1.0;
  59066. // cases when the World Matrix is to be computed first
  59067. if (this.billboard || this._depthSort) {
  59068. this.mesh.computeWorldMatrix(true);
  59069. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59070. }
  59071. // if the particles will always face the camera
  59072. if (this.billboard) {
  59073. // compute the camera position and un-rotate it by the current mesh rotation
  59074. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59075. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59076. this._cam_axisZ.normalize();
  59077. // same for camera up vector extracted from the cam view matrix
  59078. var view = this._camera.getViewMatrix(true);
  59079. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59080. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59081. this._cam_axisY.normalize();
  59082. this._cam_axisX.normalize();
  59083. }
  59084. // if depthSort, compute the camera global position in the mesh local system
  59085. if (this._depthSort) {
  59086. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59087. }
  59088. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59089. var idx = 0; // current position index in the global array positions32
  59090. var index = 0; // position start index in the global array positions32 of the current particle
  59091. var colidx = 0; // current color index in the global array colors32
  59092. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59093. var uvidx = 0; // current uv index in the global array uvs32
  59094. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59095. var pt = 0; // current index in the particle model shape
  59096. if (this.mesh.isFacetDataEnabled) {
  59097. this._computeBoundingBox = true;
  59098. }
  59099. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59100. if (this._computeBoundingBox) {
  59101. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59102. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59103. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59104. }
  59105. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59106. if (this.mesh._boundingInfo) {
  59107. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59108. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59109. }
  59110. }
  59111. }
  59112. // particle loop
  59113. index = this.particles[start]._pos;
  59114. var vpos = (index / 3) | 0;
  59115. colorIndex = vpos * 4;
  59116. uvIndex = vpos * 2;
  59117. for (var p = start; p <= end; p++) {
  59118. this._particle = this.particles[p];
  59119. this._shape = this._particle._model._shape;
  59120. this._shapeUV = this._particle._model._shapeUV;
  59121. // call to custom user function to update the particle properties
  59122. this.updateParticle(this._particle);
  59123. // camera-particle distance for depth sorting
  59124. if (this._depthSort && this._depthSortParticles) {
  59125. var dsp = this.depthSortedParticles[p];
  59126. dsp.ind = this._particle._ind;
  59127. dsp.indicesLength = this._particle._model._indicesLength;
  59128. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59129. }
  59130. // skip the computations for inactive or already invisible particles
  59131. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59132. // increment indexes for the next particle
  59133. pt = this._shape.length;
  59134. index += pt * 3;
  59135. colorIndex += pt * 4;
  59136. uvIndex += pt * 2;
  59137. continue;
  59138. }
  59139. if (this._particle.isVisible) {
  59140. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59141. this._particleHasParent = (this._particle.parentId !== null);
  59142. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59143. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59144. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59145. // particle rotation matrix
  59146. if (this.billboard) {
  59147. this._particle.rotation.x = 0.0;
  59148. this._particle.rotation.y = 0.0;
  59149. }
  59150. if (this._computeParticleRotation || this.billboard) {
  59151. if (this._particle.rotationQuaternion) {
  59152. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59153. }
  59154. else {
  59155. this._yaw = this._particle.rotation.y;
  59156. this._pitch = this._particle.rotation.x;
  59157. this._roll = this._particle.rotation.z;
  59158. this._quaternionRotationYPR();
  59159. }
  59160. this._quaternionToRotationMatrix();
  59161. }
  59162. if (this._particleHasParent) {
  59163. this._parent = this.particles[this._particle.parentId];
  59164. 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];
  59165. 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];
  59166. 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];
  59167. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59168. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59169. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59170. if (this._computeParticleRotation || this.billboard) {
  59171. 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];
  59172. 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];
  59173. 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];
  59174. 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];
  59175. 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];
  59176. 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];
  59177. 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];
  59178. 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];
  59179. 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];
  59180. }
  59181. }
  59182. else {
  59183. this._particle._globalPosition.x = this._particle.position.x;
  59184. this._particle._globalPosition.y = this._particle.position.y;
  59185. this._particle._globalPosition.z = this._particle.position.z;
  59186. if (this._computeParticleRotation || this.billboard) {
  59187. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59188. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59189. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59190. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59191. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59192. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59193. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59194. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59195. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59196. }
  59197. }
  59198. if (this._particle.translateFromPivot) {
  59199. this._pivotBackTranslation.x = 0.0;
  59200. this._pivotBackTranslation.y = 0.0;
  59201. this._pivotBackTranslation.z = 0.0;
  59202. }
  59203. else {
  59204. this._pivotBackTranslation.x = this._scaledPivot.x;
  59205. this._pivotBackTranslation.y = this._scaledPivot.y;
  59206. this._pivotBackTranslation.z = this._scaledPivot.z;
  59207. }
  59208. // particle vertex loop
  59209. for (pt = 0; pt < this._shape.length; pt++) {
  59210. idx = index + pt * 3;
  59211. colidx = colorIndex + pt * 4;
  59212. uvidx = uvIndex + pt * 2;
  59213. this._vertex.x = this._shape[pt].x;
  59214. this._vertex.y = this._shape[pt].y;
  59215. this._vertex.z = this._shape[pt].z;
  59216. if (this._computeParticleVertex) {
  59217. this.updateParticleVertex(this._particle, this._vertex, pt);
  59218. }
  59219. // positions
  59220. this._vertex.x *= this._particle.scaling.x;
  59221. this._vertex.y *= this._particle.scaling.y;
  59222. this._vertex.z *= this._particle.scaling.z;
  59223. this._vertex.x -= this._scaledPivot.x;
  59224. this._vertex.y -= this._scaledPivot.y;
  59225. this._vertex.z -= this._scaledPivot.z;
  59226. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59227. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59228. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59229. this._rotated.x += this._pivotBackTranslation.x;
  59230. this._rotated.y += this._pivotBackTranslation.y;
  59231. this._rotated.z += this._pivotBackTranslation.z;
  59232. 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;
  59233. 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;
  59234. 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;
  59235. if (this._computeBoundingBox) {
  59236. if (this._positions32[idx] < this._minimum.x) {
  59237. this._minimum.x = this._positions32[idx];
  59238. }
  59239. if (this._positions32[idx] > this._maximum.x) {
  59240. this._maximum.x = this._positions32[idx];
  59241. }
  59242. if (this._positions32[idx + 1] < this._minimum.y) {
  59243. this._minimum.y = this._positions32[idx + 1];
  59244. }
  59245. if (this._positions32[idx + 1] > this._maximum.y) {
  59246. this._maximum.y = this._positions32[idx + 1];
  59247. }
  59248. if (this._positions32[idx + 2] < this._minimum.z) {
  59249. this._minimum.z = this._positions32[idx + 2];
  59250. }
  59251. if (this._positions32[idx + 2] > this._maximum.z) {
  59252. this._maximum.z = this._positions32[idx + 2];
  59253. }
  59254. }
  59255. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59256. if (!this._computeParticleVertex) {
  59257. this._normal.x = this._fixedNormal32[idx];
  59258. this._normal.y = this._fixedNormal32[idx + 1];
  59259. this._normal.z = this._fixedNormal32[idx + 2];
  59260. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59261. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59262. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59263. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59264. 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;
  59265. 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;
  59266. }
  59267. if (this._computeParticleColor && this._particle.color) {
  59268. this._colors32[colidx] = this._particle.color.r;
  59269. this._colors32[colidx + 1] = this._particle.color.g;
  59270. this._colors32[colidx + 2] = this._particle.color.b;
  59271. this._colors32[colidx + 3] = this._particle.color.a;
  59272. }
  59273. if (this._computeParticleTexture) {
  59274. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59275. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59276. }
  59277. }
  59278. }
  59279. // particle just set invisible : scaled to zero and positioned at the origin
  59280. else {
  59281. this._particle._stillInvisible = true; // mark the particle as invisible
  59282. for (pt = 0; pt < this._shape.length; pt++) {
  59283. idx = index + pt * 3;
  59284. colidx = colorIndex + pt * 4;
  59285. uvidx = uvIndex + pt * 2;
  59286. this._positions32[idx] = 0.0;
  59287. this._positions32[idx + 1] = 0.0;
  59288. this._positions32[idx + 2] = 0.0;
  59289. this._normals32[idx] = 0.0;
  59290. this._normals32[idx + 1] = 0.0;
  59291. this._normals32[idx + 2] = 0.0;
  59292. if (this._computeParticleColor && this._particle.color) {
  59293. this._colors32[colidx] = this._particle.color.r;
  59294. this._colors32[colidx + 1] = this._particle.color.g;
  59295. this._colors32[colidx + 2] = this._particle.color.b;
  59296. this._colors32[colidx + 3] = this._particle.color.a;
  59297. }
  59298. if (this._computeParticleTexture) {
  59299. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59300. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59301. }
  59302. }
  59303. }
  59304. // if the particle intersections must be computed : update the bbInfo
  59305. if (this._particlesIntersect) {
  59306. var bInfo = this._particle._boundingInfo;
  59307. var bBox = bInfo.boundingBox;
  59308. var bSphere = bInfo.boundingSphere;
  59309. if (!this._bSphereOnly) {
  59310. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59311. for (var b = 0; b < bBox.vectors.length; b++) {
  59312. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59313. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59314. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59315. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59316. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59317. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59318. 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;
  59319. 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;
  59320. 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;
  59321. }
  59322. bBox._update(this.mesh._worldMatrix);
  59323. }
  59324. // place and scale the particle bouding sphere in the SPS local system, then update it
  59325. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59326. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59327. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59328. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59329. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59330. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59331. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59332. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59333. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59334. 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));
  59335. bSphere._update(this.mesh._worldMatrix);
  59336. }
  59337. // increment indexes for the next particle
  59338. index = idx + 3;
  59339. colorIndex = colidx + 4;
  59340. uvIndex = uvidx + 2;
  59341. }
  59342. // if the VBO must be updated
  59343. if (update) {
  59344. if (this._computeParticleColor) {
  59345. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59346. }
  59347. if (this._computeParticleTexture) {
  59348. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59349. }
  59350. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59351. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59352. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59353. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59354. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59355. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59356. for (var i = 0; i < this._normals32.length; i++) {
  59357. this._fixedNormal32[i] = this._normals32[i];
  59358. }
  59359. }
  59360. if (!this.mesh.areNormalsFrozen) {
  59361. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59362. }
  59363. }
  59364. if (this._depthSort && this._depthSortParticles) {
  59365. this.depthSortedParticles.sort(this._depthSortFunction);
  59366. var dspl = this.depthSortedParticles.length;
  59367. var sorted = 0;
  59368. var lind = 0;
  59369. var sind = 0;
  59370. var sid = 0;
  59371. for (sorted = 0; sorted < dspl; sorted++) {
  59372. lind = this.depthSortedParticles[sorted].indicesLength;
  59373. sind = this.depthSortedParticles[sorted].ind;
  59374. for (var i = 0; i < lind; i++) {
  59375. this._indices32[sid] = this._indices[sind + i];
  59376. sid++;
  59377. }
  59378. }
  59379. this.mesh.updateIndices(this._indices32);
  59380. }
  59381. }
  59382. if (this._computeBoundingBox) {
  59383. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59384. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59385. }
  59386. this.afterUpdateParticles(start, end, update);
  59387. return this;
  59388. };
  59389. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59390. this._halfroll = this._roll * 0.5;
  59391. this._halfpitch = this._pitch * 0.5;
  59392. this._halfyaw = this._yaw * 0.5;
  59393. this._sinRoll = Math.sin(this._halfroll);
  59394. this._cosRoll = Math.cos(this._halfroll);
  59395. this._sinPitch = Math.sin(this._halfpitch);
  59396. this._cosPitch = Math.cos(this._halfpitch);
  59397. this._sinYaw = Math.sin(this._halfyaw);
  59398. this._cosYaw = Math.cos(this._halfyaw);
  59399. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59400. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59401. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59402. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59403. };
  59404. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59405. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59406. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59407. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59408. this._rotMatrix.m[3] = 0;
  59409. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59410. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59411. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59412. this._rotMatrix.m[7] = 0;
  59413. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59414. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59415. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59416. this._rotMatrix.m[11] = 0;
  59417. this._rotMatrix.m[12] = 0;
  59418. this._rotMatrix.m[13] = 0;
  59419. this._rotMatrix.m[14] = 0;
  59420. this._rotMatrix.m[15] = 1.0;
  59421. };
  59422. /**
  59423. * Disposes the SPS.
  59424. */
  59425. SolidParticleSystem.prototype.dispose = function () {
  59426. this.mesh.dispose();
  59427. this.vars = null;
  59428. // drop references to internal big arrays for the GC
  59429. this._positions = null;
  59430. this._indices = null;
  59431. this._normals = null;
  59432. this._uvs = null;
  59433. this._colors = null;
  59434. this._indices32 = null;
  59435. this._positions32 = null;
  59436. this._normals32 = null;
  59437. this._fixedNormal32 = null;
  59438. this._uvs32 = null;
  59439. this._colors32 = null;
  59440. this.pickedParticles = null;
  59441. };
  59442. /**
  59443. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59444. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59445. * @returns the SPS.
  59446. */
  59447. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59448. if (!this._isVisibilityBoxLocked) {
  59449. this.mesh.refreshBoundingInfo();
  59450. }
  59451. return this;
  59452. };
  59453. /**
  59454. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59455. * @param size the size (float) of the visibility box
  59456. * note : this doesn't lock the SPS mesh bounding box.
  59457. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59458. */
  59459. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59460. var vis = size / 2;
  59461. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59462. };
  59463. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59464. /**
  59465. * Gets whether the SPS as always visible or not
  59466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59467. */
  59468. get: function () {
  59469. return this._alwaysVisible;
  59470. },
  59471. /**
  59472. * Sets the SPS as always visible or not
  59473. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59474. */
  59475. set: function (val) {
  59476. this._alwaysVisible = val;
  59477. this.mesh.alwaysSelectAsActiveMesh = val;
  59478. },
  59479. enumerable: true,
  59480. configurable: true
  59481. });
  59482. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59483. /**
  59484. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59485. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59486. */
  59487. get: function () {
  59488. return this._isVisibilityBoxLocked;
  59489. },
  59490. /**
  59491. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59492. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59493. */
  59494. set: function (val) {
  59495. this._isVisibilityBoxLocked = val;
  59496. var boundingInfo = this.mesh.getBoundingInfo();
  59497. boundingInfo.isLocked = val;
  59498. },
  59499. enumerable: true,
  59500. configurable: true
  59501. });
  59502. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59503. /**
  59504. * Gets if `setParticles()` computes the particle rotations or not.
  59505. * Default value : true. The SPS is faster when it's set to false.
  59506. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59507. */
  59508. get: function () {
  59509. return this._computeParticleRotation;
  59510. },
  59511. /**
  59512. * Tells to `setParticles()` to compute the particle rotations or not.
  59513. * Default value : true. The SPS is faster when it's set to false.
  59514. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59515. */
  59516. set: function (val) {
  59517. this._computeParticleRotation = val;
  59518. },
  59519. enumerable: true,
  59520. configurable: true
  59521. });
  59522. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59523. /**
  59524. * Gets if `setParticles()` computes the particle colors or not.
  59525. * Default value : true. The SPS is faster when it's set to false.
  59526. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59527. */
  59528. get: function () {
  59529. return this._computeParticleColor;
  59530. },
  59531. /**
  59532. * Tells to `setParticles()` to compute the particle colors or not.
  59533. * Default value : true. The SPS is faster when it's set to false.
  59534. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59535. */
  59536. set: function (val) {
  59537. this._computeParticleColor = val;
  59538. },
  59539. enumerable: true,
  59540. configurable: true
  59541. });
  59542. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59543. /**
  59544. * Gets if `setParticles()` computes the particle textures or not.
  59545. * Default value : true. The SPS is faster when it's set to false.
  59546. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59547. */
  59548. get: function () {
  59549. return this._computeParticleTexture;
  59550. },
  59551. set: function (val) {
  59552. this._computeParticleTexture = val;
  59553. },
  59554. enumerable: true,
  59555. configurable: true
  59556. });
  59557. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59558. /**
  59559. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59560. * Default value : false. The SPS is faster when it's set to false.
  59561. * Note : the particle custom vertex positions aren't stored values.
  59562. */
  59563. get: function () {
  59564. return this._computeParticleVertex;
  59565. },
  59566. /**
  59567. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59568. * Default value : false. The SPS is faster when it's set to false.
  59569. * Note : the particle custom vertex positions aren't stored values.
  59570. */
  59571. set: function (val) {
  59572. this._computeParticleVertex = val;
  59573. },
  59574. enumerable: true,
  59575. configurable: true
  59576. });
  59577. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59578. /**
  59579. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59580. */
  59581. get: function () {
  59582. return this._computeBoundingBox;
  59583. },
  59584. /**
  59585. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59586. */
  59587. set: function (val) {
  59588. this._computeBoundingBox = val;
  59589. },
  59590. enumerable: true,
  59591. configurable: true
  59592. });
  59593. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59594. /**
  59595. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59596. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59597. * Default : `true`
  59598. */
  59599. get: function () {
  59600. return this._depthSortParticles;
  59601. },
  59602. /**
  59603. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59604. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59605. * Default : `true`
  59606. */
  59607. set: function (val) {
  59608. this._depthSortParticles = val;
  59609. },
  59610. enumerable: true,
  59611. configurable: true
  59612. });
  59613. // =======================================================================
  59614. // Particle behavior logic
  59615. // these following methods may be overwritten by the user to fit his needs
  59616. /**
  59617. * This function does nothing. It may be overwritten to set all the particle first values.
  59618. * The SPS doesn't call this function, you may have to call it by your own.
  59619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59620. */
  59621. SolidParticleSystem.prototype.initParticles = function () {
  59622. };
  59623. /**
  59624. * This function does nothing. It may be overwritten to recycle a particle.
  59625. * The SPS doesn't call this function, you may have to call it by your own.
  59626. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59627. * @param particle The particle to recycle
  59628. * @returns the recycled particle
  59629. */
  59630. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59631. return particle;
  59632. };
  59633. /**
  59634. * Updates a particle : this function should be overwritten by the user.
  59635. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59636. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59637. * @example : just set a particle position or velocity and recycle conditions
  59638. * @param particle The particle to update
  59639. * @returns the updated particle
  59640. */
  59641. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59642. return particle;
  59643. };
  59644. /**
  59645. * Updates a vertex of a particle : it can be overwritten by the user.
  59646. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59647. * @param particle the current particle
  59648. * @param vertex the current index of the current particle
  59649. * @param pt the index of the current vertex in the particle shape
  59650. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59651. * @example : just set a vertex particle position
  59652. * @returns the updated vertex
  59653. */
  59654. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59655. return vertex;
  59656. };
  59657. /**
  59658. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59659. * This does nothing and may be overwritten by the user.
  59660. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59661. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59662. * @param update the boolean update value actually passed to setParticles()
  59663. */
  59664. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59665. };
  59666. /**
  59667. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59668. * This will be passed three parameters.
  59669. * This does nothing and may be overwritten by the user.
  59670. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59671. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59672. * @param update the boolean update value actually passed to setParticles()
  59673. */
  59674. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59675. };
  59676. return SolidParticleSystem;
  59677. }());
  59678. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59679. })(BABYLON || (BABYLON = {}));
  59680. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59681. var BABYLON;
  59682. (function (BABYLON) {
  59683. var ShaderMaterial = /** @class */ (function (_super) {
  59684. __extends(ShaderMaterial, _super);
  59685. function ShaderMaterial(name, scene, shaderPath, options) {
  59686. var _this = _super.call(this, name, scene) || this;
  59687. _this._textures = {};
  59688. _this._textureArrays = {};
  59689. _this._floats = {};
  59690. _this._ints = {};
  59691. _this._floatsArrays = {};
  59692. _this._colors3 = {};
  59693. _this._colors3Arrays = {};
  59694. _this._colors4 = {};
  59695. _this._vectors2 = {};
  59696. _this._vectors3 = {};
  59697. _this._vectors4 = {};
  59698. _this._matrices = {};
  59699. _this._matrices3x3 = {};
  59700. _this._matrices2x2 = {};
  59701. _this._vectors2Arrays = {};
  59702. _this._vectors3Arrays = {};
  59703. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59704. _this._shaderPath = shaderPath;
  59705. options.needAlphaBlending = options.needAlphaBlending || false;
  59706. options.needAlphaTesting = options.needAlphaTesting || false;
  59707. options.attributes = options.attributes || ["position", "normal", "uv"];
  59708. options.uniforms = options.uniforms || ["worldViewProjection"];
  59709. options.uniformBuffers = options.uniformBuffers || [];
  59710. options.samplers = options.samplers || [];
  59711. options.defines = options.defines || [];
  59712. _this._options = options;
  59713. return _this;
  59714. }
  59715. ShaderMaterial.prototype.getClassName = function () {
  59716. return "ShaderMaterial";
  59717. };
  59718. ShaderMaterial.prototype.needAlphaBlending = function () {
  59719. return this._options.needAlphaBlending;
  59720. };
  59721. ShaderMaterial.prototype.needAlphaTesting = function () {
  59722. return this._options.needAlphaTesting;
  59723. };
  59724. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59725. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59726. this._options.uniforms.push(uniformName);
  59727. }
  59728. };
  59729. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59730. if (this._options.samplers.indexOf(name) === -1) {
  59731. this._options.samplers.push(name);
  59732. }
  59733. this._textures[name] = texture;
  59734. return this;
  59735. };
  59736. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59737. if (this._options.samplers.indexOf(name) === -1) {
  59738. this._options.samplers.push(name);
  59739. }
  59740. this._checkUniform(name);
  59741. this._textureArrays[name] = textures;
  59742. return this;
  59743. };
  59744. ShaderMaterial.prototype.setFloat = function (name, value) {
  59745. this._checkUniform(name);
  59746. this._floats[name] = value;
  59747. return this;
  59748. };
  59749. ShaderMaterial.prototype.setInt = function (name, value) {
  59750. this._checkUniform(name);
  59751. this._ints[name] = value;
  59752. return this;
  59753. };
  59754. ShaderMaterial.prototype.setFloats = function (name, value) {
  59755. this._checkUniform(name);
  59756. this._floatsArrays[name] = value;
  59757. return this;
  59758. };
  59759. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59760. this._checkUniform(name);
  59761. this._colors3[name] = value;
  59762. return this;
  59763. };
  59764. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59765. this._checkUniform(name);
  59766. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59767. color.toArray(arr, arr.length);
  59768. return arr;
  59769. }, []);
  59770. return this;
  59771. };
  59772. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59773. this._checkUniform(name);
  59774. this._colors4[name] = value;
  59775. return this;
  59776. };
  59777. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59778. this._checkUniform(name);
  59779. this._vectors2[name] = value;
  59780. return this;
  59781. };
  59782. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59783. this._checkUniform(name);
  59784. this._vectors3[name] = value;
  59785. return this;
  59786. };
  59787. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59788. this._checkUniform(name);
  59789. this._vectors4[name] = value;
  59790. return this;
  59791. };
  59792. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59793. this._checkUniform(name);
  59794. this._matrices[name] = value;
  59795. return this;
  59796. };
  59797. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59798. this._checkUniform(name);
  59799. this._matrices3x3[name] = value;
  59800. return this;
  59801. };
  59802. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59803. this._checkUniform(name);
  59804. this._matrices2x2[name] = value;
  59805. return this;
  59806. };
  59807. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59808. this._checkUniform(name);
  59809. this._vectors2Arrays[name] = value;
  59810. return this;
  59811. };
  59812. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59813. this._checkUniform(name);
  59814. this._vectors3Arrays[name] = value;
  59815. return this;
  59816. };
  59817. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59818. if (!mesh) {
  59819. return true;
  59820. }
  59821. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59822. return false;
  59823. }
  59824. return false;
  59825. };
  59826. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59827. var scene = this.getScene();
  59828. var engine = scene.getEngine();
  59829. if (!this.checkReadyOnEveryCall) {
  59830. if (this._renderId === scene.getRenderId()) {
  59831. if (this._checkCache(scene, mesh, useInstances)) {
  59832. return true;
  59833. }
  59834. }
  59835. }
  59836. // Instances
  59837. var defines = [];
  59838. var attribs = [];
  59839. var fallbacks = new BABYLON.EffectFallbacks();
  59840. if (useInstances) {
  59841. defines.push("#define INSTANCES");
  59842. }
  59843. for (var index = 0; index < this._options.defines.length; index++) {
  59844. defines.push(this._options.defines[index]);
  59845. }
  59846. for (var index = 0; index < this._options.attributes.length; index++) {
  59847. attribs.push(this._options.attributes[index]);
  59848. }
  59849. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59850. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59851. defines.push("#define VERTEXCOLOR");
  59852. }
  59853. // Bones
  59854. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59857. if (mesh.numBoneInfluencers > 4) {
  59858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59860. }
  59861. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59862. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59863. fallbacks.addCPUSkinningFallback(0, mesh);
  59864. if (this._options.uniforms.indexOf("mBones") === -1) {
  59865. this._options.uniforms.push("mBones");
  59866. }
  59867. }
  59868. else {
  59869. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59870. }
  59871. // Textures
  59872. for (var name in this._textures) {
  59873. if (!this._textures[name].isReady()) {
  59874. return false;
  59875. }
  59876. }
  59877. // Alpha test
  59878. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59879. defines.push("#define ALPHATEST");
  59880. }
  59881. var previousEffect = this._effect;
  59882. var join = defines.join("\n");
  59883. this._effect = engine.createEffect(this._shaderPath, {
  59884. attributes: attribs,
  59885. uniformsNames: this._options.uniforms,
  59886. uniformBuffersNames: this._options.uniformBuffers,
  59887. samplers: this._options.samplers,
  59888. defines: join,
  59889. fallbacks: fallbacks,
  59890. onCompiled: this.onCompiled,
  59891. onError: this.onError
  59892. }, engine);
  59893. if (!this._effect.isReady()) {
  59894. return false;
  59895. }
  59896. if (previousEffect !== this._effect) {
  59897. scene.resetCachedMaterial();
  59898. }
  59899. this._renderId = scene.getRenderId();
  59900. return true;
  59901. };
  59902. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59903. var scene = this.getScene();
  59904. if (!this._effect) {
  59905. return;
  59906. }
  59907. if (this._options.uniforms.indexOf("world") !== -1) {
  59908. this._effect.setMatrix("world", world);
  59909. }
  59910. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59911. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59912. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59913. }
  59914. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59915. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59916. }
  59917. };
  59918. ShaderMaterial.prototype.bind = function (world, mesh) {
  59919. // Std values
  59920. this.bindOnlyWorldMatrix(world);
  59921. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59922. if (this._options.uniforms.indexOf("view") !== -1) {
  59923. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59924. }
  59925. if (this._options.uniforms.indexOf("projection") !== -1) {
  59926. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59927. }
  59928. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59929. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59930. }
  59931. // Bones
  59932. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59933. var name;
  59934. // Texture
  59935. for (name in this._textures) {
  59936. this._effect.setTexture(name, this._textures[name]);
  59937. }
  59938. // Texture arrays
  59939. for (name in this._textureArrays) {
  59940. this._effect.setTextureArray(name, this._textureArrays[name]);
  59941. }
  59942. // Int
  59943. for (name in this._ints) {
  59944. this._effect.setInt(name, this._ints[name]);
  59945. }
  59946. // Float
  59947. for (name in this._floats) {
  59948. this._effect.setFloat(name, this._floats[name]);
  59949. }
  59950. // Floats
  59951. for (name in this._floatsArrays) {
  59952. this._effect.setArray(name, this._floatsArrays[name]);
  59953. }
  59954. // Color3
  59955. for (name in this._colors3) {
  59956. this._effect.setColor3(name, this._colors3[name]);
  59957. }
  59958. for (name in this._colors3Arrays) {
  59959. this._effect.setArray3(name, this._colors3Arrays[name]);
  59960. }
  59961. // Color4
  59962. for (name in this._colors4) {
  59963. var color = this._colors4[name];
  59964. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59965. }
  59966. // Vector2
  59967. for (name in this._vectors2) {
  59968. this._effect.setVector2(name, this._vectors2[name]);
  59969. }
  59970. // Vector3
  59971. for (name in this._vectors3) {
  59972. this._effect.setVector3(name, this._vectors3[name]);
  59973. }
  59974. // Vector4
  59975. for (name in this._vectors4) {
  59976. this._effect.setVector4(name, this._vectors4[name]);
  59977. }
  59978. // Matrix
  59979. for (name in this._matrices) {
  59980. this._effect.setMatrix(name, this._matrices[name]);
  59981. }
  59982. // Matrix 3x3
  59983. for (name in this._matrices3x3) {
  59984. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59985. }
  59986. // Matrix 2x2
  59987. for (name in this._matrices2x2) {
  59988. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59989. }
  59990. // Vector2Array
  59991. for (name in this._vectors2Arrays) {
  59992. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59993. }
  59994. // Vector3Array
  59995. for (name in this._vectors3Arrays) {
  59996. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59997. }
  59998. }
  59999. this._afterBind(mesh);
  60000. };
  60001. ShaderMaterial.prototype.getActiveTextures = function () {
  60002. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60003. for (var name in this._textures) {
  60004. activeTextures.push(this._textures[name]);
  60005. }
  60006. for (var name in this._textureArrays) {
  60007. var array = this._textureArrays[name];
  60008. for (var index = 0; index < array.length; index++) {
  60009. activeTextures.push(array[index]);
  60010. }
  60011. }
  60012. return activeTextures;
  60013. };
  60014. ShaderMaterial.prototype.hasTexture = function (texture) {
  60015. if (_super.prototype.hasTexture.call(this, texture)) {
  60016. return true;
  60017. }
  60018. for (var name in this._textures) {
  60019. if (this._textures[name] === texture) {
  60020. return true;
  60021. }
  60022. }
  60023. for (var name in this._textureArrays) {
  60024. var array = this._textureArrays[name];
  60025. for (var index = 0; index < array.length; index++) {
  60026. if (array[index] === texture) {
  60027. return true;
  60028. }
  60029. }
  60030. }
  60031. return false;
  60032. };
  60033. ShaderMaterial.prototype.clone = function (name) {
  60034. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60035. return newShaderMaterial;
  60036. };
  60037. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60038. if (forceDisposeTextures) {
  60039. var name;
  60040. for (name in this._textures) {
  60041. this._textures[name].dispose();
  60042. }
  60043. for (name in this._textureArrays) {
  60044. var array = this._textureArrays[name];
  60045. for (var index = 0; index < array.length; index++) {
  60046. array[index].dispose();
  60047. }
  60048. }
  60049. }
  60050. this._textures = {};
  60051. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60052. };
  60053. ShaderMaterial.prototype.serialize = function () {
  60054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60055. serializationObject.customType = "BABYLON.ShaderMaterial";
  60056. serializationObject.options = this._options;
  60057. serializationObject.shaderPath = this._shaderPath;
  60058. var name;
  60059. // Texture
  60060. serializationObject.textures = {};
  60061. for (name in this._textures) {
  60062. serializationObject.textures[name] = this._textures[name].serialize();
  60063. }
  60064. // Texture arrays
  60065. serializationObject.textureArrays = {};
  60066. for (name in this._textureArrays) {
  60067. serializationObject.textureArrays[name] = [];
  60068. var array = this._textureArrays[name];
  60069. for (var index = 0; index < array.length; index++) {
  60070. serializationObject.textureArrays[name].push(array[index].serialize());
  60071. }
  60072. }
  60073. // Float
  60074. serializationObject.floats = {};
  60075. for (name in this._floats) {
  60076. serializationObject.floats[name] = this._floats[name];
  60077. }
  60078. // Float s
  60079. serializationObject.FloatArrays = {};
  60080. for (name in this._floatsArrays) {
  60081. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60082. }
  60083. // Color3
  60084. serializationObject.colors3 = {};
  60085. for (name in this._colors3) {
  60086. serializationObject.colors3[name] = this._colors3[name].asArray();
  60087. }
  60088. // Color3 array
  60089. serializationObject.colors3Arrays = {};
  60090. for (name in this._colors3Arrays) {
  60091. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60092. }
  60093. // Color4
  60094. serializationObject.colors4 = {};
  60095. for (name in this._colors4) {
  60096. serializationObject.colors4[name] = this._colors4[name].asArray();
  60097. }
  60098. // Vector2
  60099. serializationObject.vectors2 = {};
  60100. for (name in this._vectors2) {
  60101. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60102. }
  60103. // Vector3
  60104. serializationObject.vectors3 = {};
  60105. for (name in this._vectors3) {
  60106. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60107. }
  60108. // Vector4
  60109. serializationObject.vectors4 = {};
  60110. for (name in this._vectors4) {
  60111. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60112. }
  60113. // Matrix
  60114. serializationObject.matrices = {};
  60115. for (name in this._matrices) {
  60116. serializationObject.matrices[name] = this._matrices[name].asArray();
  60117. }
  60118. // Matrix 3x3
  60119. serializationObject.matrices3x3 = {};
  60120. for (name in this._matrices3x3) {
  60121. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60122. }
  60123. // Matrix 2x2
  60124. serializationObject.matrices2x2 = {};
  60125. for (name in this._matrices2x2) {
  60126. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60127. }
  60128. // Vector2Array
  60129. serializationObject.vectors2Arrays = {};
  60130. for (name in this._vectors2Arrays) {
  60131. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60132. }
  60133. // Vector3Array
  60134. serializationObject.vectors3Arrays = {};
  60135. for (name in this._vectors3Arrays) {
  60136. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60137. }
  60138. return serializationObject;
  60139. };
  60140. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60141. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60142. var name;
  60143. // Texture
  60144. for (name in source.textures) {
  60145. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60146. }
  60147. // Texture arrays
  60148. for (name in source.textureArrays) {
  60149. var array = source.textureArrays[name];
  60150. var textureArray = new Array();
  60151. for (var index = 0; index < array.length; index++) {
  60152. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60153. }
  60154. material.setTextureArray(name, textureArray);
  60155. }
  60156. // Float
  60157. for (name in source.floats) {
  60158. material.setFloat(name, source.floats[name]);
  60159. }
  60160. // Float s
  60161. for (name in source.floatsArrays) {
  60162. material.setFloats(name, source.floatsArrays[name]);
  60163. }
  60164. // Color3
  60165. for (name in source.colors3) {
  60166. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60167. }
  60168. // Color3 arrays
  60169. for (name in source.colors3Arrays) {
  60170. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60171. if (i % 3 === 0) {
  60172. arr.push([num]);
  60173. }
  60174. else {
  60175. arr[arr.length - 1].push(num);
  60176. }
  60177. return arr;
  60178. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60179. material.setColor3Array(name, colors);
  60180. }
  60181. // Color4
  60182. for (name in source.colors4) {
  60183. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60184. }
  60185. // Vector2
  60186. for (name in source.vectors2) {
  60187. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60188. }
  60189. // Vector3
  60190. for (name in source.vectors3) {
  60191. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60192. }
  60193. // Vector4
  60194. for (name in source.vectors4) {
  60195. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60196. }
  60197. // Matrix
  60198. for (name in source.matrices) {
  60199. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60200. }
  60201. // Matrix 3x3
  60202. for (name in source.matrices3x3) {
  60203. material.setMatrix3x3(name, source.matrices3x3[name]);
  60204. }
  60205. // Matrix 2x2
  60206. for (name in source.matrices2x2) {
  60207. material.setMatrix2x2(name, source.matrices2x2[name]);
  60208. }
  60209. // Vector2Array
  60210. for (name in source.vectors2Arrays) {
  60211. material.setArray2(name, source.vectors2Arrays[name]);
  60212. }
  60213. // Vector3Array
  60214. for (name in source.vectors3Arrays) {
  60215. material.setArray3(name, source.vectors3Arrays[name]);
  60216. }
  60217. return material;
  60218. };
  60219. return ShaderMaterial;
  60220. }(BABYLON.Material));
  60221. BABYLON.ShaderMaterial = ShaderMaterial;
  60222. })(BABYLON || (BABYLON = {}));
  60223. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60224. var BABYLON;
  60225. (function (BABYLON) {
  60226. var GroundMesh = /** @class */ (function (_super) {
  60227. __extends(GroundMesh, _super);
  60228. function GroundMesh(name, scene) {
  60229. var _this = _super.call(this, name, scene) || this;
  60230. _this.generateOctree = false;
  60231. return _this;
  60232. }
  60233. GroundMesh.prototype.getClassName = function () {
  60234. return "GroundMesh";
  60235. };
  60236. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60237. get: function () {
  60238. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60239. },
  60240. enumerable: true,
  60241. configurable: true
  60242. });
  60243. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60244. get: function () {
  60245. return this._subdivisionsX;
  60246. },
  60247. enumerable: true,
  60248. configurable: true
  60249. });
  60250. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60251. get: function () {
  60252. return this._subdivisionsY;
  60253. },
  60254. enumerable: true,
  60255. configurable: true
  60256. });
  60257. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60258. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60259. this._subdivisionsX = chunksCount;
  60260. this._subdivisionsY = chunksCount;
  60261. this.subdivide(chunksCount);
  60262. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60263. };
  60264. /**
  60265. * Returns a height (y) value in the Worl system :
  60266. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60267. * Returns the ground y position if (x, z) are outside the ground surface.
  60268. */
  60269. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60270. var world = this.getWorldMatrix();
  60271. var invMat = BABYLON.Tmp.Matrix[5];
  60272. world.invertToRef(invMat);
  60273. var tmpVect = BABYLON.Tmp.Vector3[8];
  60274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60275. x = tmpVect.x;
  60276. z = tmpVect.z;
  60277. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60278. return this.position.y;
  60279. }
  60280. if (!this._heightQuads || this._heightQuads.length == 0) {
  60281. this._initHeightQuads();
  60282. this._computeHeightQuads();
  60283. }
  60284. var facet = this._getFacetAt(x, z);
  60285. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60286. // return y in the World system
  60287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60288. return tmpVect.y;
  60289. };
  60290. /**
  60291. * Returns a normalized vector (Vector3) orthogonal to the ground
  60292. * at the ground coordinates (x, z) expressed in the World system.
  60293. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60294. */
  60295. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60296. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60297. this.getNormalAtCoordinatesToRef(x, z, normal);
  60298. return normal;
  60299. };
  60300. /**
  60301. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60302. * at the ground coordinates (x, z) expressed in the World system.
  60303. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60304. * Returns the GroundMesh.
  60305. */
  60306. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60307. var world = this.getWorldMatrix();
  60308. var tmpMat = BABYLON.Tmp.Matrix[5];
  60309. world.invertToRef(tmpMat);
  60310. var tmpVect = BABYLON.Tmp.Vector3[8];
  60311. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60312. x = tmpVect.x;
  60313. z = tmpVect.z;
  60314. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60315. return this;
  60316. }
  60317. if (!this._heightQuads || this._heightQuads.length == 0) {
  60318. this._initHeightQuads();
  60319. this._computeHeightQuads();
  60320. }
  60321. var facet = this._getFacetAt(x, z);
  60322. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60323. return this;
  60324. };
  60325. /**
  60326. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60327. * if the ground has been updated.
  60328. * This can be used in the render loop.
  60329. * Returns the GroundMesh.
  60330. */
  60331. GroundMesh.prototype.updateCoordinateHeights = function () {
  60332. if (!this._heightQuads || this._heightQuads.length == 0) {
  60333. this._initHeightQuads();
  60334. }
  60335. this._computeHeightQuads();
  60336. return this;
  60337. };
  60338. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60339. GroundMesh.prototype._getFacetAt = function (x, z) {
  60340. // retrieve col and row from x, z coordinates in the ground local system
  60341. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60342. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60343. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60344. var facet;
  60345. if (z < quad.slope.x * x + quad.slope.y) {
  60346. facet = quad.facet1;
  60347. }
  60348. else {
  60349. facet = quad.facet2;
  60350. }
  60351. return facet;
  60352. };
  60353. // Creates and populates the heightMap array with "facet" elements :
  60354. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60355. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60356. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60357. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60358. // Returns the GroundMesh.
  60359. GroundMesh.prototype._initHeightQuads = function () {
  60360. var subdivisionsX = this._subdivisionsX;
  60361. var subdivisionsY = this._subdivisionsY;
  60362. this._heightQuads = new Array();
  60363. for (var row = 0; row < subdivisionsY; row++) {
  60364. for (var col = 0; col < subdivisionsX; col++) {
  60365. 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) };
  60366. this._heightQuads[row * subdivisionsX + col] = quad;
  60367. }
  60368. }
  60369. return this;
  60370. };
  60371. // Compute each quad element values and update the the heightMap array :
  60372. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60373. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60374. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60375. // Returns the GroundMesh.
  60376. GroundMesh.prototype._computeHeightQuads = function () {
  60377. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60378. if (!positions) {
  60379. return this;
  60380. }
  60381. var v1 = BABYLON.Tmp.Vector3[3];
  60382. var v2 = BABYLON.Tmp.Vector3[2];
  60383. var v3 = BABYLON.Tmp.Vector3[1];
  60384. var v4 = BABYLON.Tmp.Vector3[0];
  60385. var v1v2 = BABYLON.Tmp.Vector3[4];
  60386. var v1v3 = BABYLON.Tmp.Vector3[5];
  60387. var v1v4 = BABYLON.Tmp.Vector3[6];
  60388. var norm1 = BABYLON.Tmp.Vector3[7];
  60389. var norm2 = BABYLON.Tmp.Vector3[8];
  60390. var i = 0;
  60391. var j = 0;
  60392. var k = 0;
  60393. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60394. var h = 0;
  60395. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60396. var d2 = 0;
  60397. var subdivisionsX = this._subdivisionsX;
  60398. var subdivisionsY = this._subdivisionsY;
  60399. for (var row = 0; row < subdivisionsY; row++) {
  60400. for (var col = 0; col < subdivisionsX; col++) {
  60401. i = col * 3;
  60402. j = row * (subdivisionsX + 1) * 3;
  60403. k = (row + 1) * (subdivisionsX + 1) * 3;
  60404. v1.x = positions[j + i];
  60405. v1.y = positions[j + i + 1];
  60406. v1.z = positions[j + i + 2];
  60407. v2.x = positions[j + i + 3];
  60408. v2.y = positions[j + i + 4];
  60409. v2.z = positions[j + i + 5];
  60410. v3.x = positions[k + i];
  60411. v3.y = positions[k + i + 1];
  60412. v3.z = positions[k + i + 2];
  60413. v4.x = positions[k + i + 3];
  60414. v4.y = positions[k + i + 4];
  60415. v4.z = positions[k + i + 5];
  60416. // 2D slope V1V4
  60417. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60418. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60419. // facet equations :
  60420. // we compute each facet normal vector
  60421. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60422. // we compute the value d by applying the equation to v1 which belongs to the plane
  60423. // then we store the facet equation in a Vector4
  60424. v2.subtractToRef(v1, v1v2);
  60425. v3.subtractToRef(v1, v1v3);
  60426. v4.subtractToRef(v1, v1v4);
  60427. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60428. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60429. norm1.normalize();
  60430. norm2.normalize();
  60431. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60432. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60433. var quad = this._heightQuads[row * subdivisionsX + col];
  60434. quad.slope.copyFromFloats(cd, h);
  60435. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60436. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60437. }
  60438. }
  60439. return this;
  60440. };
  60441. GroundMesh.prototype.serialize = function (serializationObject) {
  60442. _super.prototype.serialize.call(this, serializationObject);
  60443. serializationObject.subdivisionsX = this._subdivisionsX;
  60444. serializationObject.subdivisionsY = this._subdivisionsY;
  60445. serializationObject.minX = this._minX;
  60446. serializationObject.maxX = this._maxX;
  60447. serializationObject.minZ = this._minZ;
  60448. serializationObject.maxZ = this._maxZ;
  60449. serializationObject.width = this._width;
  60450. serializationObject.height = this._height;
  60451. };
  60452. GroundMesh.Parse = function (parsedMesh, scene) {
  60453. var result = new GroundMesh(parsedMesh.name, scene);
  60454. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60455. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60456. result._minX = parsedMesh.minX;
  60457. result._maxX = parsedMesh.maxX;
  60458. result._minZ = parsedMesh.minZ;
  60459. result._maxZ = parsedMesh.maxZ;
  60460. result._width = parsedMesh.width;
  60461. result._height = parsedMesh.height;
  60462. return result;
  60463. };
  60464. return GroundMesh;
  60465. }(BABYLON.Mesh));
  60466. BABYLON.GroundMesh = GroundMesh;
  60467. })(BABYLON || (BABYLON = {}));
  60468. //# sourceMappingURL=babylon.groundMesh.js.map
  60469. var BABYLON;
  60470. (function (BABYLON) {
  60471. /**
  60472. * Creates an instance based on a source mesh.
  60473. */
  60474. var InstancedMesh = /** @class */ (function (_super) {
  60475. __extends(InstancedMesh, _super);
  60476. function InstancedMesh(name, source) {
  60477. var _this = _super.call(this, name, source.getScene()) || this;
  60478. source.instances.push(_this);
  60479. _this._sourceMesh = source;
  60480. _this.position.copyFrom(source.position);
  60481. _this.rotation.copyFrom(source.rotation);
  60482. _this.scaling.copyFrom(source.scaling);
  60483. if (source.rotationQuaternion) {
  60484. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60485. }
  60486. _this.infiniteDistance = source.infiniteDistance;
  60487. _this.setPivotMatrix(source.getPivotMatrix());
  60488. _this.refreshBoundingInfo();
  60489. _this._syncSubMeshes();
  60490. return _this;
  60491. }
  60492. /**
  60493. * Returns the string "InstancedMesh".
  60494. */
  60495. InstancedMesh.prototype.getClassName = function () {
  60496. return "InstancedMesh";
  60497. };
  60498. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60499. // Methods
  60500. get: function () {
  60501. return this._sourceMesh.receiveShadows;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. Object.defineProperty(InstancedMesh.prototype, "material", {
  60507. get: function () {
  60508. return this._sourceMesh.material;
  60509. },
  60510. enumerable: true,
  60511. configurable: true
  60512. });
  60513. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60514. get: function () {
  60515. return this._sourceMesh.visibility;
  60516. },
  60517. enumerable: true,
  60518. configurable: true
  60519. });
  60520. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60521. get: function () {
  60522. return this._sourceMesh.skeleton;
  60523. },
  60524. enumerable: true,
  60525. configurable: true
  60526. });
  60527. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60528. get: function () {
  60529. return this._sourceMesh.renderingGroupId;
  60530. },
  60531. set: function (value) {
  60532. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60533. return;
  60534. }
  60535. //no-op with warning
  60536. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60537. },
  60538. enumerable: true,
  60539. configurable: true
  60540. });
  60541. /**
  60542. * Returns the total number of vertices (integer).
  60543. */
  60544. InstancedMesh.prototype.getTotalVertices = function () {
  60545. return this._sourceMesh.getTotalVertices();
  60546. };
  60547. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60548. get: function () {
  60549. return this._sourceMesh;
  60550. },
  60551. enumerable: true,
  60552. configurable: true
  60553. });
  60554. /**
  60555. * Is this node ready to be used/rendered
  60556. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60557. * @return {boolean} is it ready
  60558. */
  60559. InstancedMesh.prototype.isReady = function (completeCheck) {
  60560. if (completeCheck === void 0) { completeCheck = false; }
  60561. return this._sourceMesh.isReady(completeCheck, true);
  60562. };
  60563. /**
  60564. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60565. */
  60566. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60567. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60568. };
  60569. /**
  60570. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60571. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60572. * The `data` are either a numeric array either a Float32Array.
  60573. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60574. * 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).
  60575. * Note that a new underlying VertexBuffer object is created each call.
  60576. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60577. *
  60578. * Possible `kind` values :
  60579. * - BABYLON.VertexBuffer.PositionKind
  60580. * - BABYLON.VertexBuffer.UVKind
  60581. * - BABYLON.VertexBuffer.UV2Kind
  60582. * - BABYLON.VertexBuffer.UV3Kind
  60583. * - BABYLON.VertexBuffer.UV4Kind
  60584. * - BABYLON.VertexBuffer.UV5Kind
  60585. * - BABYLON.VertexBuffer.UV6Kind
  60586. * - BABYLON.VertexBuffer.ColorKind
  60587. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60588. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60589. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60590. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60591. *
  60592. * Returns the Mesh.
  60593. */
  60594. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60595. if (this.sourceMesh) {
  60596. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60597. }
  60598. return this.sourceMesh;
  60599. };
  60600. /**
  60601. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60602. * If the mesh has no geometry, it is simply returned as it is.
  60603. * The `data` are either a numeric array either a Float32Array.
  60604. * No new underlying VertexBuffer object is created.
  60605. * 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.
  60606. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60607. *
  60608. * Possible `kind` values :
  60609. * - BABYLON.VertexBuffer.PositionKind
  60610. * - BABYLON.VertexBuffer.UVKind
  60611. * - BABYLON.VertexBuffer.UV2Kind
  60612. * - BABYLON.VertexBuffer.UV3Kind
  60613. * - BABYLON.VertexBuffer.UV4Kind
  60614. * - BABYLON.VertexBuffer.UV5Kind
  60615. * - BABYLON.VertexBuffer.UV6Kind
  60616. * - BABYLON.VertexBuffer.ColorKind
  60617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60621. *
  60622. * Returns the Mesh.
  60623. */
  60624. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60625. if (this.sourceMesh) {
  60626. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60627. }
  60628. return this.sourceMesh;
  60629. };
  60630. /**
  60631. * Sets the mesh indices.
  60632. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60633. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60634. * This method creates a new index buffer each call.
  60635. * Returns the Mesh.
  60636. */
  60637. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60638. if (totalVertices === void 0) { totalVertices = null; }
  60639. if (this.sourceMesh) {
  60640. this.sourceMesh.setIndices(indices, totalVertices);
  60641. }
  60642. return this.sourceMesh;
  60643. };
  60644. /**
  60645. * Boolean : True if the mesh owns the requested kind of data.
  60646. */
  60647. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60648. return this._sourceMesh.isVerticesDataPresent(kind);
  60649. };
  60650. /**
  60651. * Returns an array of indices (IndicesArray).
  60652. */
  60653. InstancedMesh.prototype.getIndices = function () {
  60654. return this._sourceMesh.getIndices();
  60655. };
  60656. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60657. get: function () {
  60658. return this._sourceMesh._positions;
  60659. },
  60660. enumerable: true,
  60661. configurable: true
  60662. });
  60663. /**
  60664. * Sets a new updated BoundingInfo to the mesh.
  60665. * Returns the mesh.
  60666. */
  60667. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60668. var meshBB = this._sourceMesh.getBoundingInfo();
  60669. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60670. this._updateBoundingInfo();
  60671. return this;
  60672. };
  60673. InstancedMesh.prototype._preActivate = function () {
  60674. if (this._currentLOD) {
  60675. this._currentLOD._preActivate();
  60676. }
  60677. return this;
  60678. };
  60679. InstancedMesh.prototype._activate = function (renderId) {
  60680. if (this._currentLOD) {
  60681. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60682. }
  60683. return this;
  60684. };
  60685. /**
  60686. * Returns the current associated LOD AbstractMesh.
  60687. */
  60688. InstancedMesh.prototype.getLOD = function (camera) {
  60689. if (!camera) {
  60690. return this;
  60691. }
  60692. var boundingInfo = this.getBoundingInfo();
  60693. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60694. if (this._currentLOD === this.sourceMesh) {
  60695. return this;
  60696. }
  60697. return this._currentLOD;
  60698. };
  60699. InstancedMesh.prototype._syncSubMeshes = function () {
  60700. this.releaseSubMeshes();
  60701. if (this._sourceMesh.subMeshes) {
  60702. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60703. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60704. }
  60705. }
  60706. return this;
  60707. };
  60708. InstancedMesh.prototype._generatePointsArray = function () {
  60709. return this._sourceMesh._generatePointsArray();
  60710. };
  60711. /**
  60712. * Creates a new InstancedMesh from the current mesh.
  60713. * - name (string) : the cloned mesh name
  60714. * - newParent (optional Node) : the optional Node to parent the clone to.
  60715. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60716. *
  60717. * Returns the clone.
  60718. */
  60719. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60720. var result = this._sourceMesh.createInstance(name);
  60721. // Deep copy
  60722. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60723. // Bounding info
  60724. this.refreshBoundingInfo();
  60725. // Parent
  60726. if (newParent) {
  60727. result.parent = newParent;
  60728. }
  60729. if (!doNotCloneChildren) {
  60730. // Children
  60731. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60732. var mesh = this.getScene().meshes[index];
  60733. if (mesh.parent === this) {
  60734. mesh.clone(mesh.name, result);
  60735. }
  60736. }
  60737. }
  60738. result.computeWorldMatrix(true);
  60739. return result;
  60740. };
  60741. /**
  60742. * Disposes the InstancedMesh.
  60743. * Returns nothing.
  60744. */
  60745. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60746. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60747. // Remove from mesh
  60748. var index = this._sourceMesh.instances.indexOf(this);
  60749. this._sourceMesh.instances.splice(index, 1);
  60750. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60751. };
  60752. return InstancedMesh;
  60753. }(BABYLON.AbstractMesh));
  60754. BABYLON.InstancedMesh = InstancedMesh;
  60755. })(BABYLON || (BABYLON = {}));
  60756. //# sourceMappingURL=babylon.instancedMesh.js.map
  60757. var BABYLON;
  60758. (function (BABYLON) {
  60759. var LinesMesh = /** @class */ (function (_super) {
  60760. __extends(LinesMesh, _super);
  60761. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60762. if (scene === void 0) { scene = null; }
  60763. if (parent === void 0) { parent = null; }
  60764. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60765. _this.useVertexColor = useVertexColor;
  60766. _this.useVertexAlpha = useVertexAlpha;
  60767. _this.color = new BABYLON.Color3(1, 1, 1);
  60768. _this.alpha = 1;
  60769. if (source) {
  60770. _this.color = source.color.clone();
  60771. _this.alpha = source.alpha;
  60772. _this.useVertexColor = source.useVertexColor;
  60773. _this.useVertexAlpha = source.useVertexAlpha;
  60774. }
  60775. _this._intersectionThreshold = 0.1;
  60776. var defines = [];
  60777. var options = {
  60778. attributes: [BABYLON.VertexBuffer.PositionKind],
  60779. uniforms: ["world", "viewProjection"],
  60780. needAlphaBlending: true,
  60781. defines: defines
  60782. };
  60783. if (useVertexAlpha === false) {
  60784. options.needAlphaBlending = false;
  60785. }
  60786. if (!useVertexColor) {
  60787. options.uniforms.push("color");
  60788. }
  60789. else {
  60790. options.defines.push("#define VERTEXCOLOR");
  60791. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60792. }
  60793. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60794. return _this;
  60795. }
  60796. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60797. /**
  60798. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60799. * This margin is expressed in world space coordinates, so its value may vary.
  60800. * Default value is 0.1
  60801. * @returns the intersection Threshold value.
  60802. */
  60803. get: function () {
  60804. return this._intersectionThreshold;
  60805. },
  60806. /**
  60807. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60808. * This margin is expressed in world space coordinates, so its value may vary.
  60809. * @param value the new threshold to apply
  60810. */
  60811. set: function (value) {
  60812. if (this._intersectionThreshold === value) {
  60813. return;
  60814. }
  60815. this._intersectionThreshold = value;
  60816. if (this.geometry) {
  60817. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60818. }
  60819. },
  60820. enumerable: true,
  60821. configurable: true
  60822. });
  60823. /**
  60824. * Returns the string "LineMesh"
  60825. */
  60826. LinesMesh.prototype.getClassName = function () {
  60827. return "LinesMesh";
  60828. };
  60829. Object.defineProperty(LinesMesh.prototype, "material", {
  60830. get: function () {
  60831. return this._colorShader;
  60832. },
  60833. set: function (value) {
  60834. // Do nothing
  60835. },
  60836. enumerable: true,
  60837. configurable: true
  60838. });
  60839. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60840. get: function () {
  60841. return false;
  60842. },
  60843. enumerable: true,
  60844. configurable: true
  60845. });
  60846. LinesMesh.prototype.createInstance = function (name) {
  60847. throw new Error("LinesMeshes do not support createInstance.");
  60848. };
  60849. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60850. if (!this._geometry) {
  60851. return this;
  60852. }
  60853. // VBOs
  60854. this._geometry._bind(this._colorShader.getEffect());
  60855. // Color
  60856. if (!this.useVertexColor) {
  60857. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60858. }
  60859. return this;
  60860. };
  60861. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60862. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60863. return this;
  60864. }
  60865. var engine = this.getScene().getEngine();
  60866. // Draw order
  60867. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60868. return this;
  60869. };
  60870. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60871. this._colorShader.dispose();
  60872. _super.prototype.dispose.call(this, doNotRecurse);
  60873. };
  60874. /**
  60875. * Returns a new LineMesh object cloned from the current one.
  60876. */
  60877. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60878. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60879. };
  60880. return LinesMesh;
  60881. }(BABYLON.Mesh));
  60882. BABYLON.LinesMesh = LinesMesh;
  60883. })(BABYLON || (BABYLON = {}));
  60884. //# sourceMappingURL=babylon.linesMesh.js.map
  60885. var BABYLON;
  60886. (function (BABYLON) {
  60887. /**
  60888. * Class containing static functions to help procedurally build meshes
  60889. */
  60890. var MeshBuilder = /** @class */ (function () {
  60891. function MeshBuilder() {
  60892. }
  60893. MeshBuilder.updateSideOrientation = function (orientation) {
  60894. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60895. return BABYLON.Mesh.DOUBLESIDE;
  60896. }
  60897. if (orientation === undefined || orientation === null) {
  60898. return BABYLON.Mesh.FRONTSIDE;
  60899. }
  60900. return orientation;
  60901. };
  60902. /**
  60903. * Creates a box mesh
  60904. * * The parameter `size` sets the size (float) of each box side (default 1)
  60905. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60906. * * 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)
  60907. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60908. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60909. * * 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
  60910. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60911. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60912. * @param name defines the name of the mesh
  60913. * @param options defines the options used to create the mesh
  60914. * @param scene defines the hosting scene
  60915. * @returns the box mesh
  60916. */
  60917. MeshBuilder.CreateBox = function (name, options, scene) {
  60918. if (scene === void 0) { scene = null; }
  60919. var box = new BABYLON.Mesh(name, scene);
  60920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60921. box._originalBuilderSideOrientation = options.sideOrientation;
  60922. var vertexData = BABYLON.VertexData.CreateBox(options);
  60923. vertexData.applyToMesh(box, options.updatable);
  60924. return box;
  60925. };
  60926. /**
  60927. * Creates a sphere mesh
  60928. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60929. * * 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`)
  60930. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60931. * * 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
  60932. * * 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)
  60933. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60934. * * 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
  60935. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60936. * @param name defines the name of the mesh
  60937. * @param options defines the options used to create the mesh
  60938. * @param scene defines the hosting scene
  60939. * @returns the sphere mesh
  60940. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60941. */
  60942. MeshBuilder.CreateSphere = function (name, options, scene) {
  60943. var sphere = new BABYLON.Mesh(name, scene);
  60944. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60945. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60946. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60947. vertexData.applyToMesh(sphere, options.updatable);
  60948. return sphere;
  60949. };
  60950. /**
  60951. * Creates a plane polygonal mesh. By default, this is a disc
  60952. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60953. * * 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
  60954. * * 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
  60955. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60956. * * 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
  60957. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60958. * @param name defines the name of the mesh
  60959. * @param options defines the options used to create the mesh
  60960. * @param scene defines the hosting scene
  60961. * @returns the plane polygonal mesh
  60962. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60963. */
  60964. MeshBuilder.CreateDisc = function (name, options, scene) {
  60965. if (scene === void 0) { scene = null; }
  60966. var disc = new BABYLON.Mesh(name, scene);
  60967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60968. disc._originalBuilderSideOrientation = options.sideOrientation;
  60969. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60970. vertexData.applyToMesh(disc, options.updatable);
  60971. return disc;
  60972. };
  60973. /**
  60974. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60975. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60976. * * 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`)
  60977. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60978. * * 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
  60979. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60980. * * 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
  60981. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60982. * @param name defines the name of the mesh
  60983. * @param options defines the options used to create the mesh
  60984. * @param scene defines the hosting scene
  60985. * @returns the icosahedron mesh
  60986. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60987. */
  60988. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60989. var sphere = new BABYLON.Mesh(name, scene);
  60990. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60991. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60992. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60993. vertexData.applyToMesh(sphere, options.updatable);
  60994. return sphere;
  60995. };
  60996. ;
  60997. /**
  60998. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60999. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61000. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61001. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61002. * * 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
  61003. * * 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
  61004. * * 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
  61005. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61006. * * 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
  61007. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61008. * * 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
  61009. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61010. * * 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
  61011. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61012. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61013. * @param name defines the name of the mesh
  61014. * @param options defines the options used to create the mesh
  61015. * @param scene defines the hosting scene
  61016. * @returns the ribbon mesh
  61017. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61018. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61019. */
  61020. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61021. if (scene === void 0) { scene = null; }
  61022. var pathArray = options.pathArray;
  61023. var closeArray = options.closeArray;
  61024. var closePath = options.closePath;
  61025. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61026. var instance = options.instance;
  61027. var updatable = options.updatable;
  61028. if (instance) { // existing ribbon instance update
  61029. // positionFunction : ribbon case
  61030. // only pathArray and sideOrientation parameters are taken into account for positions update
  61031. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61032. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61033. var positionFunction = function (positions) {
  61034. var minlg = pathArray[0].length;
  61035. var i = 0;
  61036. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61037. for (var si = 1; si <= ns; si++) {
  61038. for (var p = 0; p < pathArray.length; p++) {
  61039. var path = pathArray[p];
  61040. var l = path.length;
  61041. minlg = (minlg < l) ? minlg : l;
  61042. var j = 0;
  61043. while (j < minlg) {
  61044. positions[i] = path[j].x;
  61045. positions[i + 1] = path[j].y;
  61046. positions[i + 2] = path[j].z;
  61047. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61048. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61049. }
  61050. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61051. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61052. }
  61053. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61054. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61055. }
  61056. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61057. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61058. }
  61059. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61060. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61061. }
  61062. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61063. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61064. }
  61065. j++;
  61066. i += 3;
  61067. }
  61068. if (instance._closePath) {
  61069. positions[i] = path[0].x;
  61070. positions[i + 1] = path[0].y;
  61071. positions[i + 2] = path[0].z;
  61072. i += 3;
  61073. }
  61074. }
  61075. }
  61076. };
  61077. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61078. positionFunction(positions);
  61079. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61080. instance._boundingInfo.update(instance._worldMatrix);
  61081. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61082. if (options.colors) {
  61083. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61084. for (var c = 0; c < options.colors.length; c++) {
  61085. colors[c * 4] = options.colors[c].r;
  61086. colors[c * 4 + 1] = options.colors[c].g;
  61087. colors[c * 4 + 2] = options.colors[c].b;
  61088. colors[c * 4 + 3] = options.colors[c].a;
  61089. }
  61090. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61091. }
  61092. if (options.uvs) {
  61093. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61094. for (var i = 0; i < options.uvs.length; i++) {
  61095. uvs[i * 2] = options.uvs[i].x;
  61096. uvs[i * 2 + 1] = options.uvs[i].y;
  61097. }
  61098. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61099. }
  61100. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61101. var indices = instance.getIndices();
  61102. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61103. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61104. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61105. if (instance._closePath) {
  61106. var indexFirst = 0;
  61107. var indexLast = 0;
  61108. for (var p = 0; p < pathArray.length; p++) {
  61109. indexFirst = instance._idx[p] * 3;
  61110. if (p + 1 < pathArray.length) {
  61111. indexLast = (instance._idx[p + 1] - 1) * 3;
  61112. }
  61113. else {
  61114. indexLast = normals.length - 3;
  61115. }
  61116. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61117. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61118. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61119. normals[indexLast] = normals[indexFirst];
  61120. normals[indexLast + 1] = normals[indexFirst + 1];
  61121. normals[indexLast + 2] = normals[indexFirst + 2];
  61122. }
  61123. }
  61124. if (!(instance.areNormalsFrozen)) {
  61125. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61126. }
  61127. }
  61128. return instance;
  61129. }
  61130. else { // new ribbon creation
  61131. var ribbon = new BABYLON.Mesh(name, scene);
  61132. ribbon._originalBuilderSideOrientation = sideOrientation;
  61133. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61134. if (closePath) {
  61135. ribbon._idx = vertexData._idx;
  61136. }
  61137. ribbon._closePath = closePath;
  61138. ribbon._closeArray = closeArray;
  61139. vertexData.applyToMesh(ribbon, updatable);
  61140. return ribbon;
  61141. }
  61142. };
  61143. /**
  61144. * Creates a cylinder or a cone mesh
  61145. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61146. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61147. * * 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.
  61148. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61149. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61150. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61151. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61152. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61153. * * 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).
  61154. * * 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
  61155. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61156. * * 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
  61157. * * 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.
  61158. * * If `enclose` is false, a ring surface is one element.
  61159. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61160. * * 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
  61161. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61162. * * 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
  61163. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61164. * @param name defines the name of the mesh
  61165. * @param options defines the options used to create the mesh
  61166. * @param scene defines the hosting scene
  61167. * @returns the cylinder mesh
  61168. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61169. */
  61170. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61171. var cylinder = new BABYLON.Mesh(name, scene);
  61172. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61173. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61174. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61175. vertexData.applyToMesh(cylinder, options.updatable);
  61176. return cylinder;
  61177. };
  61178. /**
  61179. * Creates a torus mesh
  61180. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61181. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61182. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61183. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61184. * * 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
  61185. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61186. * @param name defines the name of the mesh
  61187. * @param options defines the options used to create the mesh
  61188. * @param scene defines the hosting scene
  61189. * @returns the torus mesh
  61190. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61191. */
  61192. MeshBuilder.CreateTorus = function (name, options, scene) {
  61193. var torus = new BABYLON.Mesh(name, scene);
  61194. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61195. torus._originalBuilderSideOrientation = options.sideOrientation;
  61196. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61197. vertexData.applyToMesh(torus, options.updatable);
  61198. return torus;
  61199. };
  61200. /**
  61201. * Creates a torus knot mesh
  61202. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61203. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61204. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61205. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61206. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61207. * * 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
  61208. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61209. * @param name defines the name of the mesh
  61210. * @param options defines the options used to create the mesh
  61211. * @param scene defines the hosting scene
  61212. * @returns the torus knot mesh
  61213. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61214. */
  61215. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61216. var torusKnot = new BABYLON.Mesh(name, scene);
  61217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61218. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61219. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61220. vertexData.applyToMesh(torusKnot, options.updatable);
  61221. return torusKnot;
  61222. };
  61223. /**
  61224. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61225. * * 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
  61226. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61227. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61228. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61229. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61230. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61231. * * 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
  61232. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61234. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61235. * @param name defines the name of the new line system
  61236. * @param options defines the options used to create the line system
  61237. * @param scene defines the hosting scene
  61238. * @returns a new line system mesh
  61239. */
  61240. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61241. var instance = options.instance;
  61242. var lines = options.lines;
  61243. var colors = options.colors;
  61244. if (instance) { // lines update
  61245. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61246. var vertexColor;
  61247. var lineColors;
  61248. if (colors) {
  61249. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61250. }
  61251. var i = 0;
  61252. var c = 0;
  61253. for (var l = 0; l < lines.length; l++) {
  61254. var points = lines[l];
  61255. for (var p = 0; p < points.length; p++) {
  61256. positions[i] = points[p].x;
  61257. positions[i + 1] = points[p].y;
  61258. positions[i + 2] = points[p].z;
  61259. if (colors && vertexColor) {
  61260. lineColors = colors[l];
  61261. vertexColor[c] = lineColors[p].r;
  61262. vertexColor[c + 1] = lineColors[p].g;
  61263. vertexColor[c + 2] = lineColors[p].b;
  61264. vertexColor[c + 3] = lineColors[p].a;
  61265. c += 4;
  61266. }
  61267. i += 3;
  61268. }
  61269. }
  61270. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61271. if (colors && vertexColor) {
  61272. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61273. }
  61274. return instance;
  61275. }
  61276. // line system creation
  61277. var useVertexColor = (colors) ? true : false;
  61278. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61279. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61280. vertexData.applyToMesh(lineSystem, options.updatable);
  61281. return lineSystem;
  61282. };
  61283. /**
  61284. * Creates a line mesh
  61285. * 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
  61286. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61287. * * The parameter `points` is an array successive Vector3
  61288. * * 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
  61289. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61290. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61291. * * When updating an instance, remember that only point positions can change, not the number of points
  61292. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61293. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61294. * @param name defines the name of the new line system
  61295. * @param options defines the options used to create the line system
  61296. * @param scene defines the hosting scene
  61297. * @returns a new line mesh
  61298. */
  61299. MeshBuilder.CreateLines = function (name, options, scene) {
  61300. if (scene === void 0) { scene = null; }
  61301. var colors = (options.colors) ? [options.colors] : null;
  61302. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61303. return lines;
  61304. };
  61305. /**
  61306. * Creates a dashed line mesh
  61307. * * 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
  61308. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61309. * * The parameter `points` is an array successive Vector3
  61310. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61311. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61312. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61313. * * 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
  61314. * * When updating an instance, remember that only point positions can change, not the number of points
  61315. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61316. * @param name defines the name of the mesh
  61317. * @param options defines the options used to create the mesh
  61318. * @param scene defines the hosting scene
  61319. * @returns the dashed line mesh
  61320. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61321. */
  61322. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61323. if (scene === void 0) { scene = null; }
  61324. var points = options.points;
  61325. var instance = options.instance;
  61326. var gapSize = options.gapSize || 1;
  61327. var dashSize = options.dashSize || 3;
  61328. if (instance) { // dashed lines update
  61329. var positionFunction = function (positions) {
  61330. var curvect = BABYLON.Vector3.Zero();
  61331. var nbSeg = positions.length / 6;
  61332. var lg = 0;
  61333. var nb = 0;
  61334. var shft = 0;
  61335. var dashshft = 0;
  61336. var curshft = 0;
  61337. var p = 0;
  61338. var i = 0;
  61339. var j = 0;
  61340. for (i = 0; i < points.length - 1; i++) {
  61341. points[i + 1].subtractToRef(points[i], curvect);
  61342. lg += curvect.length();
  61343. }
  61344. shft = lg / nbSeg;
  61345. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61346. for (i = 0; i < points.length - 1; i++) {
  61347. points[i + 1].subtractToRef(points[i], curvect);
  61348. nb = Math.floor(curvect.length() / shft);
  61349. curvect.normalize();
  61350. j = 0;
  61351. while (j < nb && p < positions.length) {
  61352. curshft = shft * j;
  61353. positions[p] = points[i].x + curshft * curvect.x;
  61354. positions[p + 1] = points[i].y + curshft * curvect.y;
  61355. positions[p + 2] = points[i].z + curshft * curvect.z;
  61356. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61357. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61358. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61359. p += 6;
  61360. j++;
  61361. }
  61362. }
  61363. while (p < positions.length) {
  61364. positions[p] = points[i].x;
  61365. positions[p + 1] = points[i].y;
  61366. positions[p + 2] = points[i].z;
  61367. p += 3;
  61368. }
  61369. };
  61370. instance.updateMeshPositions(positionFunction, false);
  61371. return instance;
  61372. }
  61373. // dashed lines creation
  61374. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61375. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61376. vertexData.applyToMesh(dashedLines, options.updatable);
  61377. dashedLines.dashSize = dashSize;
  61378. dashedLines.gapSize = gapSize;
  61379. return dashedLines;
  61380. };
  61381. /**
  61382. * 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.
  61383. * * 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.
  61384. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61385. * * 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.
  61386. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61387. * * 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
  61388. * * 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
  61389. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61390. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61391. * * 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
  61392. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61393. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61394. * @param name defines the name of the mesh
  61395. * @param options defines the options used to create the mesh
  61396. * @param scene defines the hosting scene
  61397. * @returns the extruded shape mesh
  61398. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61399. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61400. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61401. */
  61402. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61403. if (scene === void 0) { scene = null; }
  61404. var path = options.path;
  61405. var shape = options.shape;
  61406. var scale = options.scale || 1;
  61407. var rotation = options.rotation || 0;
  61408. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61409. var updatable = options.updatable;
  61410. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61411. var instance = options.instance || null;
  61412. var invertUV = options.invertUV || false;
  61413. 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);
  61414. };
  61415. /**
  61416. * Creates an custom extruded shape mesh.
  61417. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61418. * * 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.
  61419. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61420. * * 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
  61421. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61422. * * 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
  61423. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61424. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61425. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61426. * * 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
  61427. * * 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
  61428. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61429. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61430. * * 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
  61431. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61432. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61433. * @param name defines the name of the mesh
  61434. * @param options defines the options used to create the mesh
  61435. * @param scene defines the hosting scene
  61436. * @returns the custom extruded shape mesh
  61437. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61438. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61439. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61440. */
  61441. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61442. var path = options.path;
  61443. var shape = options.shape;
  61444. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61445. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61446. var ribbonCloseArray = options.ribbonCloseArray || false;
  61447. var ribbonClosePath = options.ribbonClosePath || false;
  61448. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61449. var updatable = options.updatable;
  61450. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61451. var instance = options.instance;
  61452. var invertUV = options.invertUV || false;
  61453. 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);
  61454. };
  61455. /**
  61456. * Creates lathe mesh.
  61457. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61458. * * 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
  61459. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61460. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61461. * * 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
  61462. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61463. * * 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
  61464. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61465. * * 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
  61466. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61468. * @param name defines the name of the mesh
  61469. * @param options defines the options used to create the mesh
  61470. * @param scene defines the hosting scene
  61471. * @returns the lathe mesh
  61472. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61473. */
  61474. MeshBuilder.CreateLathe = function (name, options, scene) {
  61475. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61476. var closed = (options.closed === undefined) ? true : options.closed;
  61477. var shape = options.shape;
  61478. var radius = options.radius || 1;
  61479. var tessellation = options.tessellation || 64;
  61480. var updatable = options.updatable;
  61481. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61482. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61483. var pi2 = Math.PI * 2;
  61484. var paths = new Array();
  61485. var invertUV = options.invertUV || false;
  61486. var i = 0;
  61487. var p = 0;
  61488. var step = pi2 / tessellation * arc;
  61489. var rotated;
  61490. var path = new Array();
  61491. for (i = 0; i <= tessellation; i++) {
  61492. var path = [];
  61493. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61494. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61495. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61496. }
  61497. for (p = 0; p < shape.length; p++) {
  61498. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61499. path.push(rotated);
  61500. }
  61501. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61502. 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));
  61503. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61504. }
  61505. paths.push(path);
  61506. }
  61507. // lathe ribbon
  61508. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61509. return lathe;
  61510. };
  61511. /**
  61512. * Creates a plane mesh
  61513. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61514. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61515. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61516. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61517. * * 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
  61518. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61519. * @param name defines the name of the mesh
  61520. * @param options defines the options used to create the mesh
  61521. * @param scene defines the hosting scene
  61522. * @returns the plane mesh
  61523. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61524. */
  61525. MeshBuilder.CreatePlane = function (name, options, scene) {
  61526. var plane = new BABYLON.Mesh(name, scene);
  61527. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61528. plane._originalBuilderSideOrientation = options.sideOrientation;
  61529. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61530. vertexData.applyToMesh(plane, options.updatable);
  61531. if (options.sourcePlane) {
  61532. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61533. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61534. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61535. plane.rotate(vectorProduct, product);
  61536. }
  61537. return plane;
  61538. };
  61539. /**
  61540. * Creates a ground mesh
  61541. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61542. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61543. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61544. * @param name defines the name of the mesh
  61545. * @param options defines the options used to create the mesh
  61546. * @param scene defines the hosting scene
  61547. * @returns the ground mesh
  61548. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61549. */
  61550. MeshBuilder.CreateGround = function (name, options, scene) {
  61551. var ground = new BABYLON.GroundMesh(name, scene);
  61552. ground._setReady(false);
  61553. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61554. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61555. ground._width = options.width || 1;
  61556. ground._height = options.height || 1;
  61557. ground._maxX = ground._width / 2;
  61558. ground._maxZ = ground._height / 2;
  61559. ground._minX = -ground._maxX;
  61560. ground._minZ = -ground._maxZ;
  61561. var vertexData = BABYLON.VertexData.CreateGround(options);
  61562. vertexData.applyToMesh(ground, options.updatable);
  61563. ground._setReady(true);
  61564. return ground;
  61565. };
  61566. /**
  61567. * Creates a tiled ground mesh
  61568. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61569. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61570. * * 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
  61571. * * 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
  61572. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61573. * @param name defines the name of the mesh
  61574. * @param options defines the options used to create the mesh
  61575. * @param scene defines the hosting scene
  61576. * @returns the tiled ground mesh
  61577. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61578. */
  61579. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61580. var tiledGround = new BABYLON.Mesh(name, scene);
  61581. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61582. vertexData.applyToMesh(tiledGround, options.updatable);
  61583. return tiledGround;
  61584. };
  61585. /**
  61586. * Creates a ground mesh from a height map
  61587. * * The parameter `url` sets the URL of the height map image resource.
  61588. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61589. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61590. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61591. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61592. * * 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.
  61593. * * 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).
  61594. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61595. * @param name defines the name of the mesh
  61596. * @param url defines the url to the height map
  61597. * @param options defines the options used to create the mesh
  61598. * @param scene defines the hosting scene
  61599. * @returns the ground mesh
  61600. * @see http://doc.babylonjs.com/babylon101/height_map
  61601. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61602. */
  61603. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61604. var width = options.width || 10.0;
  61605. var height = options.height || 10.0;
  61606. var subdivisions = options.subdivisions || 1 | 0;
  61607. var minHeight = options.minHeight || 0.0;
  61608. var maxHeight = options.maxHeight || 1.0;
  61609. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61610. var updatable = options.updatable;
  61611. var onReady = options.onReady;
  61612. var ground = new BABYLON.GroundMesh(name, scene);
  61613. ground._subdivisionsX = subdivisions;
  61614. ground._subdivisionsY = subdivisions;
  61615. ground._width = width;
  61616. ground._height = height;
  61617. ground._maxX = ground._width / 2.0;
  61618. ground._maxZ = ground._height / 2.0;
  61619. ground._minX = -ground._maxX;
  61620. ground._minZ = -ground._maxZ;
  61621. ground._setReady(false);
  61622. var onload = function (img) {
  61623. // Getting height map data
  61624. var canvas = document.createElement("canvas");
  61625. var context = canvas.getContext("2d");
  61626. if (!context) {
  61627. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61628. }
  61629. if (scene.isDisposed) {
  61630. return;
  61631. }
  61632. var bufferWidth = img.width;
  61633. var bufferHeight = img.height;
  61634. canvas.width = bufferWidth;
  61635. canvas.height = bufferHeight;
  61636. context.drawImage(img, 0, 0);
  61637. // Create VertexData from map data
  61638. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61639. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61640. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61641. width: width, height: height,
  61642. subdivisions: subdivisions,
  61643. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61644. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61645. });
  61646. vertexData.applyToMesh(ground, updatable);
  61647. //execute ready callback, if set
  61648. if (onReady) {
  61649. onReady(ground);
  61650. }
  61651. ground._setReady(true);
  61652. };
  61653. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61654. return ground;
  61655. };
  61656. /**
  61657. * Creates a polygon mesh
  61658. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61659. * * 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
  61660. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61661. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61662. * * 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)
  61663. * * Remember you can only change the shape positions, not their number when updating a polygon
  61664. * @param name defines the name of the mesh
  61665. * @param options defines the options used to create the mesh
  61666. * @param scene defines the hosting scene
  61667. * @returns the polygon mesh
  61668. */
  61669. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61670. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61671. var shape = options.shape;
  61672. var holes = options.holes || [];
  61673. var depth = options.depth || 0;
  61674. var contours = [];
  61675. var hole = [];
  61676. for (var i = 0; i < shape.length; i++) {
  61677. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61678. }
  61679. var epsilon = 0.00000001;
  61680. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61681. contours.pop();
  61682. }
  61683. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61684. for (var hNb = 0; hNb < holes.length; hNb++) {
  61685. hole = [];
  61686. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61687. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61688. }
  61689. polygonTriangulation.addHole(hole);
  61690. }
  61691. var polygon = polygonTriangulation.build(options.updatable, depth);
  61692. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61693. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61694. vertexData.applyToMesh(polygon, options.updatable);
  61695. return polygon;
  61696. };
  61697. ;
  61698. /**
  61699. * Creates an extruded polygon mesh, with depth in the Y direction.
  61700. * * 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)
  61701. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61702. * @param name defines the name of the mesh
  61703. * @param options defines the options used to create the mesh
  61704. * @param scene defines the hosting scene
  61705. * @returns the polygon mesh
  61706. */
  61707. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61708. return MeshBuilder.CreatePolygon(name, options, scene);
  61709. };
  61710. ;
  61711. /**
  61712. * Creates a tube mesh.
  61713. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61714. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61715. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61716. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61717. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61718. * * 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)
  61719. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61720. * * 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
  61721. * * 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
  61722. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61723. * * 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
  61724. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61725. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61726. * @param name defines the name of the mesh
  61727. * @param options defines the options used to create the mesh
  61728. * @param scene defines the hosting scene
  61729. * @returns the tube mesh
  61730. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61731. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61732. */
  61733. MeshBuilder.CreateTube = function (name, options, scene) {
  61734. var path = options.path;
  61735. var instance = options.instance;
  61736. var radius = 1.0;
  61737. if (instance) {
  61738. radius = instance.radius;
  61739. }
  61740. if (options.radius !== undefined) {
  61741. radius = options.radius;
  61742. }
  61743. ;
  61744. var tessellation = options.tessellation || 64 | 0;
  61745. var radiusFunction = options.radiusFunction || null;
  61746. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61747. var invertUV = options.invertUV || false;
  61748. var updatable = options.updatable;
  61749. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61750. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61751. // tube geometry
  61752. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61753. var tangents = path3D.getTangents();
  61754. var normals = path3D.getNormals();
  61755. var distances = path3D.getDistances();
  61756. var pi2 = Math.PI * 2;
  61757. var step = pi2 / tessellation * arc;
  61758. var returnRadius = function () { return radius; };
  61759. var radiusFunctionFinal = radiusFunction || returnRadius;
  61760. var circlePath;
  61761. var rad;
  61762. var normal;
  61763. var rotated;
  61764. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61765. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61766. for (var i = 0; i < path.length; i++) {
  61767. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61768. circlePath = Array(); // current circle array
  61769. normal = normals[i]; // current normal
  61770. for (var t = 0; t < tessellation; t++) {
  61771. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61772. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61773. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61774. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61775. circlePath[t] = rotated;
  61776. }
  61777. circlePaths[index] = circlePath;
  61778. index++;
  61779. }
  61780. // cap
  61781. var capPath = function (nbPoints, pathIndex) {
  61782. var pointCap = Array();
  61783. for (var i = 0; i < nbPoints; i++) {
  61784. pointCap.push(path[pathIndex]);
  61785. }
  61786. return pointCap;
  61787. };
  61788. switch (cap) {
  61789. case BABYLON.Mesh.NO_CAP:
  61790. break;
  61791. case BABYLON.Mesh.CAP_START:
  61792. circlePaths[0] = capPath(tessellation, 0);
  61793. circlePaths[1] = circlePaths[2].slice(0);
  61794. break;
  61795. case BABYLON.Mesh.CAP_END:
  61796. circlePaths[index] = circlePaths[index - 1].slice(0);
  61797. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61798. break;
  61799. case BABYLON.Mesh.CAP_ALL:
  61800. circlePaths[0] = capPath(tessellation, 0);
  61801. circlePaths[1] = circlePaths[2].slice(0);
  61802. circlePaths[index] = circlePaths[index - 1].slice(0);
  61803. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61804. break;
  61805. default:
  61806. break;
  61807. }
  61808. return circlePaths;
  61809. };
  61810. var path3D;
  61811. var pathArray;
  61812. if (instance) { // tube update
  61813. var arc = options.arc || instance.arc;
  61814. path3D = (instance.path3D).update(path);
  61815. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61816. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61817. instance.path3D = path3D;
  61818. instance.pathArray = pathArray;
  61819. instance.arc = arc;
  61820. instance.radius = radius;
  61821. return instance;
  61822. }
  61823. // tube creation
  61824. path3D = new BABYLON.Path3D(path);
  61825. var newPathArray = new Array();
  61826. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61827. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61828. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61829. tube.pathArray = pathArray;
  61830. tube.path3D = path3D;
  61831. tube.tessellation = tessellation;
  61832. tube.cap = cap;
  61833. tube.arc = options.arc;
  61834. tube.radius = radius;
  61835. return tube;
  61836. };
  61837. /**
  61838. * Creates a polyhedron mesh
  61839. * * 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
  61840. * * The parameter `size` (positive float, default 1) sets the polygon size
  61841. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61842. * * 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`
  61843. * * 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
  61844. * * 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)`)
  61845. * * 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
  61846. * * 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
  61847. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61848. * * 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
  61849. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61850. * @param name defines the name of the mesh
  61851. * @param options defines the options used to create the mesh
  61852. * @param scene defines the hosting scene
  61853. * @returns the polyhedron mesh
  61854. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61855. */
  61856. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61857. var polyhedron = new BABYLON.Mesh(name, scene);
  61858. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61859. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61860. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61861. vertexData.applyToMesh(polyhedron, options.updatable);
  61862. return polyhedron;
  61863. };
  61864. /**
  61865. * Creates a decal mesh.
  61866. * 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
  61867. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61868. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61869. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61870. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61871. * @param name defines the name of the mesh
  61872. * @param sourceMesh defines the mesh where the decal must be applied
  61873. * @param options defines the options used to create the mesh
  61874. * @param scene defines the hosting scene
  61875. * @returns the decal mesh
  61876. * @see http://doc.babylonjs.com/how_to/decals
  61877. */
  61878. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61879. var indices = sourceMesh.getIndices();
  61880. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61881. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61882. var position = options.position || BABYLON.Vector3.Zero();
  61883. var normal = options.normal || BABYLON.Vector3.Up();
  61884. var size = options.size || BABYLON.Vector3.One();
  61885. var angle = options.angle || 0;
  61886. // Getting correct rotation
  61887. if (!normal) {
  61888. var target = new BABYLON.Vector3(0, 0, 1);
  61889. var camera = sourceMesh.getScene().activeCamera;
  61890. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61891. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61892. }
  61893. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61894. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61895. var pitch = Math.atan2(normal.y, len);
  61896. // Matrix
  61897. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61898. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61899. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61900. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61901. var vertexData = new BABYLON.VertexData();
  61902. vertexData.indices = [];
  61903. vertexData.positions = [];
  61904. vertexData.normals = [];
  61905. vertexData.uvs = [];
  61906. var currentVertexDataIndex = 0;
  61907. var extractDecalVector3 = function (indexId) {
  61908. var result = new BABYLON.PositionNormalVertex();
  61909. if (!indices || !positions || !normals) {
  61910. return result;
  61911. }
  61912. var vertexId = indices[indexId];
  61913. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61914. // Send vector to decal local world
  61915. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61916. // Get normal
  61917. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61918. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61919. return result;
  61920. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61921. var clip = function (vertices, axis) {
  61922. if (vertices.length === 0) {
  61923. return vertices;
  61924. }
  61925. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61926. var clipVertices = function (v0, v1) {
  61927. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61928. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61929. };
  61930. var result = new Array();
  61931. for (var index = 0; index < vertices.length; index += 3) {
  61932. var v1Out;
  61933. var v2Out;
  61934. var v3Out;
  61935. var total = 0;
  61936. var nV1 = null;
  61937. var nV2 = null;
  61938. var nV3 = null;
  61939. var nV4 = null;
  61940. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61941. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61942. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61943. v1Out = d1 > 0;
  61944. v2Out = d2 > 0;
  61945. v3Out = d3 > 0;
  61946. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61947. switch (total) {
  61948. case 0:
  61949. result.push(vertices[index]);
  61950. result.push(vertices[index + 1]);
  61951. result.push(vertices[index + 2]);
  61952. break;
  61953. case 1:
  61954. if (v1Out) {
  61955. nV1 = vertices[index + 1];
  61956. nV2 = vertices[index + 2];
  61957. nV3 = clipVertices(vertices[index], nV1);
  61958. nV4 = clipVertices(vertices[index], nV2);
  61959. }
  61960. if (v2Out) {
  61961. nV1 = vertices[index];
  61962. nV2 = vertices[index + 2];
  61963. nV3 = clipVertices(vertices[index + 1], nV1);
  61964. nV4 = clipVertices(vertices[index + 1], nV2);
  61965. result.push(nV3);
  61966. result.push(nV2.clone());
  61967. result.push(nV1.clone());
  61968. result.push(nV2.clone());
  61969. result.push(nV3.clone());
  61970. result.push(nV4);
  61971. break;
  61972. }
  61973. if (v3Out) {
  61974. nV1 = vertices[index];
  61975. nV2 = vertices[index + 1];
  61976. nV3 = clipVertices(vertices[index + 2], nV1);
  61977. nV4 = clipVertices(vertices[index + 2], nV2);
  61978. }
  61979. if (nV1 && nV2 && nV3 && nV4) {
  61980. result.push(nV1.clone());
  61981. result.push(nV2.clone());
  61982. result.push(nV3);
  61983. result.push(nV4);
  61984. result.push(nV3.clone());
  61985. result.push(nV2.clone());
  61986. }
  61987. break;
  61988. case 2:
  61989. if (!v1Out) {
  61990. nV1 = vertices[index].clone();
  61991. nV2 = clipVertices(nV1, vertices[index + 1]);
  61992. nV3 = clipVertices(nV1, vertices[index + 2]);
  61993. result.push(nV1);
  61994. result.push(nV2);
  61995. result.push(nV3);
  61996. }
  61997. if (!v2Out) {
  61998. nV1 = vertices[index + 1].clone();
  61999. nV2 = clipVertices(nV1, vertices[index + 2]);
  62000. nV3 = clipVertices(nV1, vertices[index]);
  62001. result.push(nV1);
  62002. result.push(nV2);
  62003. result.push(nV3);
  62004. }
  62005. if (!v3Out) {
  62006. nV1 = vertices[index + 2].clone();
  62007. nV2 = clipVertices(nV1, vertices[index]);
  62008. nV3 = clipVertices(nV1, vertices[index + 1]);
  62009. result.push(nV1);
  62010. result.push(nV2);
  62011. result.push(nV3);
  62012. }
  62013. break;
  62014. case 3:
  62015. break;
  62016. }
  62017. }
  62018. return result;
  62019. };
  62020. for (var index = 0; index < indices.length; index += 3) {
  62021. var faceVertices = new Array();
  62022. faceVertices.push(extractDecalVector3(index));
  62023. faceVertices.push(extractDecalVector3(index + 1));
  62024. faceVertices.push(extractDecalVector3(index + 2));
  62025. // Clip
  62026. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62027. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62028. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62029. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62030. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62031. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62032. if (faceVertices.length === 0) {
  62033. continue;
  62034. }
  62035. // Add UVs and get back to world
  62036. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62037. var vertex = faceVertices[vIndex];
  62038. //TODO check for Int32Array | Uint32Array | Uint16Array
  62039. vertexData.indices.push(currentVertexDataIndex);
  62040. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62041. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62042. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62043. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62044. currentVertexDataIndex++;
  62045. }
  62046. }
  62047. // Return mesh
  62048. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62049. vertexData.applyToMesh(decal);
  62050. decal.position = position.clone();
  62051. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62052. return decal;
  62053. };
  62054. // Privates
  62055. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62056. // extrusion geometry
  62057. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62058. var tangents = path3D.getTangents();
  62059. var normals = path3D.getNormals();
  62060. var binormals = path3D.getBinormals();
  62061. var distances = path3D.getDistances();
  62062. var angle = 0;
  62063. var returnScale = function () { return scale !== null ? scale : 1; };
  62064. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62065. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62066. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62067. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62068. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62069. for (var i = 0; i < curve.length; i++) {
  62070. var shapePath = new Array();
  62071. var angleStep = rotate(i, distances[i]);
  62072. var scaleRatio = scl(i, distances[i]);
  62073. for (var p = 0; p < shape.length; p++) {
  62074. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62075. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62076. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62077. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62078. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62079. shapePath[p] = rotated;
  62080. }
  62081. shapePaths[index] = shapePath;
  62082. angle += angleStep;
  62083. index++;
  62084. }
  62085. // cap
  62086. var capPath = function (shapePath) {
  62087. var pointCap = Array();
  62088. var barycenter = BABYLON.Vector3.Zero();
  62089. var i;
  62090. for (i = 0; i < shapePath.length; i++) {
  62091. barycenter.addInPlace(shapePath[i]);
  62092. }
  62093. barycenter.scaleInPlace(1.0 / shapePath.length);
  62094. for (i = 0; i < shapePath.length; i++) {
  62095. pointCap.push(barycenter);
  62096. }
  62097. return pointCap;
  62098. };
  62099. switch (cap) {
  62100. case BABYLON.Mesh.NO_CAP:
  62101. break;
  62102. case BABYLON.Mesh.CAP_START:
  62103. shapePaths[0] = capPath(shapePaths[2]);
  62104. shapePaths[1] = shapePaths[2];
  62105. break;
  62106. case BABYLON.Mesh.CAP_END:
  62107. shapePaths[index] = shapePaths[index - 1];
  62108. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62109. break;
  62110. case BABYLON.Mesh.CAP_ALL:
  62111. shapePaths[0] = capPath(shapePaths[2]);
  62112. shapePaths[1] = shapePaths[2];
  62113. shapePaths[index] = shapePaths[index - 1];
  62114. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62115. break;
  62116. default:
  62117. break;
  62118. }
  62119. return shapePaths;
  62120. };
  62121. var path3D;
  62122. var pathArray;
  62123. if (instance) { // instance update
  62124. path3D = (instance.path3D).update(curve);
  62125. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62126. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62127. return instance;
  62128. }
  62129. // extruded shape creation
  62130. path3D = new BABYLON.Path3D(curve);
  62131. var newShapePaths = new Array();
  62132. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62133. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62134. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62135. extrudedGeneric.pathArray = pathArray;
  62136. extrudedGeneric.path3D = path3D;
  62137. extrudedGeneric.cap = cap;
  62138. return extrudedGeneric;
  62139. };
  62140. return MeshBuilder;
  62141. }());
  62142. BABYLON.MeshBuilder = MeshBuilder;
  62143. })(BABYLON || (BABYLON = {}));
  62144. //# sourceMappingURL=babylon.meshBuilder.js.map
  62145. var BABYLON;
  62146. (function (BABYLON) {
  62147. /**
  62148. * Draco compression (https://google.github.io/draco/)
  62149. *
  62150. * This class wraps the Draco module.
  62151. *
  62152. * **Encoder**
  62153. *
  62154. * The encoder is not currently implemented.
  62155. *
  62156. * **Decoder**
  62157. *
  62158. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62159. *
  62160. * To update the configuration, use the following code:
  62161. * ```javascript
  62162. * BABYLON.DracoCompression.Configuration = {
  62163. * decoder: {
  62164. * wasmUrl: "<url to the WebAssembly library>",
  62165. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62166. * fallbackUrl: "<url to the fallback JavaScript library>",
  62167. * }
  62168. * };
  62169. * ```
  62170. *
  62171. * 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.
  62172. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62173. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62174. *
  62175. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62176. * ```javascript
  62177. * var dracoCompression = new BABYLON.DracoCompression();
  62178. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62179. * [BABYLON.VertexBuffer.PositionKind]: 0
  62180. * });
  62181. * ```
  62182. *
  62183. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62184. */
  62185. var DracoCompression = /** @class */ (function () {
  62186. /**
  62187. * Constructor
  62188. */
  62189. function DracoCompression() {
  62190. }
  62191. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62192. /**
  62193. * Returns true if the decoder is available.
  62194. */
  62195. get: function () {
  62196. if (typeof DracoDecoderModule !== "undefined") {
  62197. return true;
  62198. }
  62199. var decoder = DracoCompression.Configuration.decoder;
  62200. if (decoder) {
  62201. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62202. return true;
  62203. }
  62204. if (decoder.fallbackUrl) {
  62205. return true;
  62206. }
  62207. }
  62208. return false;
  62209. },
  62210. enumerable: true,
  62211. configurable: true
  62212. });
  62213. /**
  62214. * Stop all async operations and release resources.
  62215. */
  62216. DracoCompression.prototype.dispose = function () {
  62217. };
  62218. /**
  62219. * Decode Draco compressed mesh data to vertex data.
  62220. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62221. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62222. * @returns A promise that resolves with the decoded vertex data
  62223. */
  62224. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62225. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62226. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62227. var module = wrappedModule.module;
  62228. var vertexData = new BABYLON.VertexData();
  62229. var buffer = new module.DecoderBuffer();
  62230. buffer.Init(dataView, dataView.byteLength);
  62231. var decoder = new module.Decoder();
  62232. var geometry;
  62233. var status;
  62234. try {
  62235. var type = decoder.GetEncodedGeometryType(buffer);
  62236. switch (type) {
  62237. case module.TRIANGULAR_MESH:
  62238. geometry = new module.Mesh();
  62239. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62240. break;
  62241. case module.POINT_CLOUD:
  62242. geometry = new module.PointCloud();
  62243. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62244. break;
  62245. default:
  62246. throw new Error("Invalid geometry type " + type);
  62247. }
  62248. if (!status.ok() || !geometry.ptr) {
  62249. throw new Error(status.error_msg());
  62250. }
  62251. var numPoints = geometry.num_points();
  62252. if (type === module.TRIANGULAR_MESH) {
  62253. var numFaces = geometry.num_faces();
  62254. var faceIndices = new module.DracoInt32Array();
  62255. try {
  62256. var indices = new Uint32Array(numFaces * 3);
  62257. for (var i = 0; i < numFaces; i++) {
  62258. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62259. var offset = i * 3;
  62260. indices[offset + 0] = faceIndices.GetValue(0);
  62261. indices[offset + 1] = faceIndices.GetValue(1);
  62262. indices[offset + 2] = faceIndices.GetValue(2);
  62263. }
  62264. vertexData.indices = indices;
  62265. }
  62266. finally {
  62267. module.destroy(faceIndices);
  62268. }
  62269. }
  62270. for (var kind in attributes) {
  62271. var uniqueId = attributes[kind];
  62272. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62273. var dracoData = new module.DracoFloat32Array();
  62274. try {
  62275. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62276. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62277. for (var i = 0; i < babylonData.length; i++) {
  62278. babylonData[i] = dracoData.GetValue(i);
  62279. }
  62280. vertexData.set(babylonData, kind);
  62281. }
  62282. finally {
  62283. module.destroy(dracoData);
  62284. }
  62285. }
  62286. }
  62287. finally {
  62288. if (geometry) {
  62289. module.destroy(geometry);
  62290. }
  62291. module.destroy(decoder);
  62292. module.destroy(buffer);
  62293. }
  62294. return vertexData;
  62295. });
  62296. };
  62297. DracoCompression._GetDecoderModule = function () {
  62298. if (!DracoCompression._DecoderModulePromise) {
  62299. var promise = null;
  62300. var config_1 = {};
  62301. if (typeof DracoDecoderModule !== "undefined") {
  62302. promise = Promise.resolve();
  62303. }
  62304. else {
  62305. var decoder = DracoCompression.Configuration.decoder;
  62306. if (decoder) {
  62307. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62308. promise = Promise.all([
  62309. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62310. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62311. config_1.wasmBinary = data;
  62312. })
  62313. ]);
  62314. }
  62315. else if (decoder.fallbackUrl) {
  62316. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62317. }
  62318. }
  62319. }
  62320. if (!promise) {
  62321. throw new Error("Draco decoder module is not available");
  62322. }
  62323. DracoCompression._DecoderModulePromise = promise.then(function () {
  62324. return new Promise(function (resolve) {
  62325. config_1.onModuleLoaded = function (decoderModule) {
  62326. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62327. resolve({ module: decoderModule });
  62328. };
  62329. DracoDecoderModule(config_1);
  62330. });
  62331. });
  62332. }
  62333. return DracoCompression._DecoderModulePromise;
  62334. };
  62335. DracoCompression._LoadScriptAsync = function (url) {
  62336. return new Promise(function (resolve, reject) {
  62337. BABYLON.Tools.LoadScript(url, function () {
  62338. resolve();
  62339. }, function (message) {
  62340. reject(new Error(message));
  62341. });
  62342. });
  62343. };
  62344. DracoCompression._LoadFileAsync = function (url) {
  62345. return new Promise(function (resolve, reject) {
  62346. BABYLON.Tools.LoadFile(url, function (data) {
  62347. resolve(data);
  62348. }, undefined, undefined, true, function (request, exception) {
  62349. reject(exception);
  62350. });
  62351. });
  62352. };
  62353. /**
  62354. * The configuration. Defaults to the following urls:
  62355. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62356. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62357. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62358. */
  62359. DracoCompression.Configuration = {
  62360. decoder: {
  62361. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62362. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62363. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62364. }
  62365. };
  62366. return DracoCompression;
  62367. }());
  62368. BABYLON.DracoCompression = DracoCompression;
  62369. })(BABYLON || (BABYLON = {}));
  62370. //# sourceMappingURL=babylon.dracoCompression.js.map
  62371. var BABYLON;
  62372. (function (BABYLON) {
  62373. var AudioEngine = /** @class */ (function () {
  62374. function AudioEngine() {
  62375. this._audioContext = null;
  62376. this._audioContextInitialized = false;
  62377. this.canUseWebAudio = false;
  62378. this.WarnedWebAudioUnsupported = false;
  62379. this.unlocked = false;
  62380. this.isMP3supported = false;
  62381. this.isOGGsupported = false;
  62382. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62383. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62384. this.canUseWebAudio = true;
  62385. }
  62386. var audioElem = document.createElement('audio');
  62387. try {
  62388. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62389. this.isMP3supported = true;
  62390. }
  62391. }
  62392. catch (e) {
  62393. // protect error during capability check.
  62394. }
  62395. try {
  62396. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62397. this.isOGGsupported = true;
  62398. }
  62399. }
  62400. catch (e) {
  62401. // protect error during capability check.
  62402. }
  62403. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62404. this._unlockiOSaudio();
  62405. }
  62406. else {
  62407. this.unlocked = true;
  62408. }
  62409. }
  62410. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62411. get: function () {
  62412. if (!this._audioContextInitialized) {
  62413. this._initializeAudioContext();
  62414. }
  62415. return this._audioContext;
  62416. },
  62417. enumerable: true,
  62418. configurable: true
  62419. });
  62420. AudioEngine.prototype._unlockiOSaudio = function () {
  62421. var _this = this;
  62422. var unlockaudio = function () {
  62423. if (!_this.audioContext) {
  62424. return;
  62425. }
  62426. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62427. var source = _this.audioContext.createBufferSource();
  62428. source.buffer = buffer;
  62429. source.connect(_this.audioContext.destination);
  62430. source.start(0);
  62431. setTimeout(function () {
  62432. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62433. _this.unlocked = true;
  62434. window.removeEventListener('touchend', unlockaudio, false);
  62435. if (_this.onAudioUnlocked) {
  62436. _this.onAudioUnlocked();
  62437. }
  62438. }
  62439. }, 0);
  62440. };
  62441. window.addEventListener('touchend', unlockaudio, false);
  62442. };
  62443. AudioEngine.prototype._initializeAudioContext = function () {
  62444. try {
  62445. if (this.canUseWebAudio) {
  62446. this._audioContext = new AudioContext();
  62447. // create a global volume gain node
  62448. this.masterGain = this._audioContext.createGain();
  62449. this.masterGain.gain.value = 1;
  62450. this.masterGain.connect(this._audioContext.destination);
  62451. this._audioContextInitialized = true;
  62452. }
  62453. }
  62454. catch (e) {
  62455. this.canUseWebAudio = false;
  62456. BABYLON.Tools.Error("Web Audio: " + e.message);
  62457. }
  62458. };
  62459. AudioEngine.prototype.dispose = function () {
  62460. if (this.canUseWebAudio && this._audioContextInitialized) {
  62461. if (this._connectedAnalyser && this._audioContext) {
  62462. this._connectedAnalyser.stopDebugCanvas();
  62463. this._connectedAnalyser.dispose();
  62464. this.masterGain.disconnect();
  62465. this.masterGain.connect(this._audioContext.destination);
  62466. this._connectedAnalyser = null;
  62467. }
  62468. this.masterGain.gain.value = 1;
  62469. }
  62470. this.WarnedWebAudioUnsupported = false;
  62471. };
  62472. AudioEngine.prototype.getGlobalVolume = function () {
  62473. if (this.canUseWebAudio && this._audioContextInitialized) {
  62474. return this.masterGain.gain.value;
  62475. }
  62476. else {
  62477. return -1;
  62478. }
  62479. };
  62480. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62481. if (this.canUseWebAudio && this._audioContextInitialized) {
  62482. this.masterGain.gain.value = newVolume;
  62483. }
  62484. };
  62485. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62486. if (this._connectedAnalyser) {
  62487. this._connectedAnalyser.stopDebugCanvas();
  62488. }
  62489. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62490. this._connectedAnalyser = analyser;
  62491. this.masterGain.disconnect();
  62492. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62493. }
  62494. };
  62495. return AudioEngine;
  62496. }());
  62497. BABYLON.AudioEngine = AudioEngine;
  62498. })(BABYLON || (BABYLON = {}));
  62499. //# sourceMappingURL=babylon.audioEngine.js.map
  62500. var BABYLON;
  62501. (function (BABYLON) {
  62502. var Sound = /** @class */ (function () {
  62503. /**
  62504. * Create a sound and attach it to a scene
  62505. * @param name Name of your sound
  62506. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62507. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62508. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62509. */
  62510. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62511. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62512. var _this = this;
  62513. this.autoplay = false;
  62514. this.loop = false;
  62515. this.useCustomAttenuation = false;
  62516. this.spatialSound = false;
  62517. this.refDistance = 1;
  62518. this.rolloffFactor = 1;
  62519. this.maxDistance = 100;
  62520. this.distanceModel = "linear";
  62521. this._panningModel = "equalpower";
  62522. this._playbackRate = 1;
  62523. this._streaming = false;
  62524. this._startTime = 0;
  62525. this._startOffset = 0;
  62526. this._position = BABYLON.Vector3.Zero();
  62527. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62528. this._volume = 1;
  62529. this._isReadyToPlay = false;
  62530. this.isPlaying = false;
  62531. this.isPaused = false;
  62532. this._isDirectional = false;
  62533. // Used if you'd like to create a directional sound.
  62534. // If not set, the sound will be omnidirectional
  62535. this._coneInnerAngle = 360;
  62536. this._coneOuterAngle = 360;
  62537. this._coneOuterGain = 0;
  62538. this._isOutputConnected = false;
  62539. this._urlType = "Unknown";
  62540. this.name = name;
  62541. this._scene = scene;
  62542. this._readyToPlayCallback = readyToPlayCallback;
  62543. // Default custom attenuation function is a linear attenuation
  62544. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62545. if (currentDistance < maxDistance) {
  62546. return currentVolume * (1 - currentDistance / maxDistance);
  62547. }
  62548. else {
  62549. return 0;
  62550. }
  62551. };
  62552. if (options) {
  62553. this.autoplay = options.autoplay || false;
  62554. this.loop = options.loop || false;
  62555. // if volume === 0, we need another way to check this option
  62556. if (options.volume !== undefined) {
  62557. this._volume = options.volume;
  62558. }
  62559. this.spatialSound = options.spatialSound || false;
  62560. this.maxDistance = options.maxDistance || 100;
  62561. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62562. this.rolloffFactor = options.rolloffFactor || 1;
  62563. this.refDistance = options.refDistance || 1;
  62564. this.distanceModel = options.distanceModel || "linear";
  62565. this._playbackRate = options.playbackRate || 1;
  62566. this._streaming = options.streaming || false;
  62567. }
  62568. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62569. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62570. this._soundGain.gain.value = this._volume;
  62571. this._inputAudioNode = this._soundGain;
  62572. this._ouputAudioNode = this._soundGain;
  62573. if (this.spatialSound) {
  62574. this._createSpatialParameters();
  62575. }
  62576. this._scene.mainSoundTrack.AddSound(this);
  62577. var validParameter = true;
  62578. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62579. if (urlOrArrayBuffer) {
  62580. try {
  62581. if (typeof (urlOrArrayBuffer) === "string")
  62582. this._urlType = "String";
  62583. if (Array.isArray(urlOrArrayBuffer))
  62584. this._urlType = "Array";
  62585. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62586. this._urlType = "ArrayBuffer";
  62587. var urls = [];
  62588. var codecSupportedFound = false;
  62589. switch (this._urlType) {
  62590. case "ArrayBuffer":
  62591. if (urlOrArrayBuffer.byteLength > 0) {
  62592. codecSupportedFound = true;
  62593. this._soundLoaded(urlOrArrayBuffer);
  62594. }
  62595. break;
  62596. case "String":
  62597. urls.push(urlOrArrayBuffer);
  62598. case "Array":
  62599. if (urls.length === 0)
  62600. urls = urlOrArrayBuffer;
  62601. // If we found a supported format, we load it immediately and stop the loop
  62602. for (var i = 0; i < urls.length; i++) {
  62603. var url = urls[i];
  62604. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62605. codecSupportedFound = true;
  62606. }
  62607. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62608. codecSupportedFound = true;
  62609. }
  62610. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62611. codecSupportedFound = true;
  62612. }
  62613. if (url.indexOf("blob:") !== -1) {
  62614. codecSupportedFound = true;
  62615. }
  62616. if (codecSupportedFound) {
  62617. // Loading sound using XHR2
  62618. if (!this._streaming) {
  62619. this._scene._loadFile(url, function (data) {
  62620. _this._soundLoaded(data);
  62621. }, undefined, true, true, function (exception) {
  62622. if (exception) {
  62623. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62624. }
  62625. BABYLON.Tools.Error("Sound creation aborted.");
  62626. _this._scene.mainSoundTrack.RemoveSound(_this);
  62627. });
  62628. }
  62629. // Streaming sound using HTML5 Audio tag
  62630. else {
  62631. this._htmlAudioElement = new Audio(url);
  62632. this._htmlAudioElement.controls = false;
  62633. this._htmlAudioElement.loop = this.loop;
  62634. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62635. this._htmlAudioElement.preload = "auto";
  62636. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62637. _this._isReadyToPlay = true;
  62638. if (_this.autoplay) {
  62639. _this.play();
  62640. }
  62641. if (_this._readyToPlayCallback) {
  62642. _this._readyToPlayCallback();
  62643. }
  62644. });
  62645. document.body.appendChild(this._htmlAudioElement);
  62646. }
  62647. break;
  62648. }
  62649. }
  62650. break;
  62651. default:
  62652. validParameter = false;
  62653. break;
  62654. }
  62655. if (!validParameter) {
  62656. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62657. }
  62658. else {
  62659. if (!codecSupportedFound) {
  62660. this._isReadyToPlay = true;
  62661. // Simulating a ready to play event to avoid breaking code path
  62662. if (this._readyToPlayCallback) {
  62663. window.setTimeout(function () {
  62664. if (_this._readyToPlayCallback) {
  62665. _this._readyToPlayCallback();
  62666. }
  62667. }, 1000);
  62668. }
  62669. }
  62670. }
  62671. }
  62672. catch (ex) {
  62673. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62674. this._scene.mainSoundTrack.RemoveSound(this);
  62675. }
  62676. }
  62677. }
  62678. else {
  62679. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62680. this._scene.mainSoundTrack.AddSound(this);
  62681. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62682. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62683. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62684. }
  62685. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62686. if (this._readyToPlayCallback) {
  62687. window.setTimeout(function () {
  62688. if (_this._readyToPlayCallback) {
  62689. _this._readyToPlayCallback();
  62690. }
  62691. }, 1000);
  62692. }
  62693. }
  62694. }
  62695. Sound.prototype.dispose = function () {
  62696. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62697. if (this.isPlaying) {
  62698. this.stop();
  62699. }
  62700. this._isReadyToPlay = false;
  62701. if (this.soundTrackId === -1) {
  62702. this._scene.mainSoundTrack.RemoveSound(this);
  62703. }
  62704. else {
  62705. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62706. }
  62707. if (this._soundGain) {
  62708. this._soundGain.disconnect();
  62709. this._soundGain = null;
  62710. }
  62711. if (this._soundPanner) {
  62712. this._soundPanner.disconnect();
  62713. this._soundPanner = null;
  62714. }
  62715. if (this._soundSource) {
  62716. this._soundSource.disconnect();
  62717. this._soundSource = null;
  62718. }
  62719. this._audioBuffer = null;
  62720. if (this._htmlAudioElement) {
  62721. this._htmlAudioElement.pause();
  62722. this._htmlAudioElement.src = "";
  62723. document.body.removeChild(this._htmlAudioElement);
  62724. }
  62725. if (this._connectedMesh && this._registerFunc) {
  62726. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62727. this._connectedMesh = null;
  62728. }
  62729. }
  62730. };
  62731. Sound.prototype.isReady = function () {
  62732. return this._isReadyToPlay;
  62733. };
  62734. Sound.prototype._soundLoaded = function (audioData) {
  62735. var _this = this;
  62736. if (!BABYLON.Engine.audioEngine.audioContext) {
  62737. return;
  62738. }
  62739. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62740. _this._audioBuffer = buffer;
  62741. _this._isReadyToPlay = true;
  62742. if (_this.autoplay) {
  62743. _this.play();
  62744. }
  62745. if (_this._readyToPlayCallback) {
  62746. _this._readyToPlayCallback();
  62747. }
  62748. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62749. };
  62750. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62751. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62752. this._audioBuffer = audioBuffer;
  62753. this._isReadyToPlay = true;
  62754. }
  62755. };
  62756. Sound.prototype.updateOptions = function (options) {
  62757. if (options) {
  62758. this.loop = options.loop || this.loop;
  62759. this.maxDistance = options.maxDistance || this.maxDistance;
  62760. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62761. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62762. this.refDistance = options.refDistance || this.refDistance;
  62763. this.distanceModel = options.distanceModel || this.distanceModel;
  62764. this._playbackRate = options.playbackRate || this._playbackRate;
  62765. this._updateSpatialParameters();
  62766. if (this.isPlaying) {
  62767. if (this._streaming) {
  62768. this._htmlAudioElement.playbackRate = this._playbackRate;
  62769. }
  62770. else {
  62771. if (this._soundSource) {
  62772. this._soundSource.playbackRate.value = this._playbackRate;
  62773. }
  62774. }
  62775. }
  62776. }
  62777. };
  62778. Sound.prototype._createSpatialParameters = function () {
  62779. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62780. if (this._scene.headphone) {
  62781. this._panningModel = "HRTF";
  62782. }
  62783. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62784. this._updateSpatialParameters();
  62785. this._soundPanner.connect(this._ouputAudioNode);
  62786. this._inputAudioNode = this._soundPanner;
  62787. }
  62788. };
  62789. Sound.prototype._updateSpatialParameters = function () {
  62790. if (this.spatialSound && this._soundPanner) {
  62791. if (this.useCustomAttenuation) {
  62792. // Tricks to disable in a way embedded Web Audio attenuation
  62793. this._soundPanner.distanceModel = "linear";
  62794. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62795. this._soundPanner.refDistance = 1;
  62796. this._soundPanner.rolloffFactor = 1;
  62797. this._soundPanner.panningModel = this._panningModel;
  62798. }
  62799. else {
  62800. this._soundPanner.distanceModel = this.distanceModel;
  62801. this._soundPanner.maxDistance = this.maxDistance;
  62802. this._soundPanner.refDistance = this.refDistance;
  62803. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62804. this._soundPanner.panningModel = this._panningModel;
  62805. }
  62806. }
  62807. };
  62808. Sound.prototype.switchPanningModelToHRTF = function () {
  62809. this._panningModel = "HRTF";
  62810. this._switchPanningModel();
  62811. };
  62812. Sound.prototype.switchPanningModelToEqualPower = function () {
  62813. this._panningModel = "equalpower";
  62814. this._switchPanningModel();
  62815. };
  62816. Sound.prototype._switchPanningModel = function () {
  62817. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62818. this._soundPanner.panningModel = this._panningModel;
  62819. }
  62820. };
  62821. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62823. if (this._isOutputConnected) {
  62824. this._ouputAudioNode.disconnect();
  62825. }
  62826. this._ouputAudioNode.connect(soundTrackAudioNode);
  62827. this._isOutputConnected = true;
  62828. }
  62829. };
  62830. /**
  62831. * Transform this sound into a directional source
  62832. * @param coneInnerAngle Size of the inner cone in degree
  62833. * @param coneOuterAngle Size of the outer cone in degree
  62834. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62835. */
  62836. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62837. if (coneOuterAngle < coneInnerAngle) {
  62838. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62839. return;
  62840. }
  62841. this._coneInnerAngle = coneInnerAngle;
  62842. this._coneOuterAngle = coneOuterAngle;
  62843. this._coneOuterGain = coneOuterGain;
  62844. this._isDirectional = true;
  62845. if (this.isPlaying && this.loop) {
  62846. this.stop();
  62847. this.play();
  62848. }
  62849. };
  62850. Sound.prototype.setPosition = function (newPosition) {
  62851. this._position = newPosition;
  62852. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62853. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62854. }
  62855. };
  62856. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62857. this._localDirection = newLocalDirection;
  62858. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62859. this._updateDirection();
  62860. }
  62861. };
  62862. Sound.prototype._updateDirection = function () {
  62863. if (!this._connectedMesh || !this._soundPanner) {
  62864. return;
  62865. }
  62866. var mat = this._connectedMesh.getWorldMatrix();
  62867. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62868. direction.normalize();
  62869. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62870. };
  62871. Sound.prototype.updateDistanceFromListener = function () {
  62872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62873. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62874. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62875. }
  62876. };
  62877. Sound.prototype.setAttenuationFunction = function (callback) {
  62878. this._customAttenuationFunction = callback;
  62879. };
  62880. /**
  62881. * Play the sound
  62882. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62883. * @param offset (optional) Start the sound setting it at a specific time
  62884. */
  62885. Sound.prototype.play = function (time, offset) {
  62886. var _this = this;
  62887. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62888. try {
  62889. if (this._startOffset < 0) {
  62890. time = -this._startOffset;
  62891. this._startOffset = 0;
  62892. }
  62893. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62894. if (!this._soundSource || !this._streamingSource) {
  62895. if (this.spatialSound && this._soundPanner) {
  62896. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62897. if (this._isDirectional) {
  62898. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62899. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62900. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62901. if (this._connectedMesh) {
  62902. this._updateDirection();
  62903. }
  62904. else {
  62905. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62906. }
  62907. }
  62908. }
  62909. }
  62910. if (this._streaming) {
  62911. if (!this._streamingSource) {
  62912. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62913. this._htmlAudioElement.onended = function () { _this._onended(); };
  62914. this._htmlAudioElement.playbackRate = this._playbackRate;
  62915. }
  62916. this._streamingSource.disconnect();
  62917. this._streamingSource.connect(this._inputAudioNode);
  62918. this._htmlAudioElement.play();
  62919. }
  62920. else {
  62921. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62922. this._soundSource.buffer = this._audioBuffer;
  62923. this._soundSource.connect(this._inputAudioNode);
  62924. this._soundSource.loop = this.loop;
  62925. this._soundSource.playbackRate.value = this._playbackRate;
  62926. this._soundSource.onended = function () { _this._onended(); };
  62927. if (this._soundSource.buffer) {
  62928. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62929. }
  62930. }
  62931. this._startTime = startTime;
  62932. this.isPlaying = true;
  62933. this.isPaused = false;
  62934. }
  62935. catch (ex) {
  62936. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62937. }
  62938. }
  62939. };
  62940. Sound.prototype._onended = function () {
  62941. this.isPlaying = false;
  62942. if (this.onended) {
  62943. this.onended();
  62944. }
  62945. };
  62946. /**
  62947. * Stop the sound
  62948. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62949. */
  62950. Sound.prototype.stop = function (time) {
  62951. if (this.isPlaying) {
  62952. if (this._streaming) {
  62953. this._htmlAudioElement.pause();
  62954. // Test needed for Firefox or it will generate an Invalid State Error
  62955. if (this._htmlAudioElement.currentTime > 0) {
  62956. this._htmlAudioElement.currentTime = 0;
  62957. }
  62958. }
  62959. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62960. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62961. this._soundSource.stop(stopTime);
  62962. this._soundSource.onended = function () { };
  62963. if (!this.isPaused) {
  62964. this._startOffset = 0;
  62965. }
  62966. }
  62967. this.isPlaying = false;
  62968. }
  62969. };
  62970. Sound.prototype.pause = function () {
  62971. if (this.isPlaying) {
  62972. this.isPaused = true;
  62973. if (this._streaming) {
  62974. this._htmlAudioElement.pause();
  62975. }
  62976. else if (BABYLON.Engine.audioEngine.audioContext) {
  62977. this.stop(0);
  62978. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62979. }
  62980. }
  62981. };
  62982. Sound.prototype.setVolume = function (newVolume, time) {
  62983. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62984. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62985. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62986. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62987. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62988. }
  62989. else {
  62990. this._soundGain.gain.value = newVolume;
  62991. }
  62992. }
  62993. this._volume = newVolume;
  62994. };
  62995. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62996. this._playbackRate = newPlaybackRate;
  62997. if (this.isPlaying) {
  62998. if (this._streaming) {
  62999. this._htmlAudioElement.playbackRate = this._playbackRate;
  63000. }
  63001. else if (this._soundSource) {
  63002. this._soundSource.playbackRate.value = this._playbackRate;
  63003. }
  63004. }
  63005. };
  63006. Sound.prototype.getVolume = function () {
  63007. return this._volume;
  63008. };
  63009. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63010. var _this = this;
  63011. if (this._connectedMesh && this._registerFunc) {
  63012. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63013. this._registerFunc = null;
  63014. }
  63015. this._connectedMesh = meshToConnectTo;
  63016. if (!this.spatialSound) {
  63017. this.spatialSound = true;
  63018. this._createSpatialParameters();
  63019. if (this.isPlaying && this.loop) {
  63020. this.stop();
  63021. this.play();
  63022. }
  63023. }
  63024. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63025. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63026. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63027. };
  63028. Sound.prototype.detachFromMesh = function () {
  63029. if (this._connectedMesh && this._registerFunc) {
  63030. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63031. this._registerFunc = null;
  63032. this._connectedMesh = null;
  63033. }
  63034. };
  63035. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63036. if (!node.getBoundingInfo) {
  63037. return;
  63038. }
  63039. var mesh = node;
  63040. var boundingInfo = mesh.getBoundingInfo();
  63041. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63043. this._updateDirection();
  63044. }
  63045. };
  63046. Sound.prototype.clone = function () {
  63047. var _this = this;
  63048. if (!this._streaming) {
  63049. var setBufferAndRun = function () {
  63050. if (_this._isReadyToPlay) {
  63051. clonedSound._audioBuffer = _this.getAudioBuffer();
  63052. clonedSound._isReadyToPlay = true;
  63053. if (clonedSound.autoplay) {
  63054. clonedSound.play();
  63055. }
  63056. }
  63057. else {
  63058. window.setTimeout(setBufferAndRun, 300);
  63059. }
  63060. };
  63061. var currentOptions = {
  63062. autoplay: this.autoplay, loop: this.loop,
  63063. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63064. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63065. refDistance: this.refDistance, distanceModel: this.distanceModel
  63066. };
  63067. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63068. if (this.useCustomAttenuation) {
  63069. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63070. }
  63071. clonedSound.setPosition(this._position);
  63072. clonedSound.setPlaybackRate(this._playbackRate);
  63073. setBufferAndRun();
  63074. return clonedSound;
  63075. }
  63076. // Can't clone a streaming sound
  63077. else {
  63078. return null;
  63079. }
  63080. };
  63081. Sound.prototype.getAudioBuffer = function () {
  63082. return this._audioBuffer;
  63083. };
  63084. Sound.prototype.serialize = function () {
  63085. var serializationObject = {
  63086. name: this.name,
  63087. url: this.name,
  63088. autoplay: this.autoplay,
  63089. loop: this.loop,
  63090. volume: this._volume,
  63091. spatialSound: this.spatialSound,
  63092. maxDistance: this.maxDistance,
  63093. rolloffFactor: this.rolloffFactor,
  63094. refDistance: this.refDistance,
  63095. distanceModel: this.distanceModel,
  63096. playbackRate: this._playbackRate,
  63097. panningModel: this._panningModel,
  63098. soundTrackId: this.soundTrackId
  63099. };
  63100. if (this.spatialSound) {
  63101. if (this._connectedMesh)
  63102. serializationObject.connectedMeshId = this._connectedMesh.id;
  63103. serializationObject.position = this._position.asArray();
  63104. serializationObject.refDistance = this.refDistance;
  63105. serializationObject.distanceModel = this.distanceModel;
  63106. serializationObject.isDirectional = this._isDirectional;
  63107. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63108. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63109. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63110. serializationObject.coneOuterGain = this._coneOuterGain;
  63111. }
  63112. return serializationObject;
  63113. };
  63114. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63115. var soundName = parsedSound.name;
  63116. var soundUrl;
  63117. if (parsedSound.url) {
  63118. soundUrl = rootUrl + parsedSound.url;
  63119. }
  63120. else {
  63121. soundUrl = rootUrl + soundName;
  63122. }
  63123. var options = {
  63124. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63125. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63126. rolloffFactor: parsedSound.rolloffFactor,
  63127. refDistance: parsedSound.refDistance,
  63128. distanceModel: parsedSound.distanceModel,
  63129. playbackRate: parsedSound.playbackRate
  63130. };
  63131. var newSound;
  63132. if (!sourceSound) {
  63133. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63134. scene._addPendingData(newSound);
  63135. }
  63136. else {
  63137. var setBufferAndRun = function () {
  63138. if (sourceSound._isReadyToPlay) {
  63139. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63140. newSound._isReadyToPlay = true;
  63141. if (newSound.autoplay) {
  63142. newSound.play();
  63143. }
  63144. }
  63145. else {
  63146. window.setTimeout(setBufferAndRun, 300);
  63147. }
  63148. };
  63149. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63150. setBufferAndRun();
  63151. }
  63152. if (parsedSound.position) {
  63153. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63154. newSound.setPosition(soundPosition);
  63155. }
  63156. if (parsedSound.isDirectional) {
  63157. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63158. if (parsedSound.localDirectionToMesh) {
  63159. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63160. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63161. }
  63162. }
  63163. if (parsedSound.connectedMeshId) {
  63164. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63165. if (connectedMesh) {
  63166. newSound.attachToMesh(connectedMesh);
  63167. }
  63168. }
  63169. return newSound;
  63170. };
  63171. return Sound;
  63172. }());
  63173. BABYLON.Sound = Sound;
  63174. })(BABYLON || (BABYLON = {}));
  63175. //# sourceMappingURL=babylon.sound.js.map
  63176. var BABYLON;
  63177. (function (BABYLON) {
  63178. var SoundTrack = /** @class */ (function () {
  63179. function SoundTrack(scene, options) {
  63180. this.id = -1;
  63181. this._isMainTrack = false;
  63182. this._isInitialized = false;
  63183. this._scene = scene;
  63184. this.soundCollection = new Array();
  63185. this._options = options;
  63186. if (!this._isMainTrack) {
  63187. this._scene.soundTracks.push(this);
  63188. this.id = this._scene.soundTracks.length - 1;
  63189. }
  63190. }
  63191. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63192. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63193. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63194. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63195. if (this._options) {
  63196. if (this._options.volume) {
  63197. this._outputAudioNode.gain.value = this._options.volume;
  63198. }
  63199. if (this._options.mainTrack) {
  63200. this._isMainTrack = this._options.mainTrack;
  63201. }
  63202. }
  63203. this._isInitialized = true;
  63204. }
  63205. };
  63206. SoundTrack.prototype.dispose = function () {
  63207. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63208. if (this._connectedAnalyser) {
  63209. this._connectedAnalyser.stopDebugCanvas();
  63210. }
  63211. while (this.soundCollection.length) {
  63212. this.soundCollection[0].dispose();
  63213. }
  63214. if (this._outputAudioNode) {
  63215. this._outputAudioNode.disconnect();
  63216. }
  63217. this._outputAudioNode = null;
  63218. }
  63219. };
  63220. SoundTrack.prototype.AddSound = function (sound) {
  63221. if (!this._isInitialized) {
  63222. this._initializeSoundTrackAudioGraph();
  63223. }
  63224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63225. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63226. }
  63227. if (sound.soundTrackId) {
  63228. if (sound.soundTrackId === -1) {
  63229. this._scene.mainSoundTrack.RemoveSound(sound);
  63230. }
  63231. else {
  63232. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63233. }
  63234. }
  63235. this.soundCollection.push(sound);
  63236. sound.soundTrackId = this.id;
  63237. };
  63238. SoundTrack.prototype.RemoveSound = function (sound) {
  63239. var index = this.soundCollection.indexOf(sound);
  63240. if (index !== -1) {
  63241. this.soundCollection.splice(index, 1);
  63242. }
  63243. };
  63244. SoundTrack.prototype.setVolume = function (newVolume) {
  63245. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63246. this._outputAudioNode.gain.value = newVolume;
  63247. }
  63248. };
  63249. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63251. for (var i = 0; i < this.soundCollection.length; i++) {
  63252. this.soundCollection[i].switchPanningModelToHRTF();
  63253. }
  63254. }
  63255. };
  63256. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63257. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63258. for (var i = 0; i < this.soundCollection.length; i++) {
  63259. this.soundCollection[i].switchPanningModelToEqualPower();
  63260. }
  63261. }
  63262. };
  63263. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63264. if (this._connectedAnalyser) {
  63265. this._connectedAnalyser.stopDebugCanvas();
  63266. }
  63267. this._connectedAnalyser = analyser;
  63268. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63269. this._outputAudioNode.disconnect();
  63270. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63271. }
  63272. };
  63273. return SoundTrack;
  63274. }());
  63275. BABYLON.SoundTrack = SoundTrack;
  63276. })(BABYLON || (BABYLON = {}));
  63277. //# sourceMappingURL=babylon.soundtrack.js.map
  63278. var BABYLON;
  63279. (function (BABYLON) {
  63280. /**
  63281. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63282. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63283. */
  63284. var Analyser = /** @class */ (function () {
  63285. /**
  63286. * Creates a new analyser
  63287. * @param scene defines hosting scene
  63288. */
  63289. function Analyser(scene) {
  63290. /**
  63291. * Gets or sets the smoothing
  63292. * @ignorenaming
  63293. */
  63294. this.SMOOTHING = 0.75;
  63295. /**
  63296. * Gets or sets the FFT table size
  63297. * @ignorenaming
  63298. */
  63299. this.FFT_SIZE = 512;
  63300. /**
  63301. * Gets or sets the bar graph amplitude
  63302. * @ignorenaming
  63303. */
  63304. this.BARGRAPHAMPLITUDE = 256;
  63305. /**
  63306. * Gets or sets the position of the debug canvas
  63307. * @ignorenaming
  63308. */
  63309. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63310. /**
  63311. * Gets or sets the debug canvas size
  63312. * @ignorenaming
  63313. */
  63314. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63315. this._scene = scene;
  63316. this._audioEngine = BABYLON.Engine.audioEngine;
  63317. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63318. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63319. this._webAudioAnalyser.minDecibels = -140;
  63320. this._webAudioAnalyser.maxDecibels = 0;
  63321. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63322. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63323. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63324. }
  63325. }
  63326. /**
  63327. * Get the number of data values you will have to play with for the visualization
  63328. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63329. * @returns a number
  63330. */
  63331. Analyser.prototype.getFrequencyBinCount = function () {
  63332. if (this._audioEngine.canUseWebAudio) {
  63333. return this._webAudioAnalyser.frequencyBinCount;
  63334. }
  63335. else {
  63336. return 0;
  63337. }
  63338. };
  63339. /**
  63340. * Gets the current frequency data as a byte array
  63341. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63342. * @returns a Uint8Array
  63343. */
  63344. Analyser.prototype.getByteFrequencyData = function () {
  63345. if (this._audioEngine.canUseWebAudio) {
  63346. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63347. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63348. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63349. }
  63350. return this._byteFreqs;
  63351. };
  63352. /**
  63353. * Gets the current waveform as a byte array
  63354. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63355. * @returns a Uint8Array
  63356. */
  63357. Analyser.prototype.getByteTimeDomainData = function () {
  63358. if (this._audioEngine.canUseWebAudio) {
  63359. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63360. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63361. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63362. }
  63363. return this._byteTime;
  63364. };
  63365. /**
  63366. * Gets the current frequency data as a float array
  63367. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63368. * @returns a Float32Array
  63369. */
  63370. Analyser.prototype.getFloatFrequencyData = function () {
  63371. if (this._audioEngine.canUseWebAudio) {
  63372. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63373. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63374. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63375. }
  63376. return this._floatFreqs;
  63377. };
  63378. /**
  63379. * Renders the debug canvas
  63380. */
  63381. Analyser.prototype.drawDebugCanvas = function () {
  63382. var _this = this;
  63383. if (this._audioEngine.canUseWebAudio) {
  63384. if (!this._debugCanvas) {
  63385. this._debugCanvas = document.createElement("canvas");
  63386. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63387. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63388. this._debugCanvas.style.position = "absolute";
  63389. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63390. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63391. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63392. document.body.appendChild(this._debugCanvas);
  63393. this._registerFunc = function () {
  63394. _this.drawDebugCanvas();
  63395. };
  63396. this._scene.registerBeforeRender(this._registerFunc);
  63397. }
  63398. if (this._registerFunc && this._debugCanvasContext) {
  63399. var workingArray = this.getByteFrequencyData();
  63400. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63401. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63402. // Draw the frequency domain chart.
  63403. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63404. var value = workingArray[i];
  63405. var percent = value / this.BARGRAPHAMPLITUDE;
  63406. var height = this.DEBUGCANVASSIZE.height * percent;
  63407. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63408. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63409. var hue = i / this.getFrequencyBinCount() * 360;
  63410. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63411. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63412. }
  63413. }
  63414. }
  63415. };
  63416. /**
  63417. * Stops rendering the debug canvas and removes it
  63418. */
  63419. Analyser.prototype.stopDebugCanvas = function () {
  63420. if (this._debugCanvas) {
  63421. if (this._registerFunc) {
  63422. this._scene.unregisterBeforeRender(this._registerFunc);
  63423. this._registerFunc = null;
  63424. }
  63425. document.body.removeChild(this._debugCanvas);
  63426. this._debugCanvas = null;
  63427. this._debugCanvasContext = null;
  63428. }
  63429. };
  63430. /**
  63431. * Connects two audio nodes
  63432. * @param inputAudioNode defines first node to connect
  63433. * @param outputAudioNode defines second node to connect
  63434. */
  63435. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63436. if (this._audioEngine.canUseWebAudio) {
  63437. inputAudioNode.connect(this._webAudioAnalyser);
  63438. this._webAudioAnalyser.connect(outputAudioNode);
  63439. }
  63440. };
  63441. /**
  63442. * Releases all associated resources
  63443. */
  63444. Analyser.prototype.dispose = function () {
  63445. if (this._audioEngine.canUseWebAudio) {
  63446. this._webAudioAnalyser.disconnect();
  63447. }
  63448. };
  63449. return Analyser;
  63450. }());
  63451. BABYLON.Analyser = Analyser;
  63452. })(BABYLON || (BABYLON = {}));
  63453. //# sourceMappingURL=babylon.analyser.js.map
  63454. var BABYLON;
  63455. (function (BABYLON) {
  63456. var CubeTexture = /** @class */ (function (_super) {
  63457. __extends(CubeTexture, _super);
  63458. /**
  63459. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63460. * as prefiltered data.
  63461. * @param rootUrl defines the url of the texture or the root name of the six images
  63462. * @param scene defines the scene the texture is attached to
  63463. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63464. * @param noMipmap defines if mipmaps should be created or not
  63465. * @param files defines the six files to load for the different faces
  63466. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63467. * @param onError defines a callback triggered in case of error during load
  63468. * @param format defines the internal format to use for the texture once loaded
  63469. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63470. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63471. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63472. * @return the cube texture
  63473. */
  63474. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63475. if (extensions === void 0) { extensions = null; }
  63476. if (noMipmap === void 0) { noMipmap = false; }
  63477. if (files === void 0) { files = null; }
  63478. if (onLoad === void 0) { onLoad = null; }
  63479. if (onError === void 0) { onError = null; }
  63480. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63481. if (prefiltered === void 0) { prefiltered = false; }
  63482. if (forcedExtension === void 0) { forcedExtension = null; }
  63483. if (createPolynomials === void 0) { createPolynomials = false; }
  63484. var _this = _super.call(this, scene) || this;
  63485. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63486. /**
  63487. * Gets or sets the center of the bounding box associated with the cube texture
  63488. * It must define where the camera used to render the texture was set
  63489. */
  63490. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63491. _this._rotationY = 0;
  63492. _this.name = rootUrl;
  63493. _this.url = rootUrl;
  63494. _this._noMipmap = noMipmap;
  63495. _this.hasAlpha = false;
  63496. _this._format = format;
  63497. _this._prefiltered = prefiltered;
  63498. _this.isCube = true;
  63499. _this._textureMatrix = BABYLON.Matrix.Identity();
  63500. _this._createPolynomials = createPolynomials;
  63501. if (prefiltered) {
  63502. _this.gammaSpace = false;
  63503. }
  63504. if (!rootUrl && !files) {
  63505. return _this;
  63506. }
  63507. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63508. var lastDot = rootUrl.lastIndexOf(".");
  63509. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63510. var isDDS = (extension === ".dds");
  63511. if (!files) {
  63512. if (!isDDS && !extensions) {
  63513. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63514. }
  63515. files = [];
  63516. if (extensions) {
  63517. for (var index = 0; index < extensions.length; index++) {
  63518. files.push(rootUrl + extensions[index]);
  63519. }
  63520. }
  63521. }
  63522. _this._files = files;
  63523. if (!_this._texture) {
  63524. if (!scene.useDelayedTextureLoading) {
  63525. if (prefiltered) {
  63526. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63527. }
  63528. else {
  63529. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63530. }
  63531. }
  63532. else {
  63533. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63534. }
  63535. }
  63536. else if (onLoad) {
  63537. if (_this._texture.isReady) {
  63538. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63539. }
  63540. else {
  63541. _this._texture.onLoadedObservable.add(onLoad);
  63542. }
  63543. }
  63544. return _this;
  63545. }
  63546. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63547. get: function () {
  63548. return this._boundingBoxSize;
  63549. },
  63550. /**
  63551. * Gets or sets the size of the bounding box associated with the cube texture
  63552. * When defined, the cubemap will switch to local mode
  63553. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63554. * @example https://www.babylonjs-playground.com/#RNASML
  63555. */
  63556. set: function (value) {
  63557. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63558. return;
  63559. }
  63560. this._boundingBoxSize = value;
  63561. var scene = this.getScene();
  63562. if (scene) {
  63563. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63564. }
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63570. /**
  63571. * Gets texture matrix rotation angle around Y axis radians.
  63572. */
  63573. get: function () {
  63574. return this._rotationY;
  63575. },
  63576. /**
  63577. * Sets texture matrix rotation angle around Y axis in radians.
  63578. */
  63579. set: function (value) {
  63580. this._rotationY = value;
  63581. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63582. },
  63583. enumerable: true,
  63584. configurable: true
  63585. });
  63586. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63587. var rootUrlKey = "";
  63588. files.forEach(function (url) { return rootUrlKey += url; });
  63589. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63590. };
  63591. /**
  63592. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63593. * @param url defines the url of the prefiltered texture
  63594. * @param scene defines the scene the texture is attached to
  63595. * @param forcedExtension defines the extension of the file if different from the url
  63596. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63597. * @return the prefiltered texture
  63598. */
  63599. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63600. if (forcedExtension === void 0) { forcedExtension = null; }
  63601. if (createPolynomials === void 0) { createPolynomials = true; }
  63602. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63603. };
  63604. // Methods
  63605. CubeTexture.prototype.delayLoad = function () {
  63606. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63607. return;
  63608. }
  63609. var scene = this.getScene();
  63610. if (!scene) {
  63611. return;
  63612. }
  63613. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63614. this._texture = this._getFromCache(this.url, this._noMipmap);
  63615. if (!this._texture) {
  63616. if (this._prefiltered) {
  63617. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63618. }
  63619. else {
  63620. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63621. }
  63622. }
  63623. };
  63624. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63625. return this._textureMatrix;
  63626. };
  63627. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63628. this._textureMatrix = value;
  63629. };
  63630. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63631. var texture = BABYLON.SerializationHelper.Parse(function () {
  63632. var prefiltered = false;
  63633. if (parsedTexture.prefiltered) {
  63634. prefiltered = parsedTexture.prefiltered;
  63635. }
  63636. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63637. }, parsedTexture, scene);
  63638. // Local Cubemaps
  63639. if (parsedTexture.boundingBoxPosition) {
  63640. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63641. }
  63642. if (parsedTexture.boundingBoxSize) {
  63643. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63644. }
  63645. // Animations
  63646. if (parsedTexture.animations) {
  63647. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63648. var parsedAnimation = parsedTexture.animations[animationIndex];
  63649. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63650. }
  63651. }
  63652. return texture;
  63653. };
  63654. CubeTexture.prototype.clone = function () {
  63655. var _this = this;
  63656. return BABYLON.SerializationHelper.Clone(function () {
  63657. var scene = _this.getScene();
  63658. if (!scene) {
  63659. return _this;
  63660. }
  63661. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63662. }, this);
  63663. };
  63664. __decorate([
  63665. BABYLON.serialize("rotationY")
  63666. ], CubeTexture.prototype, "_rotationY", void 0);
  63667. return CubeTexture;
  63668. }(BABYLON.BaseTexture));
  63669. BABYLON.CubeTexture = CubeTexture;
  63670. })(BABYLON || (BABYLON = {}));
  63671. //# sourceMappingURL=babylon.cubeTexture.js.map
  63672. var BABYLON;
  63673. (function (BABYLON) {
  63674. var RenderTargetTexture = /** @class */ (function (_super) {
  63675. __extends(RenderTargetTexture, _super);
  63676. /**
  63677. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63678. * or used a shadow, depth texture...
  63679. * @param name The friendly name of the texture
  63680. * @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)
  63681. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63682. * @param generateMipMaps True if mip maps need to be generated after render.
  63683. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63684. * @param type The type of the buffer in the RTT (int, half float, float...)
  63685. * @param isCube True if a cube texture needs to be created
  63686. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63687. * @param generateDepthBuffer True to generate a depth buffer
  63688. * @param generateStencilBuffer True to generate a stencil buffer
  63689. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63690. */
  63691. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63692. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63693. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63694. if (isCube === void 0) { isCube = false; }
  63695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63696. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63697. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63698. if (isMulti === void 0) { isMulti = false; }
  63699. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63700. _this.isCube = isCube;
  63701. /**
  63702. * Use this list to define the list of mesh you want to render.
  63703. */
  63704. _this.renderList = new Array();
  63705. _this.renderParticles = true;
  63706. _this.renderSprites = false;
  63707. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63708. _this.ignoreCameraViewport = false;
  63709. // Events
  63710. /**
  63711. * An event triggered when the texture is unbind.
  63712. */
  63713. _this.onBeforeBindObservable = new BABYLON.Observable();
  63714. /**
  63715. * An event triggered when the texture is unbind.
  63716. */
  63717. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63718. /**
  63719. * An event triggered before rendering the texture
  63720. */
  63721. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63722. /**
  63723. * An event triggered after rendering the texture
  63724. */
  63725. _this.onAfterRenderObservable = new BABYLON.Observable();
  63726. /**
  63727. * An event triggered after the texture clear
  63728. */
  63729. _this.onClearObservable = new BABYLON.Observable();
  63730. _this._currentRefreshId = -1;
  63731. _this._refreshRate = 1;
  63732. _this._samples = 1;
  63733. /**
  63734. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63735. * It must define where the camera used to render the texture is set
  63736. */
  63737. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63738. scene = _this.getScene();
  63739. if (!scene) {
  63740. return _this;
  63741. }
  63742. _this._engine = scene.getEngine();
  63743. _this.name = name;
  63744. _this.isRenderTarget = true;
  63745. _this._initialSizeParameter = size;
  63746. _this._processSizeParameter(size);
  63747. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63748. });
  63749. _this._generateMipMaps = generateMipMaps ? true : false;
  63750. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63751. // Rendering groups
  63752. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63753. if (isMulti) {
  63754. return _this;
  63755. }
  63756. _this._renderTargetOptions = {
  63757. generateMipMaps: generateMipMaps,
  63758. type: type,
  63759. samplingMode: samplingMode,
  63760. generateDepthBuffer: generateDepthBuffer,
  63761. generateStencilBuffer: generateStencilBuffer
  63762. };
  63763. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63764. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63765. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63766. }
  63767. if (isCube) {
  63768. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63769. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63770. _this._textureMatrix = BABYLON.Matrix.Identity();
  63771. }
  63772. else {
  63773. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63774. }
  63775. return _this;
  63776. }
  63777. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63778. get: function () {
  63779. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63780. },
  63781. enumerable: true,
  63782. configurable: true
  63783. });
  63784. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63785. get: function () {
  63786. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63787. },
  63788. enumerable: true,
  63789. configurable: true
  63790. });
  63791. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63792. get: function () {
  63793. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63794. },
  63795. enumerable: true,
  63796. configurable: true
  63797. });
  63798. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63799. set: function (callback) {
  63800. if (this._onAfterUnbindObserver) {
  63801. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63802. }
  63803. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63804. },
  63805. enumerable: true,
  63806. configurable: true
  63807. });
  63808. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63809. set: function (callback) {
  63810. if (this._onBeforeRenderObserver) {
  63811. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63812. }
  63813. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63814. },
  63815. enumerable: true,
  63816. configurable: true
  63817. });
  63818. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63819. set: function (callback) {
  63820. if (this._onAfterRenderObserver) {
  63821. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63822. }
  63823. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63824. },
  63825. enumerable: true,
  63826. configurable: true
  63827. });
  63828. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63829. set: function (callback) {
  63830. if (this._onClearObserver) {
  63831. this.onClearObservable.remove(this._onClearObserver);
  63832. }
  63833. this._onClearObserver = this.onClearObservable.add(callback);
  63834. },
  63835. enumerable: true,
  63836. configurable: true
  63837. });
  63838. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63839. get: function () {
  63840. return this._renderTargetOptions;
  63841. },
  63842. enumerable: true,
  63843. configurable: true
  63844. });
  63845. RenderTargetTexture.prototype._onRatioRescale = function () {
  63846. if (this._sizeRatio) {
  63847. this.resize(this._initialSizeParameter);
  63848. }
  63849. };
  63850. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63851. get: function () {
  63852. return this._boundingBoxSize;
  63853. },
  63854. /**
  63855. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63856. * When defined, the cubemap will switch to local mode
  63857. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63858. * @example https://www.babylonjs-playground.com/#RNASML
  63859. */
  63860. set: function (value) {
  63861. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63862. return;
  63863. }
  63864. this._boundingBoxSize = value;
  63865. var scene = this.getScene();
  63866. if (scene) {
  63867. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63868. }
  63869. },
  63870. enumerable: true,
  63871. configurable: true
  63872. });
  63873. /**
  63874. * Creates a depth stencil texture.
  63875. * This is only available in WebGL 2 or with the depth texture extension available.
  63876. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63877. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63878. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63879. */
  63880. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63881. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63882. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63883. if (generateStencil === void 0) { generateStencil = false; }
  63884. if (!this.getScene()) {
  63885. return;
  63886. }
  63887. var engine = this.getScene().getEngine();
  63888. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63889. bilinearFiltering: bilinearFiltering,
  63890. comparisonFunction: comparisonFunction,
  63891. generateStencil: generateStencil,
  63892. isCube: this.isCube
  63893. });
  63894. engine.setFrameBufferDepthStencilTexture(this);
  63895. };
  63896. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63897. if (size.ratio) {
  63898. this._sizeRatio = size.ratio;
  63899. this._size = {
  63900. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63901. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63902. };
  63903. }
  63904. else {
  63905. this._size = size;
  63906. }
  63907. };
  63908. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63909. get: function () {
  63910. return this._samples;
  63911. },
  63912. set: function (value) {
  63913. if (this._samples === value) {
  63914. return;
  63915. }
  63916. var scene = this.getScene();
  63917. if (!scene) {
  63918. return;
  63919. }
  63920. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63921. },
  63922. enumerable: true,
  63923. configurable: true
  63924. });
  63925. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63926. this._currentRefreshId = -1;
  63927. };
  63928. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63929. get: function () {
  63930. return this._refreshRate;
  63931. },
  63932. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63933. set: function (value) {
  63934. this._refreshRate = value;
  63935. this.resetRefreshCounter();
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63941. if (!this._postProcessManager) {
  63942. var scene = this.getScene();
  63943. if (!scene) {
  63944. return;
  63945. }
  63946. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63947. this._postProcesses = new Array();
  63948. }
  63949. this._postProcesses.push(postProcess);
  63950. this._postProcesses[0].autoClear = false;
  63951. };
  63952. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63953. if (!this._postProcesses) {
  63954. return;
  63955. }
  63956. if (dispose) {
  63957. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63958. var postProcess = _a[_i];
  63959. postProcess.dispose();
  63960. }
  63961. }
  63962. this._postProcesses = [];
  63963. };
  63964. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63965. if (!this._postProcesses) {
  63966. return;
  63967. }
  63968. var index = this._postProcesses.indexOf(postProcess);
  63969. if (index === -1) {
  63970. return;
  63971. }
  63972. this._postProcesses.splice(index, 1);
  63973. if (this._postProcesses.length > 0) {
  63974. this._postProcesses[0].autoClear = false;
  63975. }
  63976. };
  63977. RenderTargetTexture.prototype._shouldRender = function () {
  63978. if (this._currentRefreshId === -1) { // At least render once
  63979. this._currentRefreshId = 1;
  63980. return true;
  63981. }
  63982. if (this.refreshRate === this._currentRefreshId) {
  63983. this._currentRefreshId = 1;
  63984. return true;
  63985. }
  63986. this._currentRefreshId++;
  63987. return false;
  63988. };
  63989. RenderTargetTexture.prototype.getRenderSize = function () {
  63990. if (this._size.width) {
  63991. return this._size.width;
  63992. }
  63993. return this._size;
  63994. };
  63995. RenderTargetTexture.prototype.getRenderWidth = function () {
  63996. if (this._size.width) {
  63997. return this._size.width;
  63998. }
  63999. return this._size;
  64000. };
  64001. RenderTargetTexture.prototype.getRenderHeight = function () {
  64002. if (this._size.width) {
  64003. return this._size.height;
  64004. }
  64005. return this._size;
  64006. };
  64007. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64008. get: function () {
  64009. return true;
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. RenderTargetTexture.prototype.scale = function (ratio) {
  64015. var newSize = this.getRenderSize() * ratio;
  64016. this.resize(newSize);
  64017. };
  64018. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64019. if (this.isCube) {
  64020. return this._textureMatrix;
  64021. }
  64022. return _super.prototype.getReflectionTextureMatrix.call(this);
  64023. };
  64024. RenderTargetTexture.prototype.resize = function (size) {
  64025. this.releaseInternalTexture();
  64026. var scene = this.getScene();
  64027. if (!scene) {
  64028. return;
  64029. }
  64030. this._processSizeParameter(size);
  64031. if (this.isCube) {
  64032. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64033. }
  64034. else {
  64035. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64036. }
  64037. };
  64038. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64039. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64040. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64041. var scene = this.getScene();
  64042. if (!scene) {
  64043. return;
  64044. }
  64045. var engine = scene.getEngine();
  64046. if (this.useCameraPostProcesses !== undefined) {
  64047. useCameraPostProcess = this.useCameraPostProcesses;
  64048. }
  64049. if (this._waitingRenderList) {
  64050. this.renderList = [];
  64051. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64052. var id = this._waitingRenderList[index];
  64053. var mesh_1 = scene.getMeshByID(id);
  64054. if (mesh_1) {
  64055. this.renderList.push(mesh_1);
  64056. }
  64057. }
  64058. delete this._waitingRenderList;
  64059. }
  64060. // Is predicate defined?
  64061. if (this.renderListPredicate) {
  64062. if (this.renderList) {
  64063. this.renderList.splice(0); // Clear previous renderList
  64064. }
  64065. else {
  64066. this.renderList = [];
  64067. }
  64068. var scene = this.getScene();
  64069. if (!scene) {
  64070. return;
  64071. }
  64072. var sceneMeshes = scene.meshes;
  64073. for (var index = 0; index < sceneMeshes.length; index++) {
  64074. var mesh = sceneMeshes[index];
  64075. if (this.renderListPredicate(mesh)) {
  64076. this.renderList.push(mesh);
  64077. }
  64078. }
  64079. }
  64080. this.onBeforeBindObservable.notifyObservers(this);
  64081. // Set custom projection.
  64082. // Needs to be before binding to prevent changing the aspect ratio.
  64083. var camera;
  64084. if (this.activeCamera) {
  64085. camera = this.activeCamera;
  64086. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64087. if (this.activeCamera !== scene.activeCamera) {
  64088. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64089. }
  64090. }
  64091. else {
  64092. camera = scene.activeCamera;
  64093. if (camera) {
  64094. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64095. }
  64096. }
  64097. // Prepare renderingManager
  64098. this._renderingManager.reset();
  64099. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64100. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64101. var sceneRenderId = scene.getRenderId();
  64102. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64103. var mesh = currentRenderList[meshIndex];
  64104. if (mesh) {
  64105. if (!mesh.isReady(this.refreshRate === 0)) {
  64106. this.resetRefreshCounter();
  64107. continue;
  64108. }
  64109. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64110. var isMasked = void 0;
  64111. if (!this.renderList && camera) {
  64112. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64113. }
  64114. else {
  64115. isMasked = false;
  64116. }
  64117. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64118. mesh._activate(sceneRenderId);
  64119. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64120. var subMesh = mesh.subMeshes[subIndex];
  64121. scene._activeIndices.addCount(subMesh.indexCount, false);
  64122. this._renderingManager.dispatch(subMesh, mesh);
  64123. }
  64124. }
  64125. }
  64126. }
  64127. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64128. var particleSystem = scene.particleSystems[particleIndex];
  64129. var emitter = particleSystem.emitter;
  64130. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64131. continue;
  64132. }
  64133. if (currentRenderList.indexOf(emitter) >= 0) {
  64134. this._renderingManager.dispatchParticles(particleSystem);
  64135. }
  64136. }
  64137. if (this.isCube) {
  64138. for (var face = 0; face < 6; face++) {
  64139. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64140. scene.incrementRenderId();
  64141. scene.resetCachedMaterial();
  64142. }
  64143. }
  64144. else {
  64145. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64146. }
  64147. this.onAfterUnbindObservable.notifyObservers(this);
  64148. if (scene.activeCamera) {
  64149. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64150. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64151. }
  64152. engine.setViewport(scene.activeCamera.viewport);
  64153. }
  64154. scene.resetCachedMaterial();
  64155. };
  64156. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64157. var minimum = 128;
  64158. var x = renderDimension * scale;
  64159. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64160. // Ensure we don't exceed the render dimension (while staying POT)
  64161. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64162. };
  64163. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64164. var _this = this;
  64165. if (!this._texture) {
  64166. return;
  64167. }
  64168. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64169. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64170. });
  64171. };
  64172. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64173. var scene = this.getScene();
  64174. if (!scene) {
  64175. return;
  64176. }
  64177. var engine = scene.getEngine();
  64178. if (!this._texture) {
  64179. return;
  64180. }
  64181. // Bind
  64182. if (this._postProcessManager) {
  64183. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64184. }
  64185. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64186. if (this._texture) {
  64187. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64188. }
  64189. }
  64190. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64191. // Clear
  64192. if (this.onClearObservable.hasObservers()) {
  64193. this.onClearObservable.notifyObservers(engine);
  64194. }
  64195. else {
  64196. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64197. }
  64198. if (!this._doNotChangeAspectRatio) {
  64199. scene.updateTransformMatrix(true);
  64200. }
  64201. // Render
  64202. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64203. if (this._postProcessManager) {
  64204. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64205. }
  64206. else if (useCameraPostProcess) {
  64207. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64208. }
  64209. if (!this._doNotChangeAspectRatio) {
  64210. scene.updateTransformMatrix(true);
  64211. }
  64212. // Dump ?
  64213. if (dumpForDebug) {
  64214. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64215. }
  64216. // Unbind
  64217. if (!this.isCube || faceIndex === 5) {
  64218. if (this.isCube) {
  64219. if (faceIndex === 5) {
  64220. engine.generateMipMapsForCubemap(this._texture);
  64221. }
  64222. }
  64223. this.unbindFrameBuffer(engine, faceIndex);
  64224. }
  64225. else {
  64226. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64227. }
  64228. };
  64229. /**
  64230. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64231. * This allowed control for front to back rendering or reversly depending of the special needs.
  64232. *
  64233. * @param renderingGroupId The rendering group id corresponding to its index
  64234. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64235. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64236. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64237. */
  64238. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64239. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64240. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64241. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64242. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64243. };
  64244. /**
  64245. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64246. *
  64247. * @param renderingGroupId The rendering group id corresponding to its index
  64248. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64249. */
  64250. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64251. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64252. };
  64253. RenderTargetTexture.prototype.clone = function () {
  64254. var textureSize = this.getSize();
  64255. 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);
  64256. // Base texture
  64257. newTexture.hasAlpha = this.hasAlpha;
  64258. newTexture.level = this.level;
  64259. // RenderTarget Texture
  64260. newTexture.coordinatesMode = this.coordinatesMode;
  64261. if (this.renderList) {
  64262. newTexture.renderList = this.renderList.slice(0);
  64263. }
  64264. return newTexture;
  64265. };
  64266. RenderTargetTexture.prototype.serialize = function () {
  64267. if (!this.name) {
  64268. return null;
  64269. }
  64270. var serializationObject = _super.prototype.serialize.call(this);
  64271. serializationObject.renderTargetSize = this.getRenderSize();
  64272. serializationObject.renderList = [];
  64273. if (this.renderList) {
  64274. for (var index = 0; index < this.renderList.length; index++) {
  64275. serializationObject.renderList.push(this.renderList[index].id);
  64276. }
  64277. }
  64278. return serializationObject;
  64279. };
  64280. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64281. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64282. var objBuffer = this.getInternalTexture();
  64283. var scene = this.getScene();
  64284. if (objBuffer && scene) {
  64285. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64286. }
  64287. };
  64288. RenderTargetTexture.prototype.dispose = function () {
  64289. if (this._postProcessManager) {
  64290. this._postProcessManager.dispose();
  64291. this._postProcessManager = null;
  64292. }
  64293. this.clearPostProcesses(true);
  64294. if (this._resizeObserver) {
  64295. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64296. this._resizeObserver = null;
  64297. }
  64298. this.renderList = null;
  64299. // Remove from custom render targets
  64300. var scene = this.getScene();
  64301. if (!scene) {
  64302. return;
  64303. }
  64304. var index = scene.customRenderTargets.indexOf(this);
  64305. if (index >= 0) {
  64306. scene.customRenderTargets.splice(index, 1);
  64307. }
  64308. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64309. var camera = _a[_i];
  64310. index = camera.customRenderTargets.indexOf(this);
  64311. if (index >= 0) {
  64312. camera.customRenderTargets.splice(index, 1);
  64313. }
  64314. }
  64315. _super.prototype.dispose.call(this);
  64316. };
  64317. RenderTargetTexture.prototype._rebuild = function () {
  64318. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64319. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64320. }
  64321. if (this._postProcessManager) {
  64322. this._postProcessManager._rebuild();
  64323. }
  64324. };
  64325. /**
  64326. * Clear the info related to rendering groups preventing retention point in material dispose.
  64327. */
  64328. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64329. if (this._renderingManager) {
  64330. this._renderingManager.freeRenderingGroups();
  64331. }
  64332. };
  64333. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64334. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64335. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64336. return RenderTargetTexture;
  64337. }(BABYLON.Texture));
  64338. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64339. })(BABYLON || (BABYLON = {}));
  64340. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64341. var BABYLON;
  64342. (function (BABYLON) {
  64343. ;
  64344. var MultiRenderTarget = /** @class */ (function (_super) {
  64345. __extends(MultiRenderTarget, _super);
  64346. function MultiRenderTarget(name, size, count, scene, options) {
  64347. var _this = this;
  64348. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64349. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64350. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64351. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64352. _this._engine = scene.getEngine();
  64353. if (!_this.isSupported) {
  64354. _this.dispose();
  64355. return;
  64356. }
  64357. var types = [];
  64358. var samplingModes = [];
  64359. for (var i = 0; i < count; i++) {
  64360. if (options && options.types && options.types[i] !== undefined) {
  64361. types.push(options.types[i]);
  64362. }
  64363. else {
  64364. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64365. }
  64366. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64367. samplingModes.push(options.samplingModes[i]);
  64368. }
  64369. else {
  64370. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64371. }
  64372. }
  64373. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64374. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64375. _this._size = size;
  64376. _this._multiRenderTargetOptions = {
  64377. samplingModes: samplingModes,
  64378. generateMipMaps: generateMipMaps,
  64379. generateDepthBuffer: generateDepthBuffer,
  64380. generateStencilBuffer: generateStencilBuffer,
  64381. generateDepthTexture: generateDepthTexture,
  64382. types: types,
  64383. textureCount: count
  64384. };
  64385. _this._createInternalTextures();
  64386. _this._createTextures();
  64387. return _this;
  64388. }
  64389. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64390. get: function () {
  64391. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64392. },
  64393. enumerable: true,
  64394. configurable: true
  64395. });
  64396. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64397. get: function () {
  64398. return this._textures;
  64399. },
  64400. enumerable: true,
  64401. configurable: true
  64402. });
  64403. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64404. get: function () {
  64405. return this._textures[this._textures.length - 1];
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64411. set: function (wrap) {
  64412. if (this._textures) {
  64413. for (var i = 0; i < this._textures.length; i++) {
  64414. this._textures[i].wrapU = wrap;
  64415. }
  64416. }
  64417. },
  64418. enumerable: true,
  64419. configurable: true
  64420. });
  64421. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64422. set: function (wrap) {
  64423. if (this._textures) {
  64424. for (var i = 0; i < this._textures.length; i++) {
  64425. this._textures[i].wrapV = wrap;
  64426. }
  64427. }
  64428. },
  64429. enumerable: true,
  64430. configurable: true
  64431. });
  64432. MultiRenderTarget.prototype._rebuild = function () {
  64433. this.releaseInternalTextures();
  64434. this._createInternalTextures();
  64435. for (var i = 0; i < this._internalTextures.length; i++) {
  64436. var texture = this._textures[i];
  64437. texture._texture = this._internalTextures[i];
  64438. }
  64439. // Keeps references to frame buffer and stencil/depth buffer
  64440. this._texture = this._internalTextures[0];
  64441. };
  64442. MultiRenderTarget.prototype._createInternalTextures = function () {
  64443. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64444. };
  64445. MultiRenderTarget.prototype._createTextures = function () {
  64446. this._textures = [];
  64447. for (var i = 0; i < this._internalTextures.length; i++) {
  64448. var texture = new BABYLON.Texture(null, this.getScene());
  64449. texture._texture = this._internalTextures[i];
  64450. this._textures.push(texture);
  64451. }
  64452. // Keeps references to frame buffer and stencil/depth buffer
  64453. this._texture = this._internalTextures[0];
  64454. };
  64455. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64456. get: function () {
  64457. return this._samples;
  64458. },
  64459. set: function (value) {
  64460. if (this._samples === value) {
  64461. return;
  64462. }
  64463. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64464. },
  64465. enumerable: true,
  64466. configurable: true
  64467. });
  64468. MultiRenderTarget.prototype.resize = function (size) {
  64469. this.releaseInternalTextures();
  64470. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64471. this._createInternalTextures();
  64472. };
  64473. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64474. var _this = this;
  64475. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64476. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64477. });
  64478. };
  64479. MultiRenderTarget.prototype.dispose = function () {
  64480. this.releaseInternalTextures();
  64481. _super.prototype.dispose.call(this);
  64482. };
  64483. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64484. if (!this._internalTextures) {
  64485. return;
  64486. }
  64487. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64488. if (this._internalTextures[i] !== undefined) {
  64489. this._internalTextures[i].dispose();
  64490. this._internalTextures.splice(i, 1);
  64491. }
  64492. }
  64493. };
  64494. return MultiRenderTarget;
  64495. }(BABYLON.RenderTargetTexture));
  64496. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64497. })(BABYLON || (BABYLON = {}));
  64498. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64499. var BABYLON;
  64500. (function (BABYLON) {
  64501. var MirrorTexture = /** @class */ (function (_super) {
  64502. __extends(MirrorTexture, _super);
  64503. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64506. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64507. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64508. _this.scene = scene;
  64509. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64510. _this._transformMatrix = BABYLON.Matrix.Zero();
  64511. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64512. _this._adaptiveBlurKernel = 0;
  64513. _this._blurKernelX = 0;
  64514. _this._blurKernelY = 0;
  64515. _this._blurRatio = 1.0;
  64516. _this.ignoreCameraViewport = true;
  64517. _this._updateGammaSpace();
  64518. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64519. _this._updateGammaSpace;
  64520. });
  64521. _this.onBeforeRenderObservable.add(function () {
  64522. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64523. _this._savedViewMatrix = scene.getViewMatrix();
  64524. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64525. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64526. scene.clipPlane = _this.mirrorPlane;
  64527. scene.getEngine().cullBackFaces = false;
  64528. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64529. });
  64530. _this.onAfterRenderObservable.add(function () {
  64531. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64532. scene.getEngine().cullBackFaces = true;
  64533. scene._mirroredCameraPosition = null;
  64534. delete scene.clipPlane;
  64535. });
  64536. return _this;
  64537. }
  64538. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64539. get: function () {
  64540. return this._blurRatio;
  64541. },
  64542. set: function (value) {
  64543. if (this._blurRatio === value) {
  64544. return;
  64545. }
  64546. this._blurRatio = value;
  64547. this._preparePostProcesses();
  64548. },
  64549. enumerable: true,
  64550. configurable: true
  64551. });
  64552. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64553. set: function (value) {
  64554. this._adaptiveBlurKernel = value;
  64555. this._autoComputeBlurKernel();
  64556. },
  64557. enumerable: true,
  64558. configurable: true
  64559. });
  64560. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64561. set: function (value) {
  64562. this.blurKernelX = value;
  64563. this.blurKernelY = value;
  64564. },
  64565. enumerable: true,
  64566. configurable: true
  64567. });
  64568. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64569. get: function () {
  64570. return this._blurKernelX;
  64571. },
  64572. set: function (value) {
  64573. if (this._blurKernelX === value) {
  64574. return;
  64575. }
  64576. this._blurKernelX = value;
  64577. this._preparePostProcesses();
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64583. get: function () {
  64584. return this._blurKernelY;
  64585. },
  64586. set: function (value) {
  64587. if (this._blurKernelY === value) {
  64588. return;
  64589. }
  64590. this._blurKernelY = value;
  64591. this._preparePostProcesses();
  64592. },
  64593. enumerable: true,
  64594. configurable: true
  64595. });
  64596. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64597. var engine = this.getScene().getEngine();
  64598. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64599. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64600. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64601. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64602. };
  64603. MirrorTexture.prototype._onRatioRescale = function () {
  64604. if (this._sizeRatio) {
  64605. this.resize(this._initialSizeParameter);
  64606. if (!this._adaptiveBlurKernel) {
  64607. this._preparePostProcesses();
  64608. }
  64609. }
  64610. if (this._adaptiveBlurKernel) {
  64611. this._autoComputeBlurKernel();
  64612. }
  64613. };
  64614. MirrorTexture.prototype._updateGammaSpace = function () {
  64615. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64616. };
  64617. MirrorTexture.prototype._preparePostProcesses = function () {
  64618. this.clearPostProcesses(true);
  64619. if (this._blurKernelX && this._blurKernelY) {
  64620. var engine = this.getScene().getEngine();
  64621. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64622. 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);
  64623. this._blurX.autoClear = false;
  64624. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64625. this._blurX.inputTexture = this._texture;
  64626. }
  64627. else {
  64628. this._blurX.alwaysForcePOT = true;
  64629. }
  64630. 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);
  64631. this._blurY.autoClear = false;
  64632. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64633. this.addPostProcess(this._blurX);
  64634. this.addPostProcess(this._blurY);
  64635. }
  64636. else {
  64637. if (this._blurY) {
  64638. this.removePostProcess(this._blurY);
  64639. this._blurY.dispose();
  64640. this._blurY = null;
  64641. }
  64642. if (this._blurX) {
  64643. this.removePostProcess(this._blurX);
  64644. this._blurX.dispose();
  64645. this._blurX = null;
  64646. }
  64647. }
  64648. };
  64649. MirrorTexture.prototype.clone = function () {
  64650. var scene = this.getScene();
  64651. if (!scene) {
  64652. return this;
  64653. }
  64654. var textureSize = this.getSize();
  64655. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64656. // Base texture
  64657. newTexture.hasAlpha = this.hasAlpha;
  64658. newTexture.level = this.level;
  64659. // Mirror Texture
  64660. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64661. if (this.renderList) {
  64662. newTexture.renderList = this.renderList.slice(0);
  64663. }
  64664. return newTexture;
  64665. };
  64666. MirrorTexture.prototype.serialize = function () {
  64667. if (!this.name) {
  64668. return null;
  64669. }
  64670. var serializationObject = _super.prototype.serialize.call(this);
  64671. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64672. return serializationObject;
  64673. };
  64674. MirrorTexture.prototype.dispose = function () {
  64675. _super.prototype.dispose.call(this);
  64676. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64677. };
  64678. return MirrorTexture;
  64679. }(BABYLON.RenderTargetTexture));
  64680. BABYLON.MirrorTexture = MirrorTexture;
  64681. })(BABYLON || (BABYLON = {}));
  64682. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64683. var BABYLON;
  64684. (function (BABYLON) {
  64685. /**
  64686. * Creates a refraction texture used by refraction channel of the standard material.
  64687. * @param name the texture name
  64688. * @param size size of the underlying texture
  64689. * @param scene root scene
  64690. */
  64691. var RefractionTexture = /** @class */ (function (_super) {
  64692. __extends(RefractionTexture, _super);
  64693. function RefractionTexture(name, size, scene, generateMipMaps) {
  64694. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64695. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64696. _this.depth = 2.0;
  64697. _this.onBeforeRenderObservable.add(function () {
  64698. scene.clipPlane = _this.refractionPlane;
  64699. });
  64700. _this.onAfterRenderObservable.add(function () {
  64701. delete scene.clipPlane;
  64702. });
  64703. return _this;
  64704. }
  64705. RefractionTexture.prototype.clone = function () {
  64706. var scene = this.getScene();
  64707. if (!scene) {
  64708. return this;
  64709. }
  64710. var textureSize = this.getSize();
  64711. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64712. // Base texture
  64713. newTexture.hasAlpha = this.hasAlpha;
  64714. newTexture.level = this.level;
  64715. // Refraction Texture
  64716. newTexture.refractionPlane = this.refractionPlane.clone();
  64717. if (this.renderList) {
  64718. newTexture.renderList = this.renderList.slice(0);
  64719. }
  64720. newTexture.depth = this.depth;
  64721. return newTexture;
  64722. };
  64723. RefractionTexture.prototype.serialize = function () {
  64724. if (!this.name) {
  64725. return null;
  64726. }
  64727. var serializationObject = _super.prototype.serialize.call(this);
  64728. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64729. serializationObject.depth = this.depth;
  64730. return serializationObject;
  64731. };
  64732. return RefractionTexture;
  64733. }(BABYLON.RenderTargetTexture));
  64734. BABYLON.RefractionTexture = RefractionTexture;
  64735. })(BABYLON || (BABYLON = {}));
  64736. //# sourceMappingURL=babylon.refractionTexture.js.map
  64737. var BABYLON;
  64738. (function (BABYLON) {
  64739. /**
  64740. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64741. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64742. */
  64743. var DynamicTexture = /** @class */ (function (_super) {
  64744. __extends(DynamicTexture, _super);
  64745. /**
  64746. * Creates a {BABYLON.DynamicTexture}
  64747. * @param name defines the name of the texture
  64748. * @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
  64749. * @param scene defines the scene where you want the texture
  64750. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64751. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64752. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64753. */
  64754. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64755. if (scene === void 0) { scene = null; }
  64756. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64757. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64758. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64759. _this.name = name;
  64760. _this._engine = _this.getScene().getEngine();
  64761. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64762. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64763. _this._generateMipMaps = generateMipMaps;
  64764. if (options.getContext) {
  64765. _this._canvas = options;
  64766. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64767. }
  64768. else {
  64769. _this._canvas = document.createElement("canvas");
  64770. if (options.width || options.width === 0) {
  64771. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64772. }
  64773. else {
  64774. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64775. }
  64776. }
  64777. var textureSize = _this.getSize();
  64778. _this._canvas.width = textureSize.width;
  64779. _this._canvas.height = textureSize.height;
  64780. _this._context = _this._canvas.getContext("2d");
  64781. return _this;
  64782. }
  64783. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64784. /**
  64785. * Gets the current state of canRescale
  64786. */
  64787. get: function () {
  64788. return true;
  64789. },
  64790. enumerable: true,
  64791. configurable: true
  64792. });
  64793. DynamicTexture.prototype._recreate = function (textureSize) {
  64794. this._canvas.width = textureSize.width;
  64795. this._canvas.height = textureSize.height;
  64796. this.releaseInternalTexture();
  64797. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64798. };
  64799. /**
  64800. * Scales the texture
  64801. * @param ratio the scale factor to apply to both width and height
  64802. */
  64803. DynamicTexture.prototype.scale = function (ratio) {
  64804. var textureSize = this.getSize();
  64805. textureSize.width *= ratio;
  64806. textureSize.height *= ratio;
  64807. this._recreate(textureSize);
  64808. };
  64809. /**
  64810. * Resizes the texture
  64811. * @param width the new width
  64812. * @param height the new height
  64813. */
  64814. DynamicTexture.prototype.scaleTo = function (width, height) {
  64815. var textureSize = this.getSize();
  64816. textureSize.width = width;
  64817. textureSize.height = height;
  64818. this._recreate(textureSize);
  64819. };
  64820. /**
  64821. * Gets the context of the canvas used by the texture
  64822. * @returns the canvas context of the dynamic texture
  64823. */
  64824. DynamicTexture.prototype.getContext = function () {
  64825. return this._context;
  64826. };
  64827. /**
  64828. * Clears the texture
  64829. */
  64830. DynamicTexture.prototype.clear = function () {
  64831. var size = this.getSize();
  64832. this._context.fillRect(0, 0, size.width, size.height);
  64833. };
  64834. /**
  64835. * Updates the texture
  64836. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64837. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64838. */
  64839. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64840. if (premulAlpha === void 0) { premulAlpha = false; }
  64841. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64842. };
  64843. /**
  64844. * Draws text onto the texture
  64845. * @param text defines the text to be drawn
  64846. * @param x defines the placement of the text from the left
  64847. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64848. * @param font defines the font to be used with font-style, font-size, font-name
  64849. * @param color defines the color used for the text
  64850. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64851. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64852. * @param update defines whether texture is immediately update (default is true)
  64853. */
  64854. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64855. if (update === void 0) { update = true; }
  64856. var size = this.getSize();
  64857. if (clearColor) {
  64858. this._context.fillStyle = clearColor;
  64859. this._context.fillRect(0, 0, size.width, size.height);
  64860. }
  64861. this._context.font = font;
  64862. if (x === null || x === undefined) {
  64863. var textSize = this._context.measureText(text);
  64864. x = (size.width - textSize.width) / 2;
  64865. }
  64866. if (y === null || y === undefined) {
  64867. var fontSize = parseInt((font.replace(/\D/g, '')));
  64868. y = (size.height / 2) + (fontSize / 3.65);
  64869. }
  64870. this._context.fillStyle = color;
  64871. this._context.fillText(text, x, y);
  64872. if (update) {
  64873. this.update(invertY);
  64874. }
  64875. };
  64876. /**
  64877. * Clones the texture
  64878. * @returns the clone of the texture.
  64879. */
  64880. DynamicTexture.prototype.clone = function () {
  64881. var scene = this.getScene();
  64882. if (!scene) {
  64883. return this;
  64884. }
  64885. var textureSize = this.getSize();
  64886. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64887. // Base texture
  64888. newTexture.hasAlpha = this.hasAlpha;
  64889. newTexture.level = this.level;
  64890. // Dynamic Texture
  64891. newTexture.wrapU = this.wrapU;
  64892. newTexture.wrapV = this.wrapV;
  64893. return newTexture;
  64894. };
  64895. /** @hidden */
  64896. DynamicTexture.prototype._rebuild = function () {
  64897. this.update();
  64898. };
  64899. return DynamicTexture;
  64900. }(BABYLON.Texture));
  64901. BABYLON.DynamicTexture = DynamicTexture;
  64902. })(BABYLON || (BABYLON = {}));
  64903. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64904. var BABYLON;
  64905. (function (BABYLON) {
  64906. var VideoTexture = /** @class */ (function (_super) {
  64907. __extends(VideoTexture, _super);
  64908. /**
  64909. * Creates a video texture.
  64910. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64911. * @param {string | null} name optional name, will detect from video source, if not defined
  64912. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64913. * @param {BABYLON.Scene} scene is obviously the current scene.
  64914. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64915. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64916. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64917. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64918. */
  64919. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64920. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64921. if (invertY === void 0) { invertY = false; }
  64922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64923. if (settings === void 0) { settings = {
  64924. autoPlay: true,
  64925. loop: true,
  64926. autoUpdateTexture: true,
  64927. }; }
  64928. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64929. _this._stillImageCaptured = false;
  64930. _this._createInternalTexture = function () {
  64931. if (_this._texture != null) {
  64932. return;
  64933. }
  64934. if (!_this._engine.needPOTTextures ||
  64935. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64936. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64937. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64938. }
  64939. else {
  64940. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64941. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64942. _this._generateMipMaps = false;
  64943. }
  64944. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64945. if (!_this.video.autoplay) {
  64946. var oldHandler_1 = _this.video.onplaying;
  64947. _this.video.onplaying = function () {
  64948. _this.video.onplaying = oldHandler_1;
  64949. _this._texture.isReady = true;
  64950. _this._updateInternalTexture();
  64951. _this.video.pause();
  64952. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64953. _this.onLoadObservable.notifyObservers(_this);
  64954. }
  64955. };
  64956. _this.video.play();
  64957. }
  64958. else {
  64959. _this._texture.isReady = true;
  64960. _this._updateInternalTexture();
  64961. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64962. _this.onLoadObservable.notifyObservers(_this);
  64963. }
  64964. }
  64965. };
  64966. _this.reset = function () {
  64967. if (_this._texture == null) {
  64968. return;
  64969. }
  64970. _this._texture.dispose();
  64971. _this._texture = null;
  64972. };
  64973. _this._updateInternalTexture = function (e) {
  64974. if (_this._texture == null || !_this._texture.isReady) {
  64975. return;
  64976. }
  64977. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64978. return;
  64979. }
  64980. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64981. };
  64982. _this._engine = _this.getScene().getEngine();
  64983. _this._generateMipMaps = generateMipMaps;
  64984. _this._samplingMode = samplingMode;
  64985. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64986. _this.name = name || _this._getName(src);
  64987. _this.video = _this._getVideo(src);
  64988. if (settings.autoPlay !== undefined) {
  64989. _this.video.autoplay = settings.autoPlay;
  64990. }
  64991. if (settings.loop !== undefined) {
  64992. _this.video.loop = settings.loop;
  64993. }
  64994. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64995. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64996. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64997. _this.video.addEventListener("emptied", _this.reset);
  64998. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64999. _this._createInternalTexture();
  65000. }
  65001. return _this;
  65002. }
  65003. VideoTexture.prototype._getName = function (src) {
  65004. if (src instanceof HTMLVideoElement) {
  65005. return src.currentSrc;
  65006. }
  65007. if (typeof src === "object") {
  65008. return src.toString();
  65009. }
  65010. return src;
  65011. };
  65012. ;
  65013. VideoTexture.prototype._getVideo = function (src) {
  65014. if (src instanceof HTMLVideoElement) {
  65015. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65016. return src;
  65017. }
  65018. var video = document.createElement("video");
  65019. if (typeof src === "string") {
  65020. BABYLON.Tools.SetCorsBehavior(src, video);
  65021. video.src = src;
  65022. }
  65023. else {
  65024. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65025. src.forEach(function (url) {
  65026. var source = document.createElement("source");
  65027. source.src = url;
  65028. video.appendChild(source);
  65029. });
  65030. }
  65031. return video;
  65032. };
  65033. ;
  65034. /**
  65035. * Internal method to initiate `update`.
  65036. */
  65037. VideoTexture.prototype._rebuild = function () {
  65038. this.update();
  65039. };
  65040. /**
  65041. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65042. */
  65043. VideoTexture.prototype.update = function () {
  65044. if (!this.autoUpdateTexture) {
  65045. // Expecting user to call `updateTexture` manually
  65046. return;
  65047. }
  65048. this.updateTexture(true);
  65049. };
  65050. /**
  65051. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65052. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65053. */
  65054. VideoTexture.prototype.updateTexture = function (isVisible) {
  65055. if (!isVisible) {
  65056. return;
  65057. }
  65058. if (this.video.paused && this._stillImageCaptured) {
  65059. return;
  65060. }
  65061. this._stillImageCaptured = true;
  65062. this._updateInternalTexture();
  65063. };
  65064. /**
  65065. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65066. * @param url New url.
  65067. */
  65068. VideoTexture.prototype.updateURL = function (url) {
  65069. this.video.src = url;
  65070. };
  65071. VideoTexture.prototype.dispose = function () {
  65072. _super.prototype.dispose.call(this);
  65073. this.video.removeEventListener("canplay", this._createInternalTexture);
  65074. this.video.removeEventListener("paused", this._updateInternalTexture);
  65075. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65076. this.video.removeEventListener("emptied", this.reset);
  65077. this.video.pause();
  65078. };
  65079. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65080. var video = document.createElement("video");
  65081. var constraintsDeviceId;
  65082. if (constraints && constraints.deviceId) {
  65083. constraintsDeviceId = {
  65084. exact: constraints.deviceId,
  65085. };
  65086. }
  65087. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65088. if (navigator.mediaDevices) {
  65089. navigator.mediaDevices.getUserMedia({ video: constraints })
  65090. .then(function (stream) {
  65091. if (video.mozSrcObject !== undefined) {
  65092. // hack for Firefox < 19
  65093. video.mozSrcObject = stream;
  65094. }
  65095. else {
  65096. video.srcObject = stream;
  65097. }
  65098. var onPlaying = function () {
  65099. if (onReady) {
  65100. onReady(new VideoTexture("video", video, scene, true, true));
  65101. }
  65102. video.removeEventListener("playing", onPlaying);
  65103. };
  65104. video.addEventListener("playing", onPlaying);
  65105. video.play();
  65106. })
  65107. .catch(function (err) {
  65108. BABYLON.Tools.Error(err.name);
  65109. });
  65110. }
  65111. else {
  65112. navigator.getUserMedia =
  65113. navigator.getUserMedia ||
  65114. navigator.webkitGetUserMedia ||
  65115. navigator.mozGetUserMedia ||
  65116. navigator.msGetUserMedia;
  65117. if (navigator.getUserMedia) {
  65118. navigator.getUserMedia({
  65119. video: {
  65120. deviceId: constraintsDeviceId,
  65121. width: {
  65122. min: (constraints && constraints.minWidth) || 256,
  65123. max: (constraints && constraints.maxWidth) || 640,
  65124. },
  65125. height: {
  65126. min: (constraints && constraints.minHeight) || 256,
  65127. max: (constraints && constraints.maxHeight) || 480,
  65128. },
  65129. },
  65130. }, function (stream) {
  65131. if (video.mozSrcObject !== undefined) {
  65132. // hack for Firefox < 19
  65133. video.mozSrcObject = stream;
  65134. }
  65135. else {
  65136. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65137. }
  65138. video.play();
  65139. if (onReady) {
  65140. onReady(new VideoTexture("video", video, scene, true, true));
  65141. }
  65142. }, function (e) {
  65143. BABYLON.Tools.Error(e.name);
  65144. });
  65145. }
  65146. }
  65147. };
  65148. return VideoTexture;
  65149. }(BABYLON.Texture));
  65150. BABYLON.VideoTexture = VideoTexture;
  65151. })(BABYLON || (BABYLON = {}));
  65152. //# sourceMappingURL=babylon.videoTexture.js.map
  65153. var BABYLON;
  65154. (function (BABYLON) {
  65155. var RawTexture = /** @class */ (function (_super) {
  65156. __extends(RawTexture, _super);
  65157. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65159. if (invertY === void 0) { invertY = false; }
  65160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65161. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65162. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65163. _this.format = format;
  65164. _this._engine = scene.getEngine();
  65165. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65166. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65167. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65168. return _this;
  65169. }
  65170. RawTexture.prototype.update = function (data) {
  65171. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65172. };
  65173. // Statics
  65174. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65175. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65176. if (invertY === void 0) { invertY = false; }
  65177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65178. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65179. };
  65180. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65181. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65182. if (invertY === void 0) { invertY = false; }
  65183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65184. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65185. };
  65186. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65187. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65188. if (invertY === void 0) { invertY = false; }
  65189. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65190. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65191. };
  65192. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65193. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65194. if (invertY === void 0) { invertY = false; }
  65195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65196. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65197. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65198. };
  65199. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65200. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65201. if (invertY === void 0) { invertY = false; }
  65202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65203. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65204. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65205. };
  65206. return RawTexture;
  65207. }(BABYLON.Texture));
  65208. BABYLON.RawTexture = RawTexture;
  65209. })(BABYLON || (BABYLON = {}));
  65210. //# sourceMappingURL=babylon.rawTexture.js.map
  65211. var BABYLON;
  65212. (function (BABYLON) {
  65213. /**
  65214. * Class used to store 3D textures containing user data
  65215. */
  65216. var RawTexture3D = /** @class */ (function (_super) {
  65217. __extends(RawTexture3D, _super);
  65218. /**
  65219. * Create a new RawTexture3D
  65220. * @param data defines the data of the texture
  65221. * @param width defines the width of the texture
  65222. * @param height defines the height of the texture
  65223. * @param depth defines the depth of the texture
  65224. * @param format defines the texture format to use
  65225. * @param scene defines the hosting scene
  65226. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65227. * @param invertY defines if texture must be stored with Y axis inverted
  65228. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65229. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65230. */
  65231. function RawTexture3D(data, width, height, depth,
  65232. /** Gets or sets the texture format to use */
  65233. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65235. if (invertY === void 0) { invertY = false; }
  65236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65237. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65238. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65239. _this.format = format;
  65240. _this._engine = scene.getEngine();
  65241. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65242. _this.is3D = true;
  65243. return _this;
  65244. }
  65245. /**
  65246. * Update the texture with new data
  65247. * @param data defines the data to store in the texture
  65248. */
  65249. RawTexture3D.prototype.update = function (data) {
  65250. if (!this._texture) {
  65251. return;
  65252. }
  65253. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65254. };
  65255. return RawTexture3D;
  65256. }(BABYLON.Texture));
  65257. BABYLON.RawTexture3D = RawTexture3D;
  65258. })(BABYLON || (BABYLON = {}));
  65259. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65260. var BABYLON;
  65261. (function (BABYLON) {
  65262. /**
  65263. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65264. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65265. */
  65266. var PostProcess = /** @class */ (function () {
  65267. /**
  65268. * Creates a new instance PostProcess
  65269. * @param name The name of the PostProcess.
  65270. * @param fragmentUrl The url of the fragment shader to be used.
  65271. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65272. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65273. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65274. * @param camera The camera to apply the render pass to.
  65275. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65276. * @param engine The engine which the post process will be applied. (default: current engine)
  65277. * @param reusable If the post process can be reused on the same frame. (default: false)
  65278. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65279. * @param textureType Type of textures used when performing the post process. (default: 0)
  65280. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65281. * @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
  65282. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65283. */
  65284. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65286. if (defines === void 0) { defines = null; }
  65287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65288. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65289. if (blockCompilation === void 0) { blockCompilation = false; }
  65290. this.name = name;
  65291. /**
  65292. * Width of the texture to apply the post process on
  65293. */
  65294. this.width = -1;
  65295. /**
  65296. * Height of the texture to apply the post process on
  65297. */
  65298. this.height = -1;
  65299. /**
  65300. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65301. */
  65302. this._outputTexture = null;
  65303. /**
  65304. * If the buffer needs to be cleared before applying the post process. (default: true)
  65305. * Should be set to false if shader will overwrite all previous pixels.
  65306. */
  65307. this.autoClear = true;
  65308. /**
  65309. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65310. */
  65311. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65312. /**
  65313. * Animations to be used for the post processing
  65314. */
  65315. this.animations = new Array();
  65316. /**
  65317. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65318. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65319. */
  65320. this.enablePixelPerfectMode = false;
  65321. /**
  65322. * Force the postprocess to be applied without taking in account viewport
  65323. */
  65324. this.forceFullscreenViewport = true;
  65325. /**
  65326. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65327. *
  65328. * | Value | Type | Description |
  65329. * | ----- | ----------------------------------- | ----------- |
  65330. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65331. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65332. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65333. *
  65334. */
  65335. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65336. /**
  65337. * Force textures to be a power of two (default: false)
  65338. */
  65339. this.alwaysForcePOT = false;
  65340. /**
  65341. * Number of sample textures (default: 1)
  65342. */
  65343. this.samples = 1;
  65344. /**
  65345. * Modify the scale of the post process to be the same as the viewport (default: false)
  65346. */
  65347. this.adaptScaleToCurrentViewport = false;
  65348. this._reusable = false;
  65349. /**
  65350. * Smart array of input and output textures for the post process.
  65351. */
  65352. this._textures = new BABYLON.SmartArray(2);
  65353. /**
  65354. * The index in _textures that corresponds to the output texture.
  65355. */
  65356. this._currentRenderTextureInd = 0;
  65357. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65358. this._texelSize = BABYLON.Vector2.Zero();
  65359. // Events
  65360. /**
  65361. * An event triggered when the postprocess is activated.
  65362. */
  65363. this.onActivateObservable = new BABYLON.Observable();
  65364. /**
  65365. * An event triggered when the postprocess changes its size.
  65366. */
  65367. this.onSizeChangedObservable = new BABYLON.Observable();
  65368. /**
  65369. * An event triggered when the postprocess applies its effect.
  65370. */
  65371. this.onApplyObservable = new BABYLON.Observable();
  65372. /**
  65373. * An event triggered before rendering the postprocess
  65374. */
  65375. this.onBeforeRenderObservable = new BABYLON.Observable();
  65376. /**
  65377. * An event triggered after rendering the postprocess
  65378. */
  65379. this.onAfterRenderObservable = new BABYLON.Observable();
  65380. if (camera != null) {
  65381. this._camera = camera;
  65382. this._scene = camera.getScene();
  65383. camera.attachPostProcess(this);
  65384. this._engine = this._scene.getEngine();
  65385. this._scene.postProcesses.push(this);
  65386. }
  65387. else if (engine) {
  65388. this._engine = engine;
  65389. this._engine.postProcesses.push(this);
  65390. }
  65391. this._options = options;
  65392. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65393. this._reusable = reusable || false;
  65394. this._textureType = textureType;
  65395. this._samplers = samplers || [];
  65396. this._samplers.push("textureSampler");
  65397. this._fragmentUrl = fragmentUrl;
  65398. this._vertexUrl = vertexUrl;
  65399. this._parameters = parameters || [];
  65400. this._parameters.push("scale");
  65401. this._indexParameters = indexParameters;
  65402. if (!blockCompilation) {
  65403. this.updateEffect(defines);
  65404. }
  65405. }
  65406. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65407. /**
  65408. * A function that is added to the onActivateObservable
  65409. */
  65410. set: function (callback) {
  65411. if (this._onActivateObserver) {
  65412. this.onActivateObservable.remove(this._onActivateObserver);
  65413. }
  65414. if (callback) {
  65415. this._onActivateObserver = this.onActivateObservable.add(callback);
  65416. }
  65417. },
  65418. enumerable: true,
  65419. configurable: true
  65420. });
  65421. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65422. /**
  65423. * A function that is added to the onSizeChangedObservable
  65424. */
  65425. set: function (callback) {
  65426. if (this._onSizeChangedObserver) {
  65427. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65428. }
  65429. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65430. },
  65431. enumerable: true,
  65432. configurable: true
  65433. });
  65434. Object.defineProperty(PostProcess.prototype, "onApply", {
  65435. /**
  65436. * A function that is added to the onApplyObservable
  65437. */
  65438. set: function (callback) {
  65439. if (this._onApplyObserver) {
  65440. this.onApplyObservable.remove(this._onApplyObserver);
  65441. }
  65442. this._onApplyObserver = this.onApplyObservable.add(callback);
  65443. },
  65444. enumerable: true,
  65445. configurable: true
  65446. });
  65447. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65448. /**
  65449. * A function that is added to the onBeforeRenderObservable
  65450. */
  65451. set: function (callback) {
  65452. if (this._onBeforeRenderObserver) {
  65453. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65454. }
  65455. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65456. },
  65457. enumerable: true,
  65458. configurable: true
  65459. });
  65460. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65461. /**
  65462. * A function that is added to the onAfterRenderObservable
  65463. */
  65464. set: function (callback) {
  65465. if (this._onAfterRenderObserver) {
  65466. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65467. }
  65468. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65469. },
  65470. enumerable: true,
  65471. configurable: true
  65472. });
  65473. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65474. /**
  65475. * 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
  65476. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65477. */
  65478. get: function () {
  65479. return this._textures.data[this._currentRenderTextureInd];
  65480. },
  65481. set: function (value) {
  65482. this._forcedOutputTexture = value;
  65483. },
  65484. enumerable: true,
  65485. configurable: true
  65486. });
  65487. /**
  65488. * Gets the camera which post process is applied to.
  65489. * @returns The camera the post process is applied to.
  65490. */
  65491. PostProcess.prototype.getCamera = function () {
  65492. return this._camera;
  65493. };
  65494. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65495. /**
  65496. * Gets the texel size of the postprocess.
  65497. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65498. */
  65499. get: function () {
  65500. if (this._shareOutputWithPostProcess) {
  65501. return this._shareOutputWithPostProcess.texelSize;
  65502. }
  65503. if (this._forcedOutputTexture) {
  65504. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65505. }
  65506. return this._texelSize;
  65507. },
  65508. enumerable: true,
  65509. configurable: true
  65510. });
  65511. /**
  65512. * Gets the engine which this post process belongs to.
  65513. * @returns The engine the post process was enabled with.
  65514. */
  65515. PostProcess.prototype.getEngine = function () {
  65516. return this._engine;
  65517. };
  65518. /**
  65519. * The effect that is created when initializing the post process.
  65520. * @returns The created effect corrisponding the the postprocess.
  65521. */
  65522. PostProcess.prototype.getEffect = function () {
  65523. return this._effect;
  65524. };
  65525. /**
  65526. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65527. * @param postProcess The post process to share the output with.
  65528. * @returns This post process.
  65529. */
  65530. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65531. this._disposeTextures();
  65532. this._shareOutputWithPostProcess = postProcess;
  65533. return this;
  65534. };
  65535. /**
  65536. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65537. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65538. */
  65539. PostProcess.prototype.useOwnOutput = function () {
  65540. if (this._textures.length == 0) {
  65541. this._textures = new BABYLON.SmartArray(2);
  65542. }
  65543. this._shareOutputWithPostProcess = null;
  65544. };
  65545. /**
  65546. * Updates the effect with the current post process compile time values and recompiles the shader.
  65547. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65548. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65549. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65550. * @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
  65551. * @param onCompiled Called when the shader has been compiled.
  65552. * @param onError Called if there is an error when compiling a shader.
  65553. */
  65554. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65555. if (defines === void 0) { defines = null; }
  65556. if (uniforms === void 0) { uniforms = null; }
  65557. if (samplers === void 0) { samplers = null; }
  65558. 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);
  65559. };
  65560. /**
  65561. * The post process is reusable if it can be used multiple times within one frame.
  65562. * @returns If the post process is reusable
  65563. */
  65564. PostProcess.prototype.isReusable = function () {
  65565. return this._reusable;
  65566. };
  65567. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65568. PostProcess.prototype.markTextureDirty = function () {
  65569. this.width = -1;
  65570. };
  65571. /**
  65572. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65573. * 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.
  65574. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65575. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65576. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65577. * @returns The target texture that was bound to be written to.
  65578. */
  65579. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65580. var _this = this;
  65581. if (sourceTexture === void 0) { sourceTexture = null; }
  65582. camera = camera || this._camera;
  65583. var scene = camera.getScene();
  65584. var engine = scene.getEngine();
  65585. var maxSize = engine.getCaps().maxTextureSize;
  65586. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65587. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65588. // 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
  65589. var webVRCamera = camera.parent;
  65590. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65591. requiredWidth /= 2;
  65592. }
  65593. var desiredWidth = (this._options.width || requiredWidth);
  65594. var desiredHeight = this._options.height || requiredHeight;
  65595. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65596. if (this.adaptScaleToCurrentViewport) {
  65597. var currentViewport = engine.currentViewport;
  65598. if (currentViewport) {
  65599. desiredWidth *= currentViewport.width;
  65600. desiredHeight *= currentViewport.height;
  65601. }
  65602. }
  65603. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65604. if (!this._options.width) {
  65605. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65606. }
  65607. if (!this._options.height) {
  65608. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65609. }
  65610. }
  65611. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65612. if (this._textures.length > 0) {
  65613. for (var i = 0; i < this._textures.length; i++) {
  65614. this._engine._releaseTexture(this._textures.data[i]);
  65615. }
  65616. this._textures.reset();
  65617. }
  65618. this.width = desiredWidth;
  65619. this.height = desiredHeight;
  65620. var textureSize = { width: this.width, height: this.height };
  65621. var textureOptions = {
  65622. generateMipMaps: false,
  65623. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65624. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65625. samplingMode: this.renderTargetSamplingMode,
  65626. type: this._textureType
  65627. };
  65628. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65629. if (this._reusable) {
  65630. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65631. }
  65632. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65633. this.onSizeChangedObservable.notifyObservers(this);
  65634. }
  65635. this._textures.forEach(function (texture) {
  65636. if (texture.samples !== _this.samples) {
  65637. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65638. }
  65639. });
  65640. }
  65641. var target;
  65642. if (this._shareOutputWithPostProcess) {
  65643. target = this._shareOutputWithPostProcess.inputTexture;
  65644. }
  65645. else if (this._forcedOutputTexture) {
  65646. target = this._forcedOutputTexture;
  65647. this.width = this._forcedOutputTexture.width;
  65648. this.height = this._forcedOutputTexture.height;
  65649. }
  65650. else {
  65651. target = this.inputTexture;
  65652. }
  65653. // Bind the input of this post process to be used as the output of the previous post process.
  65654. if (this.enablePixelPerfectMode) {
  65655. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65656. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65657. }
  65658. else {
  65659. this._scaleRatio.copyFromFloats(1, 1);
  65660. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65661. }
  65662. this.onActivateObservable.notifyObservers(camera);
  65663. // Clear
  65664. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65665. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65666. }
  65667. if (this._reusable) {
  65668. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65669. }
  65670. return target;
  65671. };
  65672. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65673. /**
  65674. * If the post process is supported.
  65675. */
  65676. get: function () {
  65677. return this._effect.isSupported;
  65678. },
  65679. enumerable: true,
  65680. configurable: true
  65681. });
  65682. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65683. /**
  65684. * The aspect ratio of the output texture.
  65685. */
  65686. get: function () {
  65687. if (this._shareOutputWithPostProcess) {
  65688. return this._shareOutputWithPostProcess.aspectRatio;
  65689. }
  65690. if (this._forcedOutputTexture) {
  65691. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65692. }
  65693. return this.width / this.height;
  65694. },
  65695. enumerable: true,
  65696. configurable: true
  65697. });
  65698. /**
  65699. * Get a value indicating if the post-process is ready to be used
  65700. * @returns true if the post-process is ready (shader is compiled)
  65701. */
  65702. PostProcess.prototype.isReady = function () {
  65703. return this._effect && this._effect.isReady();
  65704. };
  65705. /**
  65706. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65707. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65708. */
  65709. PostProcess.prototype.apply = function () {
  65710. // Check
  65711. if (!this._effect || !this._effect.isReady())
  65712. return null;
  65713. // States
  65714. this._engine.enableEffect(this._effect);
  65715. this._engine.setState(false);
  65716. this._engine.setDepthBuffer(false);
  65717. this._engine.setDepthWrite(false);
  65718. // Alpha
  65719. this._engine.setAlphaMode(this.alphaMode);
  65720. if (this.alphaConstants) {
  65721. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65722. }
  65723. // Bind the output texture of the preivous post process as the input to this post process.
  65724. var source;
  65725. if (this._shareOutputWithPostProcess) {
  65726. source = this._shareOutputWithPostProcess.inputTexture;
  65727. }
  65728. else if (this._forcedOutputTexture) {
  65729. source = this._forcedOutputTexture;
  65730. }
  65731. else {
  65732. source = this.inputTexture;
  65733. }
  65734. this._effect._bindTexture("textureSampler", source);
  65735. // Parameters
  65736. this._effect.setVector2("scale", this._scaleRatio);
  65737. this.onApplyObservable.notifyObservers(this._effect);
  65738. return this._effect;
  65739. };
  65740. PostProcess.prototype._disposeTextures = function () {
  65741. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65742. return;
  65743. }
  65744. if (this._textures.length > 0) {
  65745. for (var i = 0; i < this._textures.length; i++) {
  65746. this._engine._releaseTexture(this._textures.data[i]);
  65747. }
  65748. }
  65749. this._textures.dispose();
  65750. };
  65751. /**
  65752. * Disposes the post process.
  65753. * @param camera The camera to dispose the post process on.
  65754. */
  65755. PostProcess.prototype.dispose = function (camera) {
  65756. camera = camera || this._camera;
  65757. this._disposeTextures();
  65758. if (this._scene) {
  65759. var index_1 = this._scene.postProcesses.indexOf(this);
  65760. if (index_1 !== -1) {
  65761. this._scene.postProcesses.splice(index_1, 1);
  65762. }
  65763. }
  65764. else {
  65765. var index_2 = this._engine.postProcesses.indexOf(this);
  65766. if (index_2 !== -1) {
  65767. this._engine.postProcesses.splice(index_2, 1);
  65768. }
  65769. }
  65770. if (!camera) {
  65771. return;
  65772. }
  65773. camera.detachPostProcess(this);
  65774. var index = camera._postProcesses.indexOf(this);
  65775. if (index === 0 && camera._postProcesses.length > 0) {
  65776. var firstPostProcess = this._camera._getFirstPostProcess();
  65777. if (firstPostProcess) {
  65778. firstPostProcess.markTextureDirty();
  65779. }
  65780. }
  65781. this.onActivateObservable.clear();
  65782. this.onAfterRenderObservable.clear();
  65783. this.onApplyObservable.clear();
  65784. this.onBeforeRenderObservable.clear();
  65785. this.onSizeChangedObservable.clear();
  65786. };
  65787. return PostProcess;
  65788. }());
  65789. BABYLON.PostProcess = PostProcess;
  65790. })(BABYLON || (BABYLON = {}));
  65791. //# sourceMappingURL=babylon.postProcess.js.map
  65792. var BABYLON;
  65793. (function (BABYLON) {
  65794. var PassPostProcess = /** @class */ (function (_super) {
  65795. __extends(PassPostProcess, _super);
  65796. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65797. if (camera === void 0) { camera = null; }
  65798. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65799. if (blockCompilation === void 0) { blockCompilation = false; }
  65800. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65801. }
  65802. return PassPostProcess;
  65803. }(BABYLON.PostProcess));
  65804. BABYLON.PassPostProcess = PassPostProcess;
  65805. })(BABYLON || (BABYLON = {}));
  65806. //# sourceMappingURL=babylon.passPostProcess.js.map
  65807. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65808. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65809. s = arguments[i];
  65810. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65811. t[p] = s[p];
  65812. }
  65813. return t;
  65814. };
  65815. var BABYLON;
  65816. (function (BABYLON) {
  65817. /**
  65818. * Default implementation IShadowGenerator.
  65819. * This is the main object responsible of generating shadows in the framework.
  65820. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65821. */
  65822. var ShadowGenerator = /** @class */ (function () {
  65823. /**
  65824. * Creates a ShadowGenerator object.
  65825. * A ShadowGenerator is the required tool to use the shadows.
  65826. * Each light casting shadows needs to use its own ShadowGenerator.
  65827. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65828. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65829. * @param light The light object generating the shadows.
  65830. * @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.
  65831. */
  65832. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65833. this._bias = 0.00005;
  65834. this._normalBias = 0;
  65835. this._blurBoxOffset = 1;
  65836. this._blurScale = 2;
  65837. this._blurKernel = 1;
  65838. this._useKernelBlur = false;
  65839. this._filter = ShadowGenerator.FILTER_NONE;
  65840. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65841. this._contactHardeningLightSizeUVRatio = 0.1;
  65842. this._darkness = 0;
  65843. this._transparencyShadow = false;
  65844. /**
  65845. * Controls the extent to which the shadows fade out at the edge of the frustum
  65846. * Used only by directionals and spots
  65847. */
  65848. this.frustumEdgeFalloff = 0;
  65849. /**
  65850. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65851. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65852. * It might on the other hand introduce peter panning.
  65853. */
  65854. this.forceBackFacesOnly = false;
  65855. this._lightDirection = BABYLON.Vector3.Zero();
  65856. this._viewMatrix = BABYLON.Matrix.Zero();
  65857. this._projectionMatrix = BABYLON.Matrix.Zero();
  65858. this._transformMatrix = BABYLON.Matrix.Zero();
  65859. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65860. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65861. this._currentFaceIndex = 0;
  65862. this._currentFaceIndexCache = 0;
  65863. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65864. this._mapSize = mapSize;
  65865. this._light = light;
  65866. this._scene = light.getScene();
  65867. light._shadowGenerator = this;
  65868. // Texture type fallback from float to int if not supported.
  65869. var caps = this._scene.getEngine().getCaps();
  65870. if (!useFullFloatFirst) {
  65871. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65872. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65873. }
  65874. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65875. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65876. }
  65877. else {
  65878. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65879. }
  65880. }
  65881. else {
  65882. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65883. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65884. }
  65885. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65886. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65887. }
  65888. else {
  65889. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65890. }
  65891. }
  65892. this._initializeGenerator();
  65893. this._applyFilterValues();
  65894. }
  65895. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65896. /**
  65897. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65898. */
  65899. get: function () {
  65900. return this._bias;
  65901. },
  65902. /**
  65903. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65904. */
  65905. set: function (bias) {
  65906. this._bias = bias;
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65912. /**
  65913. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65914. */
  65915. get: function () {
  65916. return this._normalBias;
  65917. },
  65918. /**
  65919. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65920. */
  65921. set: function (normalBias) {
  65922. this._normalBias = normalBias;
  65923. },
  65924. enumerable: true,
  65925. configurable: true
  65926. });
  65927. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65928. /**
  65929. * Gets the blur box offset: offset applied during the blur pass.
  65930. * Only usefull if useKernelBlur = false
  65931. */
  65932. get: function () {
  65933. return this._blurBoxOffset;
  65934. },
  65935. /**
  65936. * Sets the blur box offset: offset applied during the blur pass.
  65937. * Only usefull if useKernelBlur = false
  65938. */
  65939. set: function (value) {
  65940. if (this._blurBoxOffset === value) {
  65941. return;
  65942. }
  65943. this._blurBoxOffset = value;
  65944. this._disposeBlurPostProcesses();
  65945. },
  65946. enumerable: true,
  65947. configurable: true
  65948. });
  65949. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65950. /**
  65951. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65952. * 2 means half of the size.
  65953. */
  65954. get: function () {
  65955. return this._blurScale;
  65956. },
  65957. /**
  65958. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65959. * 2 means half of the size.
  65960. */
  65961. set: function (value) {
  65962. if (this._blurScale === value) {
  65963. return;
  65964. }
  65965. this._blurScale = value;
  65966. this._disposeBlurPostProcesses();
  65967. },
  65968. enumerable: true,
  65969. configurable: true
  65970. });
  65971. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65972. /**
  65973. * Gets the blur kernel: kernel size of the blur pass.
  65974. * Only usefull if useKernelBlur = true
  65975. */
  65976. get: function () {
  65977. return this._blurKernel;
  65978. },
  65979. /**
  65980. * Sets the blur kernel: kernel size of the blur pass.
  65981. * Only usefull if useKernelBlur = true
  65982. */
  65983. set: function (value) {
  65984. if (this._blurKernel === value) {
  65985. return;
  65986. }
  65987. this._blurKernel = value;
  65988. this._disposeBlurPostProcesses();
  65989. },
  65990. enumerable: true,
  65991. configurable: true
  65992. });
  65993. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65994. /**
  65995. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65996. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65997. */
  65998. get: function () {
  65999. return this._useKernelBlur;
  66000. },
  66001. /**
  66002. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66003. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66004. */
  66005. set: function (value) {
  66006. if (this._useKernelBlur === value) {
  66007. return;
  66008. }
  66009. this._useKernelBlur = value;
  66010. this._disposeBlurPostProcesses();
  66011. },
  66012. enumerable: true,
  66013. configurable: true
  66014. });
  66015. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66016. /**
  66017. * Gets the depth scale used in ESM mode.
  66018. */
  66019. get: function () {
  66020. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66021. },
  66022. /**
  66023. * Sets the depth scale used in ESM mode.
  66024. * This can override the scale stored on the light.
  66025. */
  66026. set: function (value) {
  66027. this._depthScale = value;
  66028. },
  66029. enumerable: true,
  66030. configurable: true
  66031. });
  66032. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66033. /**
  66034. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66035. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66036. */
  66037. get: function () {
  66038. return this._filter;
  66039. },
  66040. /**
  66041. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66042. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66043. */
  66044. set: function (value) {
  66045. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66046. if (this._light.needCube()) {
  66047. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66048. this.useExponentialShadowMap = true;
  66049. return;
  66050. }
  66051. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66052. this.useCloseExponentialShadowMap = true;
  66053. return;
  66054. }
  66055. // PCF on cubemap would also be expensive
  66056. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66057. this.usePoissonSampling = true;
  66058. return;
  66059. }
  66060. }
  66061. // Weblg1 fallback for PCF.
  66062. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66063. if (this._scene.getEngine().webGLVersion === 1) {
  66064. this.usePoissonSampling = true;
  66065. return;
  66066. }
  66067. }
  66068. if (this._filter === value) {
  66069. return;
  66070. }
  66071. this._filter = value;
  66072. this._disposeBlurPostProcesses();
  66073. this._applyFilterValues();
  66074. this._light._markMeshesAsLightDirty();
  66075. },
  66076. enumerable: true,
  66077. configurable: true
  66078. });
  66079. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66080. /**
  66081. * Gets if the current filter is set to Poisson Sampling.
  66082. */
  66083. get: function () {
  66084. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66085. },
  66086. /**
  66087. * Sets the current filter to Poisson Sampling.
  66088. */
  66089. set: function (value) {
  66090. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66091. return;
  66092. }
  66093. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66094. },
  66095. enumerable: true,
  66096. configurable: true
  66097. });
  66098. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66099. /**
  66100. * Gets if the current filter is set to VSM.
  66101. * DEPRECATED. Should use useExponentialShadowMap instead.
  66102. */
  66103. get: function () {
  66104. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66105. return this.useExponentialShadowMap;
  66106. },
  66107. /**
  66108. * Sets the current filter is to VSM.
  66109. * DEPRECATED. Should use useExponentialShadowMap instead.
  66110. */
  66111. set: function (value) {
  66112. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66113. this.useExponentialShadowMap = value;
  66114. },
  66115. enumerable: true,
  66116. configurable: true
  66117. });
  66118. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66119. /**
  66120. * Gets if the current filter is set to blurred VSM.
  66121. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66122. */
  66123. get: function () {
  66124. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66125. return this.useBlurExponentialShadowMap;
  66126. },
  66127. /**
  66128. * Sets the current filter is to blurred VSM.
  66129. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66130. */
  66131. set: function (value) {
  66132. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66133. this.useBlurExponentialShadowMap = value;
  66134. },
  66135. enumerable: true,
  66136. configurable: true
  66137. });
  66138. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66139. /**
  66140. * Gets if the current filter is set to ESM.
  66141. */
  66142. get: function () {
  66143. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66144. },
  66145. /**
  66146. * Sets the current filter is to ESM.
  66147. */
  66148. set: function (value) {
  66149. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66150. return;
  66151. }
  66152. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66153. },
  66154. enumerable: true,
  66155. configurable: true
  66156. });
  66157. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66158. /**
  66159. * Gets if the current filter is set to filtered ESM.
  66160. */
  66161. get: function () {
  66162. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66163. },
  66164. /**
  66165. * Gets if the current filter is set to filtered ESM.
  66166. */
  66167. set: function (value) {
  66168. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66169. return;
  66170. }
  66171. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66172. },
  66173. enumerable: true,
  66174. configurable: true
  66175. });
  66176. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66177. /**
  66178. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66179. * exponential to prevent steep falloff artifacts).
  66180. */
  66181. get: function () {
  66182. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66183. },
  66184. /**
  66185. * Sets the current filter to "close ESM" (using the inverse of the
  66186. * exponential to prevent steep falloff artifacts).
  66187. */
  66188. set: function (value) {
  66189. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66190. return;
  66191. }
  66192. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66193. },
  66194. enumerable: true,
  66195. configurable: true
  66196. });
  66197. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66198. /**
  66199. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66200. * exponential to prevent steep falloff artifacts).
  66201. */
  66202. get: function () {
  66203. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66204. },
  66205. /**
  66206. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66207. * exponential to prevent steep falloff artifacts).
  66208. */
  66209. set: function (value) {
  66210. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66211. return;
  66212. }
  66213. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66214. },
  66215. enumerable: true,
  66216. configurable: true
  66217. });
  66218. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66219. /**
  66220. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66221. */
  66222. get: function () {
  66223. return this.filter === ShadowGenerator.FILTER_PCF;
  66224. },
  66225. /**
  66226. * Sets the current filter to "PCF" (percentage closer filtering).
  66227. */
  66228. set: function (value) {
  66229. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66230. return;
  66231. }
  66232. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66233. },
  66234. enumerable: true,
  66235. configurable: true
  66236. });
  66237. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66238. /**
  66239. * Gets the PCF or PCSS Quality.
  66240. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66241. */
  66242. get: function () {
  66243. return this._filteringQuality;
  66244. },
  66245. /**
  66246. * Sets the PCF or PCSS Quality.
  66247. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66248. */
  66249. set: function (filteringQuality) {
  66250. this._filteringQuality = filteringQuality;
  66251. },
  66252. enumerable: true,
  66253. configurable: true
  66254. });
  66255. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66256. /**
  66257. * Gets if the current filter is set to "PCSS" (contact hardening).
  66258. */
  66259. get: function () {
  66260. return this.filter === ShadowGenerator.FILTER_PCSS;
  66261. },
  66262. /**
  66263. * Sets the current filter to "PCSS" (contact hardening).
  66264. */
  66265. set: function (value) {
  66266. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66267. return;
  66268. }
  66269. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66270. },
  66271. enumerable: true,
  66272. configurable: true
  66273. });
  66274. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66275. /**
  66276. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66277. * Using a ratio helps keeping shape stability independently of the map size.
  66278. *
  66279. * It does not account for the light projection as it was having too much
  66280. * instability during the light setup or during light position changes.
  66281. *
  66282. * Only valid if useContactHardeningShadow is true.
  66283. */
  66284. get: function () {
  66285. return this._contactHardeningLightSizeUVRatio;
  66286. },
  66287. /**
  66288. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66289. * Using a ratio helps keeping shape stability independently of the map size.
  66290. *
  66291. * It does not account for the light projection as it was having too much
  66292. * instability during the light setup or during light position changes.
  66293. *
  66294. * Only valid if useContactHardeningShadow is true.
  66295. */
  66296. set: function (contactHardeningLightSizeUVRatio) {
  66297. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. /**
  66303. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66304. * 0 means strongest and 1 would means no shadow.
  66305. * @returns the darkness.
  66306. */
  66307. ShadowGenerator.prototype.getDarkness = function () {
  66308. return this._darkness;
  66309. };
  66310. /**
  66311. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66312. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66313. * @returns the shadow generator allowing fluent coding.
  66314. */
  66315. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66316. if (darkness >= 1.0)
  66317. this._darkness = 1.0;
  66318. else if (darkness <= 0.0)
  66319. this._darkness = 0.0;
  66320. else
  66321. this._darkness = darkness;
  66322. return this;
  66323. };
  66324. /**
  66325. * Sets the ability to have transparent shadow (boolean).
  66326. * @param transparent True if transparent else False
  66327. * @returns the shadow generator allowing fluent coding
  66328. */
  66329. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66330. this._transparencyShadow = transparent;
  66331. return this;
  66332. };
  66333. /**
  66334. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66335. * @returns The render target texture if present otherwise, null
  66336. */
  66337. ShadowGenerator.prototype.getShadowMap = function () {
  66338. return this._shadowMap;
  66339. };
  66340. /**
  66341. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66342. * @returns The render target texture if the shadow map is present otherwise, null
  66343. */
  66344. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66345. if (this._shadowMap2) {
  66346. return this._shadowMap2;
  66347. }
  66348. return this._shadowMap;
  66349. };
  66350. /**
  66351. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66352. * @param mesh Mesh to add
  66353. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66354. * @returns the Shadow Generator itself
  66355. */
  66356. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66357. if (includeDescendants === void 0) { includeDescendants = true; }
  66358. if (!this._shadowMap) {
  66359. return this;
  66360. }
  66361. if (!this._shadowMap.renderList) {
  66362. this._shadowMap.renderList = [];
  66363. }
  66364. this._shadowMap.renderList.push(mesh);
  66365. if (includeDescendants) {
  66366. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66367. }
  66368. return this;
  66369. var _a;
  66370. };
  66371. /**
  66372. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66373. * @param mesh Mesh to remove
  66374. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66375. * @returns the Shadow Generator itself
  66376. */
  66377. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66378. if (includeDescendants === void 0) { includeDescendants = true; }
  66379. if (!this._shadowMap || !this._shadowMap.renderList) {
  66380. return this;
  66381. }
  66382. var index = this._shadowMap.renderList.indexOf(mesh);
  66383. if (index !== -1) {
  66384. this._shadowMap.renderList.splice(index, 1);
  66385. }
  66386. if (includeDescendants) {
  66387. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66388. var child = _a[_i];
  66389. this.removeShadowCaster(child);
  66390. }
  66391. }
  66392. return this;
  66393. };
  66394. /**
  66395. * Returns the associated light object.
  66396. * @returns the light generating the shadow
  66397. */
  66398. ShadowGenerator.prototype.getLight = function () {
  66399. return this._light;
  66400. };
  66401. ShadowGenerator.prototype._initializeGenerator = function () {
  66402. this._light._markMeshesAsLightDirty();
  66403. this._initializeShadowMap();
  66404. };
  66405. ShadowGenerator.prototype._initializeShadowMap = function () {
  66406. var _this = this;
  66407. // Render target
  66408. var engine = this._scene.getEngine();
  66409. if (engine.webGLVersion > 1) {
  66410. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66411. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66412. }
  66413. else {
  66414. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66415. }
  66416. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66417. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66418. this._shadowMap.anisotropicFilteringLevel = 1;
  66419. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66420. this._shadowMap.renderParticles = false;
  66421. this._shadowMap.ignoreCameraViewport = true;
  66422. // Record Face Index before render.
  66423. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66424. _this._currentFaceIndex = faceIndex;
  66425. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66426. engine.setColorWrite(false);
  66427. }
  66428. });
  66429. // Custom render function.
  66430. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66431. // Blur if required afer render.
  66432. this._shadowMap.onAfterUnbindObservable.add(function () {
  66433. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66434. engine.setColorWrite(true);
  66435. }
  66436. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66437. return;
  66438. }
  66439. var shadowMap = _this.getShadowMapForRendering();
  66440. if (shadowMap) {
  66441. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66442. }
  66443. });
  66444. // Clear according to the chosen filter.
  66445. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66446. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66447. this._shadowMap.onClearObservable.add(function (engine) {
  66448. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66449. engine.clear(clearOne, false, true, false);
  66450. }
  66451. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66452. engine.clear(clearZero, true, true, false);
  66453. }
  66454. else {
  66455. engine.clear(clearOne, true, true, false);
  66456. }
  66457. });
  66458. };
  66459. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66460. var _this = this;
  66461. var engine = this._scene.getEngine();
  66462. var targetSize = this._mapSize / this.blurScale;
  66463. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66464. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66465. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66466. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66467. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66468. }
  66469. if (this.useKernelBlur) {
  66470. 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);
  66471. this._kernelBlurXPostprocess.width = targetSize;
  66472. this._kernelBlurXPostprocess.height = targetSize;
  66473. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66474. effect.setTexture("textureSampler", _this._shadowMap);
  66475. });
  66476. 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);
  66477. this._kernelBlurXPostprocess.autoClear = false;
  66478. this._kernelBlurYPostprocess.autoClear = false;
  66479. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66480. this._kernelBlurXPostprocess.packedFloat = true;
  66481. this._kernelBlurYPostprocess.packedFloat = true;
  66482. }
  66483. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66484. }
  66485. else {
  66486. 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);
  66487. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66488. effect.setFloat2("screenSize", targetSize, targetSize);
  66489. effect.setTexture("textureSampler", _this._shadowMap);
  66490. });
  66491. this._boxBlurPostprocess.autoClear = false;
  66492. this._blurPostProcesses = [this._boxBlurPostprocess];
  66493. }
  66494. };
  66495. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66496. var index;
  66497. var engine = this._scene.getEngine();
  66498. if (depthOnlySubMeshes.length) {
  66499. engine.setColorWrite(false);
  66500. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66501. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66502. }
  66503. engine.setColorWrite(true);
  66504. }
  66505. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66506. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66507. }
  66508. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66509. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66510. }
  66511. if (this._transparencyShadow) {
  66512. for (index = 0; index < transparentSubMeshes.length; index++) {
  66513. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66514. }
  66515. }
  66516. };
  66517. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66518. var _this = this;
  66519. var mesh = subMesh.getRenderingMesh();
  66520. var scene = this._scene;
  66521. var engine = scene.getEngine();
  66522. var material = subMesh.getMaterial();
  66523. if (!material) {
  66524. return;
  66525. }
  66526. // Culling
  66527. engine.setState(material.backFaceCulling);
  66528. // Managing instances
  66529. var batch = mesh._getInstancesRenderList(subMesh._id);
  66530. if (batch.mustReturn) {
  66531. return;
  66532. }
  66533. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66534. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66535. engine.enableEffect(this._effect);
  66536. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66537. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66538. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66539. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66540. this._effect.setVector3("lightData", this._cachedDirection);
  66541. }
  66542. else {
  66543. this._effect.setVector3("lightData", this._cachedPosition);
  66544. }
  66545. if (scene.activeCamera) {
  66546. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66547. }
  66548. // Alpha test
  66549. if (material && material.needAlphaTesting()) {
  66550. var alphaTexture = material.getAlphaTestTexture();
  66551. if (alphaTexture) {
  66552. this._effect.setTexture("diffuseSampler", alphaTexture);
  66553. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66554. }
  66555. }
  66556. // Bones
  66557. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66558. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66559. }
  66560. // Morph targets
  66561. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66562. if (this.forceBackFacesOnly) {
  66563. engine.setState(true, 0, false, true);
  66564. }
  66565. // Draw
  66566. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66567. if (this.forceBackFacesOnly) {
  66568. engine.setState(true, 0, false, false);
  66569. }
  66570. }
  66571. else {
  66572. // Need to reset refresh rate of the shadowMap
  66573. if (this._shadowMap) {
  66574. this._shadowMap.resetRefreshCounter();
  66575. }
  66576. }
  66577. };
  66578. ShadowGenerator.prototype._applyFilterValues = function () {
  66579. if (!this._shadowMap) {
  66580. return;
  66581. }
  66582. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66583. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66584. }
  66585. else {
  66586. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66587. }
  66588. };
  66589. /**
  66590. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66591. * @param onCompiled Callback triggered at the and of the effects compilation
  66592. * @param options Sets of optional options forcing the compilation with different modes
  66593. */
  66594. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66595. var _this = this;
  66596. var localOptions = __assign({ useInstances: false }, options);
  66597. var shadowMap = this.getShadowMap();
  66598. if (!shadowMap) {
  66599. if (onCompiled) {
  66600. onCompiled(this);
  66601. }
  66602. return;
  66603. }
  66604. var renderList = shadowMap.renderList;
  66605. if (!renderList) {
  66606. if (onCompiled) {
  66607. onCompiled(this);
  66608. }
  66609. return;
  66610. }
  66611. var subMeshes = new Array();
  66612. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66613. var mesh = renderList_1[_i];
  66614. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66615. }
  66616. if (subMeshes.length === 0) {
  66617. if (onCompiled) {
  66618. onCompiled(this);
  66619. }
  66620. return;
  66621. }
  66622. var currentIndex = 0;
  66623. var checkReady = function () {
  66624. if (!_this._scene || !_this._scene.getEngine()) {
  66625. return;
  66626. }
  66627. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66628. currentIndex++;
  66629. if (currentIndex >= subMeshes.length) {
  66630. if (onCompiled) {
  66631. onCompiled(_this);
  66632. }
  66633. return;
  66634. }
  66635. }
  66636. setTimeout(checkReady, 16);
  66637. };
  66638. checkReady();
  66639. };
  66640. /**
  66641. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66642. * @param options Sets of optional options forcing the compilation with different modes
  66643. * @returns A promise that resolves when the compilation completes
  66644. */
  66645. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66646. var _this = this;
  66647. return new Promise(function (resolve) {
  66648. _this.forceCompilation(function () {
  66649. resolve();
  66650. }, options);
  66651. });
  66652. };
  66653. /**
  66654. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66655. * @param subMesh The submesh we want to render in the shadow map
  66656. * @param useInstances Defines wether will draw in the map using instances
  66657. * @returns true if ready otherwise, false
  66658. */
  66659. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66660. var defines = [];
  66661. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66662. defines.push("#define FLOAT");
  66663. }
  66664. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66665. defines.push("#define ESM");
  66666. }
  66667. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66668. defines.push("#define DEPTHTEXTURE");
  66669. }
  66670. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66671. var mesh = subMesh.getMesh();
  66672. var material = subMesh.getMaterial();
  66673. // Normal bias.
  66674. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66675. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66676. defines.push("#define NORMAL");
  66677. if (mesh.nonUniformScaling) {
  66678. defines.push("#define NONUNIFORMSCALING");
  66679. }
  66680. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66681. defines.push("#define DIRECTIONINLIGHTDATA");
  66682. }
  66683. }
  66684. // Alpha test
  66685. if (material && material.needAlphaTesting()) {
  66686. var alphaTexture = material.getAlphaTestTexture();
  66687. if (alphaTexture) {
  66688. defines.push("#define ALPHATEST");
  66689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66690. attribs.push(BABYLON.VertexBuffer.UVKind);
  66691. defines.push("#define UV1");
  66692. }
  66693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66694. if (alphaTexture.coordinatesIndex === 1) {
  66695. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66696. defines.push("#define UV2");
  66697. }
  66698. }
  66699. }
  66700. }
  66701. // Bones
  66702. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66705. if (mesh.numBoneInfluencers > 4) {
  66706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66708. }
  66709. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66710. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66711. }
  66712. else {
  66713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66714. }
  66715. // Morph targets
  66716. var manager = mesh.morphTargetManager;
  66717. var morphInfluencers = 0;
  66718. if (manager) {
  66719. if (manager.numInfluencers > 0) {
  66720. defines.push("#define MORPHTARGETS");
  66721. morphInfluencers = manager.numInfluencers;
  66722. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66723. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66724. }
  66725. }
  66726. // Instances
  66727. if (useInstances) {
  66728. defines.push("#define INSTANCES");
  66729. attribs.push("world0");
  66730. attribs.push("world1");
  66731. attribs.push("world2");
  66732. attribs.push("world3");
  66733. }
  66734. // Get correct effect
  66735. var join = defines.join("\n");
  66736. if (this._cachedDefines !== join) {
  66737. this._cachedDefines = join;
  66738. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66739. }
  66740. if (!this._effect.isReady()) {
  66741. return false;
  66742. }
  66743. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66744. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66745. this._initializeBlurRTTAndPostProcesses();
  66746. }
  66747. }
  66748. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66749. return false;
  66750. }
  66751. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66752. return false;
  66753. }
  66754. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66755. return false;
  66756. }
  66757. return true;
  66758. };
  66759. /**
  66760. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66761. * @param defines Defines of the material we want to update
  66762. * @param lightIndex Index of the light in the enabled light list of the material
  66763. */
  66764. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66765. var scene = this._scene;
  66766. var light = this._light;
  66767. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66768. return;
  66769. }
  66770. defines["SHADOW" + lightIndex] = true;
  66771. if (this.useContactHardeningShadow) {
  66772. defines["SHADOWPCSS" + lightIndex] = true;
  66773. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66774. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66775. }
  66776. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66777. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66778. }
  66779. // else default to high.
  66780. }
  66781. if (this.usePercentageCloserFiltering) {
  66782. defines["SHADOWPCF" + lightIndex] = true;
  66783. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66784. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66785. }
  66786. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66787. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66788. }
  66789. // else default to high.
  66790. }
  66791. else if (this.usePoissonSampling) {
  66792. defines["SHADOWPOISSON" + lightIndex] = true;
  66793. }
  66794. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66795. defines["SHADOWESM" + lightIndex] = true;
  66796. }
  66797. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66798. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66799. }
  66800. if (light.needCube()) {
  66801. defines["SHADOWCUBE" + lightIndex] = true;
  66802. }
  66803. };
  66804. /**
  66805. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66806. * defined in the generator but impacting the effect).
  66807. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66808. * @param effect The effect we are binfing the information for
  66809. */
  66810. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66811. var light = this._light;
  66812. var scene = this._scene;
  66813. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66814. return;
  66815. }
  66816. var camera = scene.activeCamera;
  66817. if (!camera) {
  66818. return;
  66819. }
  66820. var shadowMap = this.getShadowMap();
  66821. if (!shadowMap) {
  66822. return;
  66823. }
  66824. if (!light.needCube()) {
  66825. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66826. }
  66827. // Only PCF uses depth stencil texture.
  66828. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66829. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66830. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66831. }
  66832. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66833. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66834. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66835. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66836. }
  66837. else {
  66838. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66839. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66840. }
  66841. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66842. };
  66843. /**
  66844. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66845. * (eq to shadow prjection matrix * light transform matrix)
  66846. * @returns The transform matrix used to create the shadow map
  66847. */
  66848. ShadowGenerator.prototype.getTransformMatrix = function () {
  66849. var scene = this._scene;
  66850. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66851. return this._transformMatrix;
  66852. }
  66853. this._currentRenderID = scene.getRenderId();
  66854. this._currentFaceIndexCache = this._currentFaceIndex;
  66855. var lightPosition = this._light.position;
  66856. if (this._light.computeTransformedInformation()) {
  66857. lightPosition = this._light.transformedPosition;
  66858. }
  66859. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66860. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66861. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66862. }
  66863. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66864. this._cachedPosition.copyFrom(lightPosition);
  66865. this._cachedDirection.copyFrom(this._lightDirection);
  66866. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66867. var shadowMap = this.getShadowMap();
  66868. if (shadowMap) {
  66869. var renderList = shadowMap.renderList;
  66870. if (renderList) {
  66871. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66872. }
  66873. }
  66874. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66875. }
  66876. return this._transformMatrix;
  66877. };
  66878. /**
  66879. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66880. * Cube and 2D textures for instance.
  66881. */
  66882. ShadowGenerator.prototype.recreateShadowMap = function () {
  66883. var shadowMap = this._shadowMap;
  66884. if (!shadowMap) {
  66885. return;
  66886. }
  66887. // Track render list.
  66888. var renderList = shadowMap.renderList;
  66889. // Clean up existing data.
  66890. this._disposeRTTandPostProcesses();
  66891. // Reinitializes.
  66892. this._initializeGenerator();
  66893. // Reaffect the filter to ensure a correct fallback if necessary.
  66894. this.filter = this.filter;
  66895. // Reaffect the filter.
  66896. this._applyFilterValues();
  66897. // Reaffect Render List.
  66898. this._shadowMap.renderList = renderList;
  66899. };
  66900. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66901. if (this._shadowMap2) {
  66902. this._shadowMap2.dispose();
  66903. this._shadowMap2 = null;
  66904. }
  66905. if (this._boxBlurPostprocess) {
  66906. this._boxBlurPostprocess.dispose();
  66907. this._boxBlurPostprocess = null;
  66908. }
  66909. if (this._kernelBlurXPostprocess) {
  66910. this._kernelBlurXPostprocess.dispose();
  66911. this._kernelBlurXPostprocess = null;
  66912. }
  66913. if (this._kernelBlurYPostprocess) {
  66914. this._kernelBlurYPostprocess.dispose();
  66915. this._kernelBlurYPostprocess = null;
  66916. }
  66917. this._blurPostProcesses = [];
  66918. };
  66919. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66920. if (this._shadowMap) {
  66921. this._shadowMap.dispose();
  66922. this._shadowMap = null;
  66923. }
  66924. this._disposeBlurPostProcesses();
  66925. };
  66926. /**
  66927. * Disposes the ShadowGenerator.
  66928. * Returns nothing.
  66929. */
  66930. ShadowGenerator.prototype.dispose = function () {
  66931. this._disposeRTTandPostProcesses();
  66932. if (this._light) {
  66933. this._light._shadowGenerator = null;
  66934. this._light._markMeshesAsLightDirty();
  66935. }
  66936. };
  66937. /**
  66938. * Serializes the shadow generator setup to a json object.
  66939. * @returns The serialized JSON object
  66940. */
  66941. ShadowGenerator.prototype.serialize = function () {
  66942. var serializationObject = {};
  66943. var shadowMap = this.getShadowMap();
  66944. if (!shadowMap) {
  66945. return serializationObject;
  66946. }
  66947. serializationObject.lightId = this._light.id;
  66948. serializationObject.mapSize = shadowMap.getRenderSize();
  66949. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66950. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66951. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66952. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66953. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66954. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66955. serializationObject.depthScale = this.depthScale;
  66956. serializationObject.darkness = this.getDarkness();
  66957. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66958. serializationObject.blurKernel = this.blurKernel;
  66959. serializationObject.blurScale = this.blurScale;
  66960. serializationObject.useKernelBlur = this.useKernelBlur;
  66961. serializationObject.transparencyShadow = this._transparencyShadow;
  66962. serializationObject.bias = this.bias;
  66963. serializationObject.normalBias = this.normalBias;
  66964. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66965. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66966. serializationObject.filteringQuality = this.filteringQuality;
  66967. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66968. serializationObject.renderList = [];
  66969. if (shadowMap.renderList) {
  66970. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66971. var mesh = shadowMap.renderList[meshIndex];
  66972. serializationObject.renderList.push(mesh.id);
  66973. }
  66974. }
  66975. return serializationObject;
  66976. };
  66977. /**
  66978. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66979. * @param parsedShadowGenerator The JSON object to parse
  66980. * @param scene The scene to create the shadow map for
  66981. * @returns The parsed shadow generator
  66982. */
  66983. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66984. //casting to point light, as light is missing the position attr and typescript complains.
  66985. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66986. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66987. var shadowMap = shadowGenerator.getShadowMap();
  66988. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66989. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66990. meshes.forEach(function (mesh) {
  66991. if (!shadowMap) {
  66992. return;
  66993. }
  66994. if (!shadowMap.renderList) {
  66995. shadowMap.renderList = [];
  66996. }
  66997. shadowMap.renderList.push(mesh);
  66998. });
  66999. }
  67000. if (parsedShadowGenerator.usePoissonSampling) {
  67001. shadowGenerator.usePoissonSampling = true;
  67002. }
  67003. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67004. shadowGenerator.useExponentialShadowMap = true;
  67005. }
  67006. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67007. shadowGenerator.useBlurExponentialShadowMap = true;
  67008. }
  67009. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67010. shadowGenerator.useCloseExponentialShadowMap = true;
  67011. }
  67012. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67013. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67014. }
  67015. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67016. shadowGenerator.usePercentageCloserFiltering = true;
  67017. }
  67018. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67019. shadowGenerator.useContactHardeningShadow = true;
  67020. }
  67021. if (parsedShadowGenerator.filteringQuality) {
  67022. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67023. }
  67024. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67025. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67026. }
  67027. // Backward compat
  67028. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67029. shadowGenerator.useExponentialShadowMap = true;
  67030. }
  67031. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67032. shadowGenerator.useBlurExponentialShadowMap = true;
  67033. }
  67034. if (parsedShadowGenerator.depthScale) {
  67035. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67036. }
  67037. if (parsedShadowGenerator.blurScale) {
  67038. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67039. }
  67040. if (parsedShadowGenerator.blurBoxOffset) {
  67041. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67042. }
  67043. if (parsedShadowGenerator.useKernelBlur) {
  67044. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67045. }
  67046. if (parsedShadowGenerator.blurKernel) {
  67047. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67048. }
  67049. if (parsedShadowGenerator.bias !== undefined) {
  67050. shadowGenerator.bias = parsedShadowGenerator.bias;
  67051. }
  67052. if (parsedShadowGenerator.normalBias !== undefined) {
  67053. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67054. }
  67055. if (parsedShadowGenerator.darkness) {
  67056. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67057. }
  67058. if (parsedShadowGenerator.transparencyShadow) {
  67059. shadowGenerator.setTransparencyShadow(true);
  67060. }
  67061. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67062. return shadowGenerator;
  67063. };
  67064. /**
  67065. * Shadow generator mode None: no filtering applied.
  67066. */
  67067. ShadowGenerator.FILTER_NONE = 0;
  67068. /**
  67069. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67070. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67071. */
  67072. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67073. /**
  67074. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67075. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67076. */
  67077. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67078. /**
  67079. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67080. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67081. */
  67082. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67083. /**
  67084. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67085. * edge artifacts on steep falloff.
  67086. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67087. */
  67088. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67089. /**
  67090. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67091. * edge artifacts on steep falloff.
  67092. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67093. */
  67094. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67095. /**
  67096. * Shadow generator mode PCF: Percentage Closer Filtering
  67097. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67098. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67099. */
  67100. ShadowGenerator.FILTER_PCF = 6;
  67101. /**
  67102. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67103. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67104. * Contact Hardening
  67105. */
  67106. ShadowGenerator.FILTER_PCSS = 7;
  67107. /**
  67108. * Reserved for PCF and PCSS
  67109. * Highest Quality.
  67110. *
  67111. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67112. *
  67113. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67114. */
  67115. ShadowGenerator.QUALITY_HIGH = 0;
  67116. /**
  67117. * Reserved for PCF and PCSS
  67118. * Good tradeoff for quality/perf cross devices
  67119. *
  67120. * Execute PCF on a 3*3 kernel.
  67121. *
  67122. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67123. */
  67124. ShadowGenerator.QUALITY_MEDIUM = 1;
  67125. /**
  67126. * Reserved for PCF and PCSS
  67127. * The lowest quality but the fastest.
  67128. *
  67129. * Execute PCF on a 1*1 kernel.
  67130. *
  67131. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67132. */
  67133. ShadowGenerator.QUALITY_LOW = 2;
  67134. return ShadowGenerator;
  67135. }());
  67136. BABYLON.ShadowGenerator = ShadowGenerator;
  67137. })(BABYLON || (BABYLON = {}));
  67138. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67139. var BABYLON;
  67140. (function (BABYLON) {
  67141. var DefaultLoadingScreen = /** @class */ (function () {
  67142. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67143. if (_loadingText === void 0) { _loadingText = ""; }
  67144. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67145. var _this = this;
  67146. this._renderingCanvas = _renderingCanvas;
  67147. this._loadingText = _loadingText;
  67148. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67149. // Resize
  67150. this._resizeLoadingUI = function () {
  67151. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67152. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67153. if (!_this._loadingDiv) {
  67154. return;
  67155. }
  67156. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67157. _this._loadingDiv.style.left = canvasRect.left + "px";
  67158. _this._loadingDiv.style.top = canvasRect.top + "px";
  67159. _this._loadingDiv.style.width = canvasRect.width + "px";
  67160. _this._loadingDiv.style.height = canvasRect.height + "px";
  67161. };
  67162. }
  67163. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67164. if (this._loadingDiv) {
  67165. // Do not add a loading screen if there is already one
  67166. return;
  67167. }
  67168. this._loadingDiv = document.createElement("div");
  67169. this._loadingDiv.id = "babylonjsLoadingDiv";
  67170. this._loadingDiv.style.opacity = "0";
  67171. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67172. this._loadingDiv.style.pointerEvents = "none";
  67173. // Loading text
  67174. this._loadingTextDiv = document.createElement("div");
  67175. this._loadingTextDiv.style.position = "absolute";
  67176. this._loadingTextDiv.style.left = "0";
  67177. this._loadingTextDiv.style.top = "50%";
  67178. this._loadingTextDiv.style.marginTop = "80px";
  67179. this._loadingTextDiv.style.width = "100%";
  67180. this._loadingTextDiv.style.height = "20px";
  67181. this._loadingTextDiv.style.fontFamily = "Arial";
  67182. this._loadingTextDiv.style.fontSize = "14px";
  67183. this._loadingTextDiv.style.color = "white";
  67184. this._loadingTextDiv.style.textAlign = "center";
  67185. this._loadingTextDiv.innerHTML = "Loading";
  67186. this._loadingDiv.appendChild(this._loadingTextDiv);
  67187. //set the predefined text
  67188. this._loadingTextDiv.innerHTML = this._loadingText;
  67189. // Generating keyframes
  67190. var style = document.createElement('style');
  67191. style.type = 'text/css';
  67192. 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 }";
  67193. style.innerHTML = keyFrames;
  67194. document.getElementsByTagName('head')[0].appendChild(style);
  67195. // Loading img
  67196. var imgBack = new Image();
  67197. 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";
  67198. imgBack.style.position = "absolute";
  67199. imgBack.style.left = "50%";
  67200. imgBack.style.top = "50%";
  67201. imgBack.style.marginLeft = "-60px";
  67202. imgBack.style.marginTop = "-60px";
  67203. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67204. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67205. imgBack.style.transformOrigin = "50% 50%";
  67206. imgBack.style.webkitTransformOrigin = "50% 50%";
  67207. this._loadingDiv.appendChild(imgBack);
  67208. this._resizeLoadingUI();
  67209. window.addEventListener("resize", this._resizeLoadingUI);
  67210. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67211. document.body.appendChild(this._loadingDiv);
  67212. this._loadingDiv.style.opacity = "1";
  67213. };
  67214. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67215. var _this = this;
  67216. if (!this._loadingDiv) {
  67217. return;
  67218. }
  67219. var onTransitionEnd = function () {
  67220. if (!_this._loadingDiv) {
  67221. return;
  67222. }
  67223. document.body.removeChild(_this._loadingDiv);
  67224. window.removeEventListener("resize", _this._resizeLoadingUI);
  67225. _this._loadingDiv = null;
  67226. };
  67227. this._loadingDiv.style.opacity = "0";
  67228. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67229. };
  67230. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67231. set: function (text) {
  67232. this._loadingText = text;
  67233. if (this._loadingTextDiv) {
  67234. this._loadingTextDiv.innerHTML = this._loadingText;
  67235. }
  67236. },
  67237. enumerable: true,
  67238. configurable: true
  67239. });
  67240. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67241. get: function () {
  67242. return this._loadingDivBackgroundColor;
  67243. },
  67244. set: function (color) {
  67245. this._loadingDivBackgroundColor = color;
  67246. if (!this._loadingDiv) {
  67247. return;
  67248. }
  67249. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67250. },
  67251. enumerable: true,
  67252. configurable: true
  67253. });
  67254. return DefaultLoadingScreen;
  67255. }());
  67256. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67257. })(BABYLON || (BABYLON = {}));
  67258. //# sourceMappingURL=babylon.loadingScreen.js.map
  67259. var BABYLON;
  67260. (function (BABYLON) {
  67261. var SceneLoaderProgressEvent = /** @class */ (function () {
  67262. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67263. this.lengthComputable = lengthComputable;
  67264. this.loaded = loaded;
  67265. this.total = total;
  67266. }
  67267. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67268. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67269. };
  67270. return SceneLoaderProgressEvent;
  67271. }());
  67272. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67273. var SceneLoader = /** @class */ (function () {
  67274. function SceneLoader() {
  67275. }
  67276. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67277. get: function () {
  67278. return 0;
  67279. },
  67280. enumerable: true,
  67281. configurable: true
  67282. });
  67283. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67284. get: function () {
  67285. return 1;
  67286. },
  67287. enumerable: true,
  67288. configurable: true
  67289. });
  67290. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67291. get: function () {
  67292. return 2;
  67293. },
  67294. enumerable: true,
  67295. configurable: true
  67296. });
  67297. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67298. get: function () {
  67299. return 3;
  67300. },
  67301. enumerable: true,
  67302. configurable: true
  67303. });
  67304. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67305. get: function () {
  67306. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67307. },
  67308. set: function (value) {
  67309. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67310. },
  67311. enumerable: true,
  67312. configurable: true
  67313. });
  67314. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67315. get: function () {
  67316. return SceneLoader._ShowLoadingScreen;
  67317. },
  67318. set: function (value) {
  67319. SceneLoader._ShowLoadingScreen = value;
  67320. },
  67321. enumerable: true,
  67322. configurable: true
  67323. });
  67324. Object.defineProperty(SceneLoader, "loggingLevel", {
  67325. get: function () {
  67326. return SceneLoader._loggingLevel;
  67327. },
  67328. set: function (value) {
  67329. SceneLoader._loggingLevel = value;
  67330. },
  67331. enumerable: true,
  67332. configurable: true
  67333. });
  67334. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67335. get: function () {
  67336. return SceneLoader._CleanBoneMatrixWeights;
  67337. },
  67338. set: function (value) {
  67339. SceneLoader._CleanBoneMatrixWeights = value;
  67340. },
  67341. enumerable: true,
  67342. configurable: true
  67343. });
  67344. SceneLoader._getDefaultPlugin = function () {
  67345. return SceneLoader._registeredPlugins[".babylon"];
  67346. };
  67347. SceneLoader._getPluginForExtension = function (extension) {
  67348. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67349. if (registeredPlugin) {
  67350. return registeredPlugin;
  67351. }
  67352. 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");
  67353. return SceneLoader._getDefaultPlugin();
  67354. };
  67355. SceneLoader._getPluginForDirectLoad = function (data) {
  67356. for (var extension in SceneLoader._registeredPlugins) {
  67357. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67358. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67359. return SceneLoader._registeredPlugins[extension];
  67360. }
  67361. }
  67362. return SceneLoader._getDefaultPlugin();
  67363. };
  67364. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67365. if (sceneFilename.name) {
  67366. sceneFilename = sceneFilename.name;
  67367. }
  67368. var queryStringPosition = sceneFilename.indexOf("?");
  67369. if (queryStringPosition !== -1) {
  67370. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67371. }
  67372. var dotPosition = sceneFilename.lastIndexOf(".");
  67373. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67374. return SceneLoader._getPluginForExtension(extension);
  67375. };
  67376. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67377. SceneLoader._getDirectLoad = function (sceneFilename) {
  67378. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67379. return sceneFilename.substr(5);
  67380. }
  67381. return null;
  67382. };
  67383. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67384. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67385. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67386. var plugin;
  67387. if (registeredPlugin.plugin.createPlugin) {
  67388. plugin = registeredPlugin.plugin.createPlugin();
  67389. }
  67390. else {
  67391. plugin = registeredPlugin.plugin;
  67392. }
  67393. var useArrayBuffer = registeredPlugin.isBinary;
  67394. var database;
  67395. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67396. var dataCallback = function (data, responseURL) {
  67397. if (scene.isDisposed) {
  67398. onError("Scene has been disposed");
  67399. return;
  67400. }
  67401. scene.database = database;
  67402. onSuccess(plugin, data, responseURL);
  67403. };
  67404. var request = null;
  67405. var pluginDisposed = false;
  67406. var onDisposeObservable = plugin.onDisposeObservable;
  67407. if (onDisposeObservable) {
  67408. onDisposeObservable.add(function () {
  67409. pluginDisposed = true;
  67410. if (request) {
  67411. request.abort();
  67412. request = null;
  67413. }
  67414. onDispose();
  67415. });
  67416. }
  67417. var manifestChecked = function () {
  67418. if (pluginDisposed) {
  67419. return;
  67420. }
  67421. var url = rootUrl + sceneFilename;
  67422. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67423. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67424. } : undefined, database, useArrayBuffer, function (request, exception) {
  67425. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67426. });
  67427. };
  67428. if (directLoad) {
  67429. dataCallback(directLoad);
  67430. return plugin;
  67431. }
  67432. if (rootUrl.indexOf("file:") === -1) {
  67433. var engine = scene.getEngine();
  67434. var canUseOfflineSupport = engine.enableOfflineSupport;
  67435. if (canUseOfflineSupport) {
  67436. // Also check for exceptions
  67437. var exceptionFound = false;
  67438. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67439. var regex = _a[_i];
  67440. if (regex.test(rootUrl + sceneFilename)) {
  67441. exceptionFound = true;
  67442. break;
  67443. }
  67444. }
  67445. canUseOfflineSupport = !exceptionFound;
  67446. }
  67447. if (canUseOfflineSupport) {
  67448. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67449. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67450. }
  67451. else {
  67452. manifestChecked();
  67453. }
  67454. }
  67455. // Loading file from disk via input file or drag'n'drop
  67456. else {
  67457. var fileOrString = sceneFilename;
  67458. if (fileOrString.name) { // File
  67459. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67460. }
  67461. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67462. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67463. }
  67464. else {
  67465. onError("Unable to find file named " + sceneFilename);
  67466. }
  67467. }
  67468. return plugin;
  67469. };
  67470. // Public functions
  67471. SceneLoader.GetPluginForExtension = function (extension) {
  67472. return SceneLoader._getPluginForExtension(extension).plugin;
  67473. };
  67474. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67475. return !!SceneLoader._registeredPlugins[extension];
  67476. };
  67477. SceneLoader.RegisterPlugin = function (plugin) {
  67478. if (typeof plugin.extensions === "string") {
  67479. var extension = plugin.extensions;
  67480. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67481. plugin: plugin,
  67482. isBinary: false
  67483. };
  67484. }
  67485. else {
  67486. var extensions = plugin.extensions;
  67487. Object.keys(extensions).forEach(function (extension) {
  67488. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67489. plugin: plugin,
  67490. isBinary: extensions[extension].isBinary
  67491. };
  67492. });
  67493. }
  67494. };
  67495. /**
  67496. * Import meshes into a scene
  67497. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67498. * @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)
  67499. * @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)
  67500. * @param scene the instance of BABYLON.Scene to append to
  67501. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67502. * @param onProgress a callback with a progress event for each file being loaded
  67503. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67504. * @param pluginExtension the extension used to determine the plugin
  67505. * @returns The loaded plugin
  67506. */
  67507. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67508. if (sceneFilename === void 0) { sceneFilename = ""; }
  67509. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67510. if (onSuccess === void 0) { onSuccess = null; }
  67511. if (onProgress === void 0) { onProgress = null; }
  67512. if (onError === void 0) { onError = null; }
  67513. if (pluginExtension === void 0) { pluginExtension = null; }
  67514. if (!scene) {
  67515. BABYLON.Tools.Error("No scene available to import mesh to");
  67516. return null;
  67517. }
  67518. if (!sceneFilename) {
  67519. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67520. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67521. }
  67522. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67523. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67524. return null;
  67525. }
  67526. var loadingToken = {};
  67527. scene._addPendingData(loadingToken);
  67528. var disposeHandler = function () {
  67529. scene._removePendingData(loadingToken);
  67530. };
  67531. var errorHandler = function (message, exception) {
  67532. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67533. if (onError) {
  67534. onError(scene, errorMessage, exception);
  67535. }
  67536. else {
  67537. BABYLON.Tools.Error(errorMessage);
  67538. // should the exception be thrown?
  67539. }
  67540. disposeHandler();
  67541. };
  67542. var progressHandler = onProgress ? function (event) {
  67543. try {
  67544. onProgress(event);
  67545. }
  67546. catch (e) {
  67547. errorHandler("Error in onProgress callback", e);
  67548. }
  67549. } : undefined;
  67550. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67551. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67552. if (onSuccess) {
  67553. try {
  67554. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67555. }
  67556. catch (e) {
  67557. errorHandler("Error in onSuccess callback", e);
  67558. }
  67559. }
  67560. scene._removePendingData(loadingToken);
  67561. };
  67562. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67563. if (plugin.rewriteRootURL) {
  67564. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67565. }
  67566. if (sceneFilename === "") {
  67567. if (sceneFilename === "") {
  67568. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67569. }
  67570. }
  67571. if (plugin.importMesh) {
  67572. var syncedPlugin = plugin;
  67573. var meshes = new Array();
  67574. var particleSystems = new Array();
  67575. var skeletons = new Array();
  67576. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67577. return;
  67578. }
  67579. scene.loadingPluginName = plugin.name;
  67580. successHandler(meshes, particleSystems, skeletons, []);
  67581. }
  67582. else {
  67583. var asyncedPlugin = plugin;
  67584. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67585. scene.loadingPluginName = plugin.name;
  67586. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67587. }).catch(function (error) {
  67588. errorHandler(error.message, error);
  67589. });
  67590. }
  67591. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67592. };
  67593. /**
  67594. * Import meshes into a scene
  67595. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67596. * @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)
  67597. * @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)
  67598. * @param scene the instance of BABYLON.Scene to append to
  67599. * @param onProgress a callback with a progress event for each file being loaded
  67600. * @param pluginExtension the extension used to determine the plugin
  67601. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67602. */
  67603. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67604. if (sceneFilename === void 0) { sceneFilename = ""; }
  67605. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67606. if (onProgress === void 0) { onProgress = null; }
  67607. if (pluginExtension === void 0) { pluginExtension = null; }
  67608. return new Promise(function (resolve, reject) {
  67609. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67610. resolve({
  67611. meshes: meshes,
  67612. particleSystems: particleSystems,
  67613. skeletons: skeletons,
  67614. animationGroups: animationGroups
  67615. });
  67616. }, onProgress, function (scene, message, exception) {
  67617. reject(exception || new Error(message));
  67618. }, pluginExtension);
  67619. });
  67620. };
  67621. /**
  67622. * Load a scene
  67623. * @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)
  67624. * @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)
  67625. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67626. * @param onSuccess a callback with the scene when import succeeds
  67627. * @param onProgress a callback with a progress event for each file being loaded
  67628. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67629. * @param pluginExtension the extension used to determine the plugin
  67630. * @returns The loaded plugin
  67631. */
  67632. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67633. if (onSuccess === void 0) { onSuccess = null; }
  67634. if (onProgress === void 0) { onProgress = null; }
  67635. if (onError === void 0) { onError = null; }
  67636. if (pluginExtension === void 0) { pluginExtension = null; }
  67637. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67638. };
  67639. /**
  67640. * Load a scene
  67641. * @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)
  67642. * @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)
  67643. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67644. * @param onProgress a callback with a progress event for each file being loaded
  67645. * @param pluginExtension the extension used to determine the plugin
  67646. * @returns The loaded scene
  67647. */
  67648. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67649. if (onProgress === void 0) { onProgress = null; }
  67650. if (pluginExtension === void 0) { pluginExtension = null; }
  67651. return new Promise(function (resolve, reject) {
  67652. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67653. resolve(scene);
  67654. }, onProgress, function (scene, message, exception) {
  67655. reject(exception || new Error(message));
  67656. }, pluginExtension);
  67657. });
  67658. };
  67659. /**
  67660. * Append a scene
  67661. * @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)
  67662. * @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)
  67663. * @param scene is the instance of BABYLON.Scene to append to
  67664. * @param onSuccess a callback with the scene when import succeeds
  67665. * @param onProgress a callback with a progress event for each file being loaded
  67666. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67667. * @param pluginExtension the extension used to determine the plugin
  67668. * @returns The loaded plugin
  67669. */
  67670. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67671. if (sceneFilename === void 0) { sceneFilename = ""; }
  67672. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67673. if (onSuccess === void 0) { onSuccess = null; }
  67674. if (onProgress === void 0) { onProgress = null; }
  67675. if (onError === void 0) { onError = null; }
  67676. if (pluginExtension === void 0) { pluginExtension = null; }
  67677. if (!scene) {
  67678. BABYLON.Tools.Error("No scene available to append to");
  67679. return null;
  67680. }
  67681. if (!sceneFilename) {
  67682. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67683. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67684. }
  67685. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67686. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67687. return null;
  67688. }
  67689. if (SceneLoader.ShowLoadingScreen) {
  67690. scene.getEngine().displayLoadingUI();
  67691. }
  67692. var loadingToken = {};
  67693. scene._addPendingData(loadingToken);
  67694. var disposeHandler = function () {
  67695. scene._removePendingData(loadingToken);
  67696. scene.getEngine().hideLoadingUI();
  67697. };
  67698. var errorHandler = function (message, exception) {
  67699. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67700. if (onError) {
  67701. onError(scene, errorMessage, exception);
  67702. }
  67703. else {
  67704. BABYLON.Tools.Error(errorMessage);
  67705. // should the exception be thrown?
  67706. }
  67707. disposeHandler();
  67708. };
  67709. var progressHandler = onProgress ? function (event) {
  67710. try {
  67711. onProgress(event);
  67712. }
  67713. catch (e) {
  67714. errorHandler("Error in onProgress callback", e);
  67715. }
  67716. } : undefined;
  67717. var successHandler = function () {
  67718. if (onSuccess) {
  67719. try {
  67720. onSuccess(scene);
  67721. }
  67722. catch (e) {
  67723. errorHandler("Error in onSuccess callback", e);
  67724. }
  67725. }
  67726. scene._removePendingData(loadingToken);
  67727. };
  67728. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67729. if (sceneFilename === "") {
  67730. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67731. }
  67732. if (plugin.load) {
  67733. var syncedPlugin = plugin;
  67734. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67735. return;
  67736. }
  67737. scene.loadingPluginName = plugin.name;
  67738. successHandler();
  67739. }
  67740. else {
  67741. var asyncedPlugin = plugin;
  67742. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67743. scene.loadingPluginName = plugin.name;
  67744. successHandler();
  67745. }).catch(function (error) {
  67746. errorHandler(error.message, error);
  67747. });
  67748. }
  67749. if (SceneLoader.ShowLoadingScreen) {
  67750. scene.executeWhenReady(function () {
  67751. scene.getEngine().hideLoadingUI();
  67752. });
  67753. }
  67754. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67755. };
  67756. /**
  67757. * Append a scene
  67758. * @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)
  67759. * @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)
  67760. * @param scene is the instance of BABYLON.Scene to append to
  67761. * @param onProgress a callback with a progress event for each file being loaded
  67762. * @param pluginExtension the extension used to determine the plugin
  67763. * @returns The given scene
  67764. */
  67765. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67766. if (sceneFilename === void 0) { sceneFilename = ""; }
  67767. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67768. if (onProgress === void 0) { onProgress = null; }
  67769. if (pluginExtension === void 0) { pluginExtension = null; }
  67770. return new Promise(function (resolve, reject) {
  67771. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67772. resolve(scene);
  67773. }, onProgress, function (scene, message, exception) {
  67774. reject(exception || new Error(message));
  67775. }, pluginExtension);
  67776. });
  67777. };
  67778. /**
  67779. * Load a scene into an asset container
  67780. * @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)
  67781. * @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)
  67782. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67783. * @param onSuccess a callback with the scene when import succeeds
  67784. * @param onProgress a callback with a progress event for each file being loaded
  67785. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67786. * @param pluginExtension the extension used to determine the plugin
  67787. * @returns The loaded plugin
  67788. */
  67789. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67790. if (sceneFilename === void 0) { sceneFilename = ""; }
  67791. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67792. if (onSuccess === void 0) { onSuccess = null; }
  67793. if (onProgress === void 0) { onProgress = null; }
  67794. if (onError === void 0) { onError = null; }
  67795. if (pluginExtension === void 0) { pluginExtension = null; }
  67796. if (!scene) {
  67797. BABYLON.Tools.Error("No scene available to load asset container to");
  67798. return null;
  67799. }
  67800. if (!sceneFilename) {
  67801. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67802. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67803. }
  67804. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67805. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67806. return null;
  67807. }
  67808. var loadingToken = {};
  67809. scene._addPendingData(loadingToken);
  67810. var disposeHandler = function () {
  67811. scene._removePendingData(loadingToken);
  67812. };
  67813. var errorHandler = function (message, exception) {
  67814. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67815. if (onError) {
  67816. onError(scene, errorMessage, exception);
  67817. }
  67818. else {
  67819. BABYLON.Tools.Error(errorMessage);
  67820. // should the exception be thrown?
  67821. }
  67822. disposeHandler();
  67823. };
  67824. var progressHandler = onProgress ? function (event) {
  67825. try {
  67826. onProgress(event);
  67827. }
  67828. catch (e) {
  67829. errorHandler("Error in onProgress callback", e);
  67830. }
  67831. } : undefined;
  67832. var successHandler = function (assets) {
  67833. if (onSuccess) {
  67834. try {
  67835. onSuccess(assets);
  67836. }
  67837. catch (e) {
  67838. errorHandler("Error in onSuccess callback", e);
  67839. }
  67840. }
  67841. scene._removePendingData(loadingToken);
  67842. };
  67843. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67844. if (plugin.loadAssetContainer) {
  67845. var syncedPlugin = plugin;
  67846. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67847. if (!assetContainer) {
  67848. return;
  67849. }
  67850. scene.loadingPluginName = plugin.name;
  67851. successHandler(assetContainer);
  67852. }
  67853. else if (plugin.loadAssetContainerAsync) {
  67854. var asyncedPlugin = plugin;
  67855. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67856. scene.loadingPluginName = plugin.name;
  67857. successHandler(assetContainer);
  67858. }).catch(function (error) {
  67859. errorHandler(error.message, error);
  67860. });
  67861. }
  67862. else {
  67863. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67864. }
  67865. if (SceneLoader.ShowLoadingScreen) {
  67866. scene.executeWhenReady(function () {
  67867. scene.getEngine().hideLoadingUI();
  67868. });
  67869. }
  67870. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67871. };
  67872. /**
  67873. * Load a scene into an asset container
  67874. * @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)
  67875. * @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)
  67876. * @param scene is the instance of BABYLON.Scene to append to
  67877. * @param onProgress a callback with a progress event for each file being loaded
  67878. * @param pluginExtension the extension used to determine the plugin
  67879. * @returns The loaded asset container
  67880. */
  67881. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67882. if (sceneFilename === void 0) { sceneFilename = ""; }
  67883. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67884. if (onProgress === void 0) { onProgress = null; }
  67885. if (pluginExtension === void 0) { pluginExtension = null; }
  67886. return new Promise(function (resolve, reject) {
  67887. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67888. resolve(assetContainer);
  67889. }, onProgress, function (scene, message, exception) {
  67890. reject(exception || new Error(message));
  67891. }, pluginExtension);
  67892. });
  67893. };
  67894. // Flags
  67895. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67896. SceneLoader._ShowLoadingScreen = true;
  67897. SceneLoader._CleanBoneMatrixWeights = false;
  67898. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67899. // Members
  67900. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67901. SceneLoader._registeredPlugins = {};
  67902. return SceneLoader;
  67903. }());
  67904. BABYLON.SceneLoader = SceneLoader;
  67905. ;
  67906. })(BABYLON || (BABYLON = {}));
  67907. //# sourceMappingURL=babylon.sceneLoader.js.map
  67908. var BABYLON;
  67909. (function (BABYLON) {
  67910. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67911. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67912. var parsedMaterial = parsedData.materials[index];
  67913. if (parsedMaterial.id === id) {
  67914. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67915. }
  67916. }
  67917. return null;
  67918. };
  67919. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67920. for (var i in names) {
  67921. if (mesh.name === names[i]) {
  67922. hierarchyIds.push(mesh.id);
  67923. return true;
  67924. }
  67925. }
  67926. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67927. hierarchyIds.push(mesh.id);
  67928. return true;
  67929. }
  67930. return false;
  67931. };
  67932. var logOperation = function (operation, producer) {
  67933. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67934. };
  67935. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67936. if (addToScene === void 0) { addToScene = false; }
  67937. var container = new BABYLON.AssetContainer(scene);
  67938. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67939. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67940. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67941. // and avoid problems with multiple concurrent .babylon loads.
  67942. var log = "importScene has failed JSON parse";
  67943. try {
  67944. var parsedData = JSON.parse(data);
  67945. log = "";
  67946. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67947. var index;
  67948. var cache;
  67949. // Lights
  67950. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67951. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67952. var parsedLight = parsedData.lights[index];
  67953. var light = BABYLON.Light.Parse(parsedLight, scene);
  67954. if (light) {
  67955. container.lights.push(light);
  67956. log += (index === 0 ? "\n\tLights:" : "");
  67957. log += "\n\t\t" + light.toString(fullDetails);
  67958. }
  67959. }
  67960. }
  67961. // Animations
  67962. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67963. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67964. var parsedAnimation = parsedData.animations[index];
  67965. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67966. scene.animations.push(animation);
  67967. container.animations.push(animation);
  67968. log += (index === 0 ? "\n\tAnimations:" : "");
  67969. log += "\n\t\t" + animation.toString(fullDetails);
  67970. }
  67971. }
  67972. // Materials
  67973. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67974. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67975. var parsedMaterial = parsedData.materials[index];
  67976. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67977. container.materials.push(mat);
  67978. log += (index === 0 ? "\n\tMaterials:" : "");
  67979. log += "\n\t\t" + mat.toString(fullDetails);
  67980. }
  67981. }
  67982. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67983. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67984. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67985. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67986. container.multiMaterials.push(mmat);
  67987. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67988. log += "\n\t\t" + mmat.toString(fullDetails);
  67989. }
  67990. }
  67991. // Morph targets
  67992. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67993. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67994. var managerData = _a[_i];
  67995. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67996. }
  67997. }
  67998. // Skeletons
  67999. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68000. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68001. var parsedSkeleton = parsedData.skeletons[index];
  68002. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68003. container.skeletons.push(skeleton);
  68004. log += (index === 0 ? "\n\tSkeletons:" : "");
  68005. log += "\n\t\t" + skeleton.toString(fullDetails);
  68006. }
  68007. }
  68008. // Geometries
  68009. var geometries = parsedData.geometries;
  68010. if (geometries !== undefined && geometries !== null) {
  68011. var addedGeometry = new Array();
  68012. // Boxes
  68013. var boxes = geometries.boxes;
  68014. if (boxes !== undefined && boxes !== null) {
  68015. for (index = 0, cache = boxes.length; index < cache; index++) {
  68016. var parsedBox = boxes[index];
  68017. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68018. }
  68019. }
  68020. // Spheres
  68021. var spheres = geometries.spheres;
  68022. if (spheres !== undefined && spheres !== null) {
  68023. for (index = 0, cache = spheres.length; index < cache; index++) {
  68024. var parsedSphere = spheres[index];
  68025. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68026. }
  68027. }
  68028. // Cylinders
  68029. var cylinders = geometries.cylinders;
  68030. if (cylinders !== undefined && cylinders !== null) {
  68031. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68032. var parsedCylinder = cylinders[index];
  68033. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68034. }
  68035. }
  68036. // Toruses
  68037. var toruses = geometries.toruses;
  68038. if (toruses !== undefined && toruses !== null) {
  68039. for (index = 0, cache = toruses.length; index < cache; index++) {
  68040. var parsedTorus = toruses[index];
  68041. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68042. }
  68043. }
  68044. // Grounds
  68045. var grounds = geometries.grounds;
  68046. if (grounds !== undefined && grounds !== null) {
  68047. for (index = 0, cache = grounds.length; index < cache; index++) {
  68048. var parsedGround = grounds[index];
  68049. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68050. }
  68051. }
  68052. // Planes
  68053. var planes = geometries.planes;
  68054. if (planes !== undefined && planes !== null) {
  68055. for (index = 0, cache = planes.length; index < cache; index++) {
  68056. var parsedPlane = planes[index];
  68057. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68058. }
  68059. }
  68060. // TorusKnots
  68061. var torusKnots = geometries.torusKnots;
  68062. if (torusKnots !== undefined && torusKnots !== null) {
  68063. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68064. var parsedTorusKnot = torusKnots[index];
  68065. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68066. }
  68067. }
  68068. // VertexData
  68069. var vertexData = geometries.vertexData;
  68070. if (vertexData !== undefined && vertexData !== null) {
  68071. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68072. var parsedVertexData = vertexData[index];
  68073. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68074. }
  68075. }
  68076. addedGeometry.forEach(function (g) {
  68077. if (g) {
  68078. container.geometries.push(g);
  68079. }
  68080. });
  68081. }
  68082. // Transform nodes
  68083. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68084. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68085. var parsedTransformNode = parsedData.transformNodes[index];
  68086. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68087. container.transformNodes.push(node);
  68088. }
  68089. }
  68090. // Meshes
  68091. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68092. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68093. var parsedMesh = parsedData.meshes[index];
  68094. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68095. container.meshes.push(mesh);
  68096. log += (index === 0 ? "\n\tMeshes:" : "");
  68097. log += "\n\t\t" + mesh.toString(fullDetails);
  68098. }
  68099. }
  68100. // Cameras
  68101. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68102. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68103. var parsedCamera = parsedData.cameras[index];
  68104. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68105. container.cameras.push(camera);
  68106. log += (index === 0 ? "\n\tCameras:" : "");
  68107. log += "\n\t\t" + camera.toString(fullDetails);
  68108. }
  68109. }
  68110. // Browsing all the graph to connect the dots
  68111. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68112. var camera = scene.cameras[index];
  68113. if (camera._waitingParentId) {
  68114. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68115. camera._waitingParentId = null;
  68116. }
  68117. }
  68118. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68119. var light_1 = scene.lights[index];
  68120. if (light_1 && light_1._waitingParentId) {
  68121. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68122. light_1._waitingParentId = null;
  68123. }
  68124. }
  68125. // Sounds
  68126. // TODO: add sound
  68127. var loadedSounds = [];
  68128. var loadedSound;
  68129. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68130. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68131. var parsedSound = parsedData.sounds[index];
  68132. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68133. if (!parsedSound.url)
  68134. parsedSound.url = parsedSound.name;
  68135. if (!loadedSounds[parsedSound.url]) {
  68136. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68137. loadedSounds[parsedSound.url] = loadedSound;
  68138. container.sounds.push(loadedSound);
  68139. }
  68140. else {
  68141. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68142. }
  68143. }
  68144. else {
  68145. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68146. }
  68147. }
  68148. }
  68149. loadedSounds = [];
  68150. // Connect parents & children and parse actions
  68151. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68152. var transformNode = scene.transformNodes[index];
  68153. if (transformNode._waitingParentId) {
  68154. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68155. transformNode._waitingParentId = null;
  68156. }
  68157. }
  68158. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68159. var mesh = scene.meshes[index];
  68160. if (mesh._waitingParentId) {
  68161. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68162. mesh._waitingParentId = null;
  68163. }
  68164. if (mesh._waitingActions) {
  68165. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68166. mesh._waitingActions = null;
  68167. }
  68168. }
  68169. // freeze world matrix application
  68170. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68171. var currentMesh = scene.meshes[index];
  68172. if (currentMesh._waitingFreezeWorldMatrix) {
  68173. currentMesh.freezeWorldMatrix();
  68174. currentMesh._waitingFreezeWorldMatrix = null;
  68175. }
  68176. else {
  68177. currentMesh.computeWorldMatrix(true);
  68178. }
  68179. }
  68180. // Particles Systems
  68181. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68182. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68183. var parsedParticleSystem = parsedData.particleSystems[index];
  68184. if (parsedParticleSystem.activeParticleCount) {
  68185. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68186. container.particleSystems.push(ps);
  68187. }
  68188. else {
  68189. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68190. container.particleSystems.push(ps);
  68191. }
  68192. }
  68193. }
  68194. // Lens flares
  68195. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68196. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68197. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68198. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68199. container.lensFlareSystems.push(lf);
  68200. }
  68201. }
  68202. // Shadows
  68203. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68204. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68205. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68206. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68207. container.shadowGenerators.push(sg);
  68208. }
  68209. }
  68210. // Lights exclusions / inclusions
  68211. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68212. var light_2 = scene.lights[index];
  68213. // Excluded check
  68214. if (light_2._excludedMeshesIds.length > 0) {
  68215. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68216. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68217. if (excludedMesh) {
  68218. light_2.excludedMeshes.push(excludedMesh);
  68219. }
  68220. }
  68221. light_2._excludedMeshesIds = [];
  68222. }
  68223. // Included check
  68224. if (light_2._includedOnlyMeshesIds.length > 0) {
  68225. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68226. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68227. if (includedOnlyMesh) {
  68228. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68229. }
  68230. }
  68231. light_2._includedOnlyMeshesIds = [];
  68232. }
  68233. }
  68234. // Effect layers
  68235. if (parsedData.effectLayers) {
  68236. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68237. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68238. container.effectLayers.push(effectLayer);
  68239. }
  68240. }
  68241. // Actions (scene)
  68242. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68243. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68244. }
  68245. if (!addToScene) {
  68246. container.removeAllFromScene();
  68247. }
  68248. }
  68249. catch (err) {
  68250. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68251. if (onError) {
  68252. onError(msg, err);
  68253. }
  68254. else {
  68255. BABYLON.Tools.Log(msg);
  68256. throw err;
  68257. }
  68258. }
  68259. finally {
  68260. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68261. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68262. }
  68263. }
  68264. return container;
  68265. };
  68266. BABYLON.SceneLoader.RegisterPlugin({
  68267. name: "babylon.js",
  68268. extensions: ".babylon",
  68269. canDirectLoad: function (data) {
  68270. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68271. return true;
  68272. }
  68273. return false;
  68274. },
  68275. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68276. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68277. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68278. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68279. // and avoid problems with multiple concurrent .babylon loads.
  68280. var log = "importMesh has failed JSON parse";
  68281. try {
  68282. var parsedData = JSON.parse(data);
  68283. log = "";
  68284. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68285. if (!meshesNames) {
  68286. meshesNames = null;
  68287. }
  68288. else if (!Array.isArray(meshesNames)) {
  68289. meshesNames = [meshesNames];
  68290. }
  68291. var hierarchyIds = new Array();
  68292. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68293. var loadedSkeletonsIds = [];
  68294. var loadedMaterialsIds = [];
  68295. var index;
  68296. var cache;
  68297. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68298. var parsedMesh = parsedData.meshes[index];
  68299. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68300. if (meshesNames !== null) {
  68301. // Remove found mesh name from list.
  68302. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68303. }
  68304. //Geometry?
  68305. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68306. //does the file contain geometries?
  68307. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68308. //find the correct geometry and add it to the scene
  68309. var found = false;
  68310. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68311. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68312. return;
  68313. }
  68314. else {
  68315. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68316. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68317. switch (geometryType) {
  68318. case "boxes":
  68319. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68320. break;
  68321. case "spheres":
  68322. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68323. break;
  68324. case "cylinders":
  68325. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68326. break;
  68327. case "toruses":
  68328. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68329. break;
  68330. case "grounds":
  68331. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68332. break;
  68333. case "planes":
  68334. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68335. break;
  68336. case "torusKnots":
  68337. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68338. break;
  68339. case "vertexData":
  68340. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68341. break;
  68342. }
  68343. found = true;
  68344. }
  68345. });
  68346. }
  68347. });
  68348. if (found === false) {
  68349. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68350. }
  68351. }
  68352. }
  68353. // Material ?
  68354. if (parsedMesh.materialId) {
  68355. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68356. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68357. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68358. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68359. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68360. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68361. var subMatId = parsedMultiMaterial.materials[matIndex];
  68362. loadedMaterialsIds.push(subMatId);
  68363. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68364. if (mat) {
  68365. log += "\n\tMaterial " + mat.toString(fullDetails);
  68366. }
  68367. }
  68368. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68369. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68370. if (mmat) {
  68371. materialFound = true;
  68372. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68373. }
  68374. break;
  68375. }
  68376. }
  68377. }
  68378. if (materialFound === false) {
  68379. loadedMaterialsIds.push(parsedMesh.materialId);
  68380. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68381. if (!mat) {
  68382. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68383. }
  68384. else {
  68385. log += "\n\tMaterial " + mat.toString(fullDetails);
  68386. }
  68387. }
  68388. }
  68389. // Skeleton ?
  68390. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68391. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68392. if (skeletonAlreadyLoaded === false) {
  68393. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68394. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68395. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68396. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68397. skeletons.push(skeleton);
  68398. loadedSkeletonsIds.push(parsedSkeleton.id);
  68399. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68400. }
  68401. }
  68402. }
  68403. }
  68404. // Morph targets ?
  68405. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68406. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68407. var managerData = _a[_i];
  68408. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68409. }
  68410. }
  68411. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68412. meshes.push(mesh);
  68413. log += "\n\tMesh " + mesh.toString(fullDetails);
  68414. }
  68415. }
  68416. // Connecting parents
  68417. var currentMesh;
  68418. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68419. currentMesh = scene.meshes[index];
  68420. if (currentMesh._waitingParentId) {
  68421. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68422. currentMesh._waitingParentId = null;
  68423. }
  68424. }
  68425. // freeze and compute world matrix application
  68426. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68427. currentMesh = scene.meshes[index];
  68428. if (currentMesh._waitingFreezeWorldMatrix) {
  68429. currentMesh.freezeWorldMatrix();
  68430. currentMesh._waitingFreezeWorldMatrix = null;
  68431. }
  68432. else {
  68433. currentMesh.computeWorldMatrix(true);
  68434. }
  68435. }
  68436. }
  68437. // Particles
  68438. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68439. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68440. var parsedParticleSystem = parsedData.particleSystems[index];
  68441. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68442. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68443. }
  68444. }
  68445. }
  68446. return true;
  68447. }
  68448. catch (err) {
  68449. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68450. if (onError) {
  68451. onError(msg, err);
  68452. }
  68453. else {
  68454. BABYLON.Tools.Log(msg);
  68455. throw err;
  68456. }
  68457. }
  68458. finally {
  68459. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68460. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68461. }
  68462. }
  68463. return false;
  68464. },
  68465. load: function (scene, data, rootUrl, onError) {
  68466. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68467. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68468. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68469. // and avoid problems with multiple concurrent .babylon loads.
  68470. var log = "importScene has failed JSON parse";
  68471. try {
  68472. var parsedData = JSON.parse(data);
  68473. log = "";
  68474. // Scene
  68475. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68476. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68477. }
  68478. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68479. scene.autoClear = parsedData.autoClear;
  68480. }
  68481. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68482. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68483. }
  68484. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68485. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68486. }
  68487. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68488. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68489. }
  68490. // Fog
  68491. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68492. scene.fogMode = parsedData.fogMode;
  68493. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68494. scene.fogStart = parsedData.fogStart;
  68495. scene.fogEnd = parsedData.fogEnd;
  68496. scene.fogDensity = parsedData.fogDensity;
  68497. log += "\tFog mode for scene: ";
  68498. switch (scene.fogMode) {
  68499. // getters not compiling, so using hardcoded
  68500. case 1:
  68501. log += "exp\n";
  68502. break;
  68503. case 2:
  68504. log += "exp2\n";
  68505. break;
  68506. case 3:
  68507. log += "linear\n";
  68508. break;
  68509. }
  68510. }
  68511. //Physics
  68512. if (parsedData.physicsEnabled) {
  68513. var physicsPlugin;
  68514. if (parsedData.physicsEngine === "cannon") {
  68515. physicsPlugin = new BABYLON.CannonJSPlugin();
  68516. }
  68517. else if (parsedData.physicsEngine === "oimo") {
  68518. physicsPlugin = new BABYLON.OimoJSPlugin();
  68519. }
  68520. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68521. //else - default engine, which is currently oimo
  68522. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68523. scene.enablePhysics(physicsGravity, physicsPlugin);
  68524. }
  68525. // Metadata
  68526. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68527. scene.metadata = parsedData.metadata;
  68528. }
  68529. //collisions, if defined. otherwise, default is true
  68530. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68531. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68532. }
  68533. scene.workerCollisions = !!parsedData.workerCollisions;
  68534. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68535. if (!container) {
  68536. return false;
  68537. }
  68538. if (parsedData.autoAnimate) {
  68539. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68540. }
  68541. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68542. scene.setActiveCameraByID(parsedData.activeCameraID);
  68543. }
  68544. // Environment texture
  68545. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68546. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68547. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68548. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68549. if (parsedData.environmentTextureRotationY) {
  68550. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68551. }
  68552. scene.environmentTexture = hdrTexture;
  68553. }
  68554. else {
  68555. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68556. if (parsedData.environmentTextureRotationY) {
  68557. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68558. }
  68559. scene.environmentTexture = cubeTexture;
  68560. }
  68561. if (parsedData.createDefaultSkybox === true) {
  68562. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68563. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68564. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68565. }
  68566. }
  68567. // Finish
  68568. return true;
  68569. }
  68570. catch (err) {
  68571. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68572. if (onError) {
  68573. onError(msg, err);
  68574. }
  68575. else {
  68576. BABYLON.Tools.Log(msg);
  68577. throw err;
  68578. }
  68579. }
  68580. finally {
  68581. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68582. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68583. }
  68584. }
  68585. return false;
  68586. },
  68587. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68588. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68589. return container;
  68590. }
  68591. });
  68592. })(BABYLON || (BABYLON = {}));
  68593. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68594. var BABYLON;
  68595. (function (BABYLON) {
  68596. var FilesInput = /** @class */ (function () {
  68597. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68598. this.onProcessFileCallback = function () { return true; };
  68599. this._engine = engine;
  68600. this._currentScene = scene;
  68601. this._sceneLoadedCallback = sceneLoadedCallback;
  68602. this._progressCallback = progressCallback;
  68603. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68604. this._textureLoadingCallback = textureLoadingCallback;
  68605. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68606. this._onReloadCallback = onReloadCallback;
  68607. this._errorCallback = errorCallback;
  68608. }
  68609. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68610. var _this = this;
  68611. if (elementToMonitor) {
  68612. this._elementToMonitor = elementToMonitor;
  68613. this._dragEnterHandler = function (e) { _this.drag(e); };
  68614. this._dragOverHandler = function (e) { _this.drag(e); };
  68615. this._dropHandler = function (e) { _this.drop(e); };
  68616. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68617. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68618. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68619. }
  68620. };
  68621. FilesInput.prototype.dispose = function () {
  68622. if (!this._elementToMonitor) {
  68623. return;
  68624. }
  68625. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68626. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68627. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68628. };
  68629. FilesInput.prototype.renderFunction = function () {
  68630. if (this._additionalRenderLoopLogicCallback) {
  68631. this._additionalRenderLoopLogicCallback();
  68632. }
  68633. if (this._currentScene) {
  68634. if (this._textureLoadingCallback) {
  68635. var remaining = this._currentScene.getWaitingItemsCount();
  68636. if (remaining > 0) {
  68637. this._textureLoadingCallback(remaining);
  68638. }
  68639. }
  68640. this._currentScene.render();
  68641. }
  68642. };
  68643. FilesInput.prototype.drag = function (e) {
  68644. e.stopPropagation();
  68645. e.preventDefault();
  68646. };
  68647. FilesInput.prototype.drop = function (eventDrop) {
  68648. eventDrop.stopPropagation();
  68649. eventDrop.preventDefault();
  68650. this.loadFiles(eventDrop);
  68651. };
  68652. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68653. var _this = this;
  68654. var reader = folder.createReader();
  68655. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68656. reader.readEntries(function (entries) {
  68657. remaining.count += entries.length;
  68658. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68659. var entry = entries_1[_i];
  68660. if (entry.isFile) {
  68661. entry.file(function (file) {
  68662. file.correctName = relativePath + file.name;
  68663. files.push(file);
  68664. if (--remaining.count === 0) {
  68665. callback();
  68666. }
  68667. });
  68668. }
  68669. else if (entry.isDirectory) {
  68670. _this._traverseFolder(entry, files, remaining, callback);
  68671. }
  68672. }
  68673. if (--remaining.count) {
  68674. callback();
  68675. }
  68676. });
  68677. };
  68678. FilesInput.prototype._processFiles = function (files) {
  68679. for (var i = 0; i < files.length; i++) {
  68680. var name = files[i].correctName.toLowerCase();
  68681. var extension = name.split('.').pop();
  68682. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68683. continue;
  68684. }
  68685. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68686. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68687. this._sceneFileToLoad = files[i];
  68688. }
  68689. else {
  68690. FilesInput.FilesToLoad[name] = files[i];
  68691. }
  68692. }
  68693. };
  68694. FilesInput.prototype.loadFiles = function (event) {
  68695. var _this = this;
  68696. if (this._startingProcessingFilesCallback)
  68697. this._startingProcessingFilesCallback();
  68698. // Handling data transfer via drag'n'drop
  68699. if (event && event.dataTransfer && event.dataTransfer.files) {
  68700. this._filesToLoad = event.dataTransfer.files;
  68701. }
  68702. // Handling files from input files
  68703. if (event && event.target && event.target.files) {
  68704. this._filesToLoad = event.target.files;
  68705. }
  68706. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68707. var files_1 = new Array();
  68708. var folders = [];
  68709. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68710. for (var i = 0; i < this._filesToLoad.length; i++) {
  68711. var fileToLoad = this._filesToLoad[i];
  68712. var name_1 = fileToLoad.name.toLowerCase();
  68713. var entry = void 0;
  68714. fileToLoad.correctName = name_1;
  68715. if (items) {
  68716. var item = items[i];
  68717. if (item.getAsEntry) {
  68718. entry = item.getAsEntry();
  68719. }
  68720. else if (item.webkitGetAsEntry) {
  68721. entry = item.webkitGetAsEntry();
  68722. }
  68723. }
  68724. if (!entry) {
  68725. files_1.push(fileToLoad);
  68726. }
  68727. else {
  68728. if (entry.isDirectory) {
  68729. folders.push(entry);
  68730. }
  68731. else {
  68732. files_1.push(fileToLoad);
  68733. }
  68734. }
  68735. }
  68736. if (folders.length === 0) {
  68737. this._processFiles(files_1);
  68738. this._processReload();
  68739. }
  68740. else {
  68741. var remaining = { count: folders.length };
  68742. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68743. var folder = folders_1[_i];
  68744. this._traverseFolder(folder, files_1, remaining, function () {
  68745. _this._processFiles(files_1);
  68746. if (remaining.count === 0) {
  68747. _this._processReload();
  68748. }
  68749. });
  68750. }
  68751. }
  68752. }
  68753. };
  68754. FilesInput.prototype._processReload = function () {
  68755. if (this._onReloadCallback) {
  68756. this._onReloadCallback(this._sceneFileToLoad);
  68757. }
  68758. else {
  68759. this.reload();
  68760. }
  68761. };
  68762. FilesInput.prototype.reload = function () {
  68763. var _this = this;
  68764. // If a scene file has been provided
  68765. if (this._sceneFileToLoad) {
  68766. if (this._currentScene) {
  68767. if (BABYLON.Tools.errorsCount > 0) {
  68768. BABYLON.Tools.ClearLogCache();
  68769. }
  68770. this._engine.stopRenderLoop();
  68771. }
  68772. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68773. if (_this._progressCallback) {
  68774. _this._progressCallback(progress);
  68775. }
  68776. }).then(function (scene) {
  68777. if (_this._currentScene) {
  68778. _this._currentScene.dispose();
  68779. }
  68780. _this._currentScene = scene;
  68781. if (_this._sceneLoadedCallback) {
  68782. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68783. }
  68784. // Wait for textures and shaders to be ready
  68785. _this._currentScene.executeWhenReady(function () {
  68786. _this._engine.runRenderLoop(function () {
  68787. _this.renderFunction();
  68788. });
  68789. });
  68790. }).catch(function (error) {
  68791. if (_this._errorCallback) {
  68792. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68793. }
  68794. });
  68795. }
  68796. else {
  68797. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68798. }
  68799. };
  68800. FilesInput.FilesToLoad = {};
  68801. return FilesInput;
  68802. }());
  68803. BABYLON.FilesInput = FilesInput;
  68804. })(BABYLON || (BABYLON = {}));
  68805. //# sourceMappingURL=babylon.filesInput.js.map
  68806. var BABYLON;
  68807. (function (BABYLON) {
  68808. /**
  68809. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68810. * The underlying implementation relies on an associative array to ensure the best performances.
  68811. * The value can be anything including 'null' but except 'undefined'
  68812. */
  68813. var StringDictionary = /** @class */ (function () {
  68814. function StringDictionary() {
  68815. this._count = 0;
  68816. this._data = {};
  68817. }
  68818. /**
  68819. * This will clear this dictionary and copy the content from the 'source' one.
  68820. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68821. * @param source the dictionary to take the content from and copy to this dictionary
  68822. */
  68823. StringDictionary.prototype.copyFrom = function (source) {
  68824. var _this = this;
  68825. this.clear();
  68826. source.forEach(function (t, v) { return _this.add(t, v); });
  68827. };
  68828. /**
  68829. * Get a value based from its key
  68830. * @param key the given key to get the matching value from
  68831. * @return the value if found, otherwise undefined is returned
  68832. */
  68833. StringDictionary.prototype.get = function (key) {
  68834. var val = this._data[key];
  68835. if (val !== undefined) {
  68836. return val;
  68837. }
  68838. return undefined;
  68839. };
  68840. /**
  68841. * Get a value from its key or add it if it doesn't exist.
  68842. * This method will ensure you that a given key/data will be present in the dictionary.
  68843. * @param key the given key to get the matching value from
  68844. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68845. * The factory will only be invoked if there's no data for the given key.
  68846. * @return the value corresponding to the key.
  68847. */
  68848. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68849. var val = this.get(key);
  68850. if (val !== undefined) {
  68851. return val;
  68852. }
  68853. val = factory(key);
  68854. if (val) {
  68855. this.add(key, val);
  68856. }
  68857. return val;
  68858. };
  68859. /**
  68860. * Get a value from its key if present in the dictionary otherwise add it
  68861. * @param key the key to get the value from
  68862. * @param val if there's no such key/value pair in the dictionary add it with this value
  68863. * @return the value corresponding to the key
  68864. */
  68865. StringDictionary.prototype.getOrAdd = function (key, val) {
  68866. var curVal = this.get(key);
  68867. if (curVal !== undefined) {
  68868. return curVal;
  68869. }
  68870. this.add(key, val);
  68871. return val;
  68872. };
  68873. /**
  68874. * Check if there's a given key in the dictionary
  68875. * @param key the key to check for
  68876. * @return true if the key is present, false otherwise
  68877. */
  68878. StringDictionary.prototype.contains = function (key) {
  68879. return this._data[key] !== undefined;
  68880. };
  68881. /**
  68882. * Add a new key and its corresponding value
  68883. * @param key the key to add
  68884. * @param value the value corresponding to the key
  68885. * @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
  68886. */
  68887. StringDictionary.prototype.add = function (key, value) {
  68888. if (this._data[key] !== undefined) {
  68889. return false;
  68890. }
  68891. this._data[key] = value;
  68892. ++this._count;
  68893. return true;
  68894. };
  68895. StringDictionary.prototype.set = function (key, value) {
  68896. if (this._data[key] === undefined) {
  68897. return false;
  68898. }
  68899. this._data[key] = value;
  68900. return true;
  68901. };
  68902. /**
  68903. * Get the element of the given key and remove it from the dictionary
  68904. * @param key
  68905. */
  68906. StringDictionary.prototype.getAndRemove = function (key) {
  68907. var val = this.get(key);
  68908. if (val !== undefined) {
  68909. delete this._data[key];
  68910. --this._count;
  68911. return val;
  68912. }
  68913. return null;
  68914. };
  68915. /**
  68916. * Remove a key/value from the dictionary.
  68917. * @param key the key to remove
  68918. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68919. */
  68920. StringDictionary.prototype.remove = function (key) {
  68921. if (this.contains(key)) {
  68922. delete this._data[key];
  68923. --this._count;
  68924. return true;
  68925. }
  68926. return false;
  68927. };
  68928. /**
  68929. * Clear the whole content of the dictionary
  68930. */
  68931. StringDictionary.prototype.clear = function () {
  68932. this._data = {};
  68933. this._count = 0;
  68934. };
  68935. Object.defineProperty(StringDictionary.prototype, "count", {
  68936. get: function () {
  68937. return this._count;
  68938. },
  68939. enumerable: true,
  68940. configurable: true
  68941. });
  68942. /**
  68943. * Execute a callback on each key/val of the dictionary.
  68944. * Note that you can remove any element in this dictionary in the callback implementation
  68945. * @param callback the callback to execute on a given key/value pair
  68946. */
  68947. StringDictionary.prototype.forEach = function (callback) {
  68948. for (var cur in this._data) {
  68949. var val = this._data[cur];
  68950. callback(cur, val);
  68951. }
  68952. };
  68953. /**
  68954. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68955. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68956. * Note that you can remove any element in this dictionary in the callback implementation
  68957. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68958. */
  68959. StringDictionary.prototype.first = function (callback) {
  68960. for (var cur in this._data) {
  68961. var val = this._data[cur];
  68962. var res = callback(cur, val);
  68963. if (res) {
  68964. return res;
  68965. }
  68966. }
  68967. return null;
  68968. };
  68969. return StringDictionary;
  68970. }());
  68971. BABYLON.StringDictionary = StringDictionary;
  68972. })(BABYLON || (BABYLON = {}));
  68973. //# sourceMappingURL=babylon.stringDictionary.js.map
  68974. var BABYLON;
  68975. (function (BABYLON) {
  68976. var Tags = /** @class */ (function () {
  68977. function Tags() {
  68978. }
  68979. Tags.EnableFor = function (obj) {
  68980. obj._tags = obj._tags || {};
  68981. obj.hasTags = function () {
  68982. return Tags.HasTags(obj);
  68983. };
  68984. obj.addTags = function (tagsString) {
  68985. return Tags.AddTagsTo(obj, tagsString);
  68986. };
  68987. obj.removeTags = function (tagsString) {
  68988. return Tags.RemoveTagsFrom(obj, tagsString);
  68989. };
  68990. obj.matchesTagsQuery = function (tagsQuery) {
  68991. return Tags.MatchesQuery(obj, tagsQuery);
  68992. };
  68993. };
  68994. Tags.DisableFor = function (obj) {
  68995. delete obj._tags;
  68996. delete obj.hasTags;
  68997. delete obj.addTags;
  68998. delete obj.removeTags;
  68999. delete obj.matchesTagsQuery;
  69000. };
  69001. Tags.HasTags = function (obj) {
  69002. if (!obj._tags) {
  69003. return false;
  69004. }
  69005. return !BABYLON.Tools.IsEmpty(obj._tags);
  69006. };
  69007. Tags.GetTags = function (obj, asString) {
  69008. if (asString === void 0) { asString = true; }
  69009. if (!obj._tags) {
  69010. return null;
  69011. }
  69012. if (asString) {
  69013. var tagsArray = [];
  69014. for (var tag in obj._tags) {
  69015. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69016. tagsArray.push(tag);
  69017. }
  69018. }
  69019. return tagsArray.join(" ");
  69020. }
  69021. else {
  69022. return obj._tags;
  69023. }
  69024. };
  69025. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69026. // a tag cannot start with '||', '&&', and '!'
  69027. // it cannot contain whitespaces
  69028. Tags.AddTagsTo = function (obj, tagsString) {
  69029. if (!tagsString) {
  69030. return;
  69031. }
  69032. if (typeof tagsString !== "string") {
  69033. return;
  69034. }
  69035. var tags = tagsString.split(" ");
  69036. tags.forEach(function (tag, index, array) {
  69037. Tags._AddTagTo(obj, tag);
  69038. });
  69039. };
  69040. Tags._AddTagTo = function (obj, tag) {
  69041. tag = tag.trim();
  69042. if (tag === "" || tag === "true" || tag === "false") {
  69043. return;
  69044. }
  69045. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69046. return;
  69047. }
  69048. Tags.EnableFor(obj);
  69049. obj._tags[tag] = true;
  69050. };
  69051. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69052. if (!Tags.HasTags(obj)) {
  69053. return;
  69054. }
  69055. var tags = tagsString.split(" ");
  69056. for (var t in tags) {
  69057. Tags._RemoveTagFrom(obj, tags[t]);
  69058. }
  69059. };
  69060. Tags._RemoveTagFrom = function (obj, tag) {
  69061. delete obj._tags[tag];
  69062. };
  69063. Tags.MatchesQuery = function (obj, tagsQuery) {
  69064. if (tagsQuery === undefined) {
  69065. return true;
  69066. }
  69067. if (tagsQuery === "") {
  69068. return Tags.HasTags(obj);
  69069. }
  69070. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69071. };
  69072. return Tags;
  69073. }());
  69074. BABYLON.Tags = Tags;
  69075. })(BABYLON || (BABYLON = {}));
  69076. //# sourceMappingURL=babylon.tags.js.map
  69077. var BABYLON;
  69078. (function (BABYLON) {
  69079. /**
  69080. * Class used to evalaute queries containing `and` and `or` operators
  69081. */
  69082. var AndOrNotEvaluator = /** @class */ (function () {
  69083. function AndOrNotEvaluator() {
  69084. }
  69085. /**
  69086. * Evaluate a query
  69087. * @param query defines the query to evaluate
  69088. * @param evaluateCallback defines the callback used to filter result
  69089. * @returns true if the query matches
  69090. */
  69091. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69092. if (!query.match(/\([^\(\)]*\)/g)) {
  69093. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69094. }
  69095. else {
  69096. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69097. // remove parenthesis
  69098. r = r.slice(1, r.length - 1);
  69099. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69100. });
  69101. }
  69102. if (query === "true") {
  69103. return true;
  69104. }
  69105. if (query === "false") {
  69106. return false;
  69107. }
  69108. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69109. };
  69110. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69111. evaluateCallback = evaluateCallback || (function (r) {
  69112. return r === "true" ? true : false;
  69113. });
  69114. var result;
  69115. var or = parenthesisContent.split("||");
  69116. for (var i in or) {
  69117. if (or.hasOwnProperty(i)) {
  69118. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69119. var and = ori.split("&&");
  69120. if (and.length > 1) {
  69121. for (var j = 0; j < and.length; ++j) {
  69122. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69123. if (andj !== "true" && andj !== "false") {
  69124. if (andj[0] === "!") {
  69125. result = !evaluateCallback(andj.substring(1));
  69126. }
  69127. else {
  69128. result = evaluateCallback(andj);
  69129. }
  69130. }
  69131. else {
  69132. result = andj === "true" ? true : false;
  69133. }
  69134. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69135. ori = "false";
  69136. break;
  69137. }
  69138. }
  69139. }
  69140. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69141. result = true;
  69142. break;
  69143. }
  69144. // result equals false (or undefined)
  69145. if (ori !== "true" && ori !== "false") {
  69146. if (ori[0] === "!") {
  69147. result = !evaluateCallback(ori.substring(1));
  69148. }
  69149. else {
  69150. result = evaluateCallback(ori);
  69151. }
  69152. }
  69153. else {
  69154. result = ori === "true" ? true : false;
  69155. }
  69156. }
  69157. }
  69158. // the whole parenthesis scope is replaced by 'true' or 'false'
  69159. return result ? "true" : "false";
  69160. };
  69161. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69162. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69163. // remove whitespaces
  69164. r = r.replace(/[\s]/g, function () { return ""; });
  69165. return r.length % 2 ? "!" : "";
  69166. });
  69167. booleanString = booleanString.trim();
  69168. if (booleanString === "!true") {
  69169. booleanString = "false";
  69170. }
  69171. else if (booleanString === "!false") {
  69172. booleanString = "true";
  69173. }
  69174. return booleanString;
  69175. };
  69176. return AndOrNotEvaluator;
  69177. }());
  69178. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69179. })(BABYLON || (BABYLON = {}));
  69180. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69181. var BABYLON;
  69182. (function (BABYLON) {
  69183. /**
  69184. * Class used to enable access to IndexedDB
  69185. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69186. */
  69187. var Database = /** @class */ (function () {
  69188. /**
  69189. * Creates a new Database
  69190. * @param urlToScene defines the url to load the scene
  69191. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69192. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69193. */
  69194. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69195. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69196. var _this = this;
  69197. // Handling various flavors of prefixed version of IndexedDB
  69198. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69199. this.callbackManifestChecked = callbackManifestChecked;
  69200. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69201. this.db = null;
  69202. this._enableSceneOffline = false;
  69203. this._enableTexturesOffline = false;
  69204. this.manifestVersionFound = 0;
  69205. this.mustUpdateRessources = false;
  69206. this.hasReachedQuota = false;
  69207. if (!Database.IDBStorageEnabled) {
  69208. this.callbackManifestChecked(true);
  69209. }
  69210. else {
  69211. if (disableManifestCheck) {
  69212. this._enableSceneOffline = true;
  69213. this._enableTexturesOffline = true;
  69214. this.manifestVersionFound = 1;
  69215. BABYLON.Tools.SetImmediate(function () {
  69216. _this.callbackManifestChecked(true);
  69217. });
  69218. }
  69219. else {
  69220. this._checkManifestFile();
  69221. }
  69222. }
  69223. }
  69224. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69225. /**
  69226. * Gets a boolean indicating if scene must be saved in the database
  69227. */
  69228. get: function () {
  69229. return this._enableSceneOffline;
  69230. },
  69231. enumerable: true,
  69232. configurable: true
  69233. });
  69234. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69235. /**
  69236. * Gets a boolean indicating if textures must be saved in the database
  69237. */
  69238. get: function () {
  69239. return this._enableTexturesOffline;
  69240. },
  69241. enumerable: true,
  69242. configurable: true
  69243. });
  69244. Database.prototype._checkManifestFile = function () {
  69245. var _this = this;
  69246. var noManifestFile = function () {
  69247. _this._enableSceneOffline = false;
  69248. _this._enableTexturesOffline = false;
  69249. _this.callbackManifestChecked(false);
  69250. };
  69251. var timeStampUsed = false;
  69252. var manifestURL = this.currentSceneUrl + ".manifest";
  69253. var xhr = new XMLHttpRequest();
  69254. if (navigator.onLine) {
  69255. // Adding a timestamp to by-pass browsers' cache
  69256. timeStampUsed = true;
  69257. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69258. }
  69259. xhr.open("GET", manifestURL, true);
  69260. xhr.addEventListener("load", function () {
  69261. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69262. try {
  69263. var manifestFile = JSON.parse(xhr.response);
  69264. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69265. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69266. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69267. _this.manifestVersionFound = manifestFile.version;
  69268. }
  69269. if (_this.callbackManifestChecked) {
  69270. _this.callbackManifestChecked(true);
  69271. }
  69272. }
  69273. catch (ex) {
  69274. noManifestFile();
  69275. }
  69276. }
  69277. else {
  69278. noManifestFile();
  69279. }
  69280. }, false);
  69281. xhr.addEventListener("error", function (event) {
  69282. if (timeStampUsed) {
  69283. timeStampUsed = false;
  69284. // Let's retry without the timeStamp
  69285. // It could fail when coupled with HTML5 Offline API
  69286. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69287. xhr.open("GET", retryManifestURL, true);
  69288. xhr.send();
  69289. }
  69290. else {
  69291. noManifestFile();
  69292. }
  69293. }, false);
  69294. try {
  69295. xhr.send();
  69296. }
  69297. catch (ex) {
  69298. BABYLON.Tools.Error("Error on XHR send request.");
  69299. this.callbackManifestChecked(false);
  69300. }
  69301. };
  69302. /**
  69303. * Open the database and make it available
  69304. * @param successCallback defines the callback to call on success
  69305. * @param errorCallback defines the callback to call on error
  69306. */
  69307. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69308. var _this = this;
  69309. var handleError = function () {
  69310. _this.isSupported = false;
  69311. if (errorCallback)
  69312. errorCallback();
  69313. };
  69314. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69315. // Your browser doesn't support IndexedDB
  69316. this.isSupported = false;
  69317. if (errorCallback)
  69318. errorCallback();
  69319. }
  69320. else {
  69321. // If the DB hasn't been opened or created yet
  69322. if (!this.db) {
  69323. this.hasReachedQuota = false;
  69324. this.isSupported = true;
  69325. var request = this.idbFactory.open("babylonjs", 1);
  69326. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69327. request.onerror = function (event) {
  69328. handleError();
  69329. };
  69330. // executes when a version change transaction cannot complete due to other active transactions
  69331. request.onblocked = function (event) {
  69332. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69333. handleError();
  69334. };
  69335. // DB has been opened successfully
  69336. request.onsuccess = function (event) {
  69337. _this.db = request.result;
  69338. successCallback();
  69339. };
  69340. // Initialization of the DB. Creating Scenes & Textures stores
  69341. request.onupgradeneeded = function (event) {
  69342. _this.db = (event.target).result;
  69343. if (_this.db) {
  69344. try {
  69345. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69346. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69347. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69348. }
  69349. catch (ex) {
  69350. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69351. handleError();
  69352. }
  69353. }
  69354. };
  69355. }
  69356. // DB has already been created and opened
  69357. else {
  69358. if (successCallback)
  69359. successCallback();
  69360. }
  69361. }
  69362. };
  69363. /**
  69364. * Loads an image from the database
  69365. * @param url defines the url to load from
  69366. * @param image defines the target DOM image
  69367. */
  69368. Database.prototype.loadImageFromDB = function (url, image) {
  69369. var _this = this;
  69370. var completeURL = Database._ReturnFullUrlLocation(url);
  69371. var saveAndLoadImage = function () {
  69372. if (!_this.hasReachedQuota && _this.db !== null) {
  69373. // the texture is not yet in the DB, let's try to save it
  69374. _this._saveImageIntoDBAsync(completeURL, image);
  69375. }
  69376. // If the texture is not in the DB and we've reached the DB quota limit
  69377. // let's load it directly from the web
  69378. else {
  69379. image.src = url;
  69380. }
  69381. };
  69382. if (!this.mustUpdateRessources) {
  69383. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69384. }
  69385. // First time we're download the images or update requested in the manifest file by a version change
  69386. else {
  69387. saveAndLoadImage();
  69388. }
  69389. };
  69390. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69391. if (this.isSupported && this.db !== null) {
  69392. var texture;
  69393. var transaction = this.db.transaction(["textures"]);
  69394. transaction.onabort = function (event) {
  69395. image.src = url;
  69396. };
  69397. transaction.oncomplete = function (event) {
  69398. var blobTextureURL;
  69399. if (texture) {
  69400. var URL = window.URL || window.webkitURL;
  69401. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69402. image.onerror = function () {
  69403. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69404. image.src = url;
  69405. };
  69406. image.src = blobTextureURL;
  69407. }
  69408. else {
  69409. notInDBCallback();
  69410. }
  69411. };
  69412. var getRequest = transaction.objectStore("textures").get(url);
  69413. getRequest.onsuccess = function (event) {
  69414. texture = (event.target).result;
  69415. };
  69416. getRequest.onerror = function (event) {
  69417. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69418. image.src = url;
  69419. };
  69420. }
  69421. else {
  69422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69423. image.src = url;
  69424. }
  69425. };
  69426. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69427. var _this = this;
  69428. if (this.isSupported) {
  69429. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69430. var generateBlobUrl = function () {
  69431. var blobTextureURL;
  69432. if (blob) {
  69433. var URL = window.URL || window.webkitURL;
  69434. try {
  69435. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69436. }
  69437. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69438. catch (ex) {
  69439. blobTextureURL = URL.createObjectURL(blob);
  69440. }
  69441. }
  69442. if (blobTextureURL) {
  69443. image.src = blobTextureURL;
  69444. }
  69445. };
  69446. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69447. var xhr = new XMLHttpRequest(), blob;
  69448. xhr.open("GET", url, true);
  69449. xhr.responseType = "blob";
  69450. xhr.addEventListener("load", function () {
  69451. if (xhr.status === 200 && _this.db) {
  69452. // Blob as response (XHR2)
  69453. blob = xhr.response;
  69454. var transaction = _this.db.transaction(["textures"], "readwrite");
  69455. // the transaction could abort because of a QuotaExceededError error
  69456. transaction.onabort = function (event) {
  69457. try {
  69458. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69459. var srcElement = (event.srcElement || event.target);
  69460. var error = srcElement.error;
  69461. if (error && error.name === "QuotaExceededError") {
  69462. _this.hasReachedQuota = true;
  69463. }
  69464. }
  69465. catch (ex) { }
  69466. generateBlobUrl();
  69467. };
  69468. transaction.oncomplete = function (event) {
  69469. generateBlobUrl();
  69470. };
  69471. var newTexture = { textureUrl: url, data: blob };
  69472. try {
  69473. // Put the blob into the dabase
  69474. var addRequest = transaction.objectStore("textures").put(newTexture);
  69475. addRequest.onsuccess = function (event) {
  69476. };
  69477. addRequest.onerror = function (event) {
  69478. generateBlobUrl();
  69479. };
  69480. }
  69481. catch (ex) {
  69482. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69483. if (ex.code === 25) {
  69484. Database.IsUASupportingBlobStorage = false;
  69485. }
  69486. image.src = url;
  69487. }
  69488. }
  69489. else {
  69490. image.src = url;
  69491. }
  69492. }, false);
  69493. xhr.addEventListener("error", function (event) {
  69494. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69495. image.src = url;
  69496. }, false);
  69497. xhr.send();
  69498. }
  69499. else {
  69500. image.src = url;
  69501. }
  69502. }
  69503. else {
  69504. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69505. image.src = url;
  69506. }
  69507. };
  69508. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69509. var _this = this;
  69510. var updateVersion = function () {
  69511. // the version is not yet in the DB or we need to update it
  69512. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69513. };
  69514. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69515. };
  69516. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69517. var _this = this;
  69518. if (this.isSupported && this.db) {
  69519. var version;
  69520. try {
  69521. var transaction = this.db.transaction(["versions"]);
  69522. transaction.oncomplete = function (event) {
  69523. if (version) {
  69524. // If the version in the JSON file is different from the version in DB
  69525. if (_this.manifestVersionFound !== version.data) {
  69526. _this.mustUpdateRessources = true;
  69527. updateInDBCallback();
  69528. }
  69529. else {
  69530. callback(version.data);
  69531. }
  69532. }
  69533. // version was not found in DB
  69534. else {
  69535. _this.mustUpdateRessources = true;
  69536. updateInDBCallback();
  69537. }
  69538. };
  69539. transaction.onabort = function (event) {
  69540. callback(-1);
  69541. };
  69542. var getRequest = transaction.objectStore("versions").get(url);
  69543. getRequest.onsuccess = function (event) {
  69544. version = (event.target).result;
  69545. };
  69546. getRequest.onerror = function (event) {
  69547. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69548. callback(-1);
  69549. };
  69550. }
  69551. catch (ex) {
  69552. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69553. callback(-1);
  69554. }
  69555. }
  69556. else {
  69557. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69558. callback(-1);
  69559. }
  69560. };
  69561. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69562. var _this = this;
  69563. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69564. try {
  69565. // Open a transaction to the database
  69566. var transaction = this.db.transaction(["versions"], "readwrite");
  69567. // the transaction could abort because of a QuotaExceededError error
  69568. transaction.onabort = function (event) {
  69569. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69570. var error = event.srcElement['error'];
  69571. if (error && error.name === "QuotaExceededError") {
  69572. _this.hasReachedQuota = true;
  69573. }
  69574. }
  69575. catch (ex) { }
  69576. callback(-1);
  69577. };
  69578. transaction.oncomplete = function (event) {
  69579. callback(_this.manifestVersionFound);
  69580. };
  69581. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69582. // Put the scene into the database
  69583. var addRequest = transaction.objectStore("versions").put(newVersion);
  69584. addRequest.onsuccess = function (event) {
  69585. };
  69586. addRequest.onerror = function (event) {
  69587. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69588. };
  69589. }
  69590. catch (ex) {
  69591. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69592. callback(-1);
  69593. }
  69594. }
  69595. else {
  69596. callback(-1);
  69597. }
  69598. };
  69599. /**
  69600. * Loads a file from database
  69601. * @param url defines the URL to load from
  69602. * @param sceneLoaded defines a callback to call on success
  69603. * @param progressCallBack defines a callback to call when progress changed
  69604. * @param errorCallback defines a callback to call on error
  69605. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69606. */
  69607. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69608. var _this = this;
  69609. var completeUrl = Database._ReturnFullUrlLocation(url);
  69610. var saveAndLoadFile = function () {
  69611. // the scene is not yet in the DB, let's try to save it
  69612. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69613. };
  69614. this._checkVersionFromDB(completeUrl, function (version) {
  69615. if (version !== -1) {
  69616. if (!_this.mustUpdateRessources) {
  69617. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69618. }
  69619. else {
  69620. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69621. }
  69622. }
  69623. else {
  69624. if (errorCallback) {
  69625. errorCallback();
  69626. }
  69627. }
  69628. });
  69629. };
  69630. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69631. if (this.isSupported && this.db) {
  69632. var targetStore;
  69633. if (url.indexOf(".babylon") !== -1) {
  69634. targetStore = "scenes";
  69635. }
  69636. else {
  69637. targetStore = "textures";
  69638. }
  69639. var file;
  69640. var transaction = this.db.transaction([targetStore]);
  69641. transaction.oncomplete = function (event) {
  69642. if (file) {
  69643. callback(file.data);
  69644. }
  69645. // file was not found in DB
  69646. else {
  69647. notInDBCallback();
  69648. }
  69649. };
  69650. transaction.onabort = function (event) {
  69651. notInDBCallback();
  69652. };
  69653. var getRequest = transaction.objectStore(targetStore).get(url);
  69654. getRequest.onsuccess = function (event) {
  69655. file = (event.target).result;
  69656. };
  69657. getRequest.onerror = function (event) {
  69658. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69659. notInDBCallback();
  69660. };
  69661. }
  69662. else {
  69663. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69664. callback();
  69665. }
  69666. };
  69667. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69668. var _this = this;
  69669. if (this.isSupported) {
  69670. var targetStore;
  69671. if (url.indexOf(".babylon") !== -1) {
  69672. targetStore = "scenes";
  69673. }
  69674. else {
  69675. targetStore = "textures";
  69676. }
  69677. // Create XHR
  69678. var xhr = new XMLHttpRequest();
  69679. var fileData;
  69680. xhr.open("GET", url, true);
  69681. if (useArrayBuffer) {
  69682. xhr.responseType = "arraybuffer";
  69683. }
  69684. if (progressCallback) {
  69685. xhr.onprogress = progressCallback;
  69686. }
  69687. xhr.addEventListener("load", function () {
  69688. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69689. // Blob as response (XHR2)
  69690. //fileData = xhr.responseText;
  69691. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69692. if (!_this.hasReachedQuota && _this.db) {
  69693. // Open a transaction to the database
  69694. var transaction = _this.db.transaction([targetStore], "readwrite");
  69695. // the transaction could abort because of a QuotaExceededError error
  69696. transaction.onabort = function (event) {
  69697. try {
  69698. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69699. var error = event.srcElement['error'];
  69700. if (error && error.name === "QuotaExceededError") {
  69701. _this.hasReachedQuota = true;
  69702. }
  69703. }
  69704. catch (ex) { }
  69705. callback(fileData);
  69706. };
  69707. transaction.oncomplete = function (event) {
  69708. callback(fileData);
  69709. };
  69710. var newFile;
  69711. if (targetStore === "scenes") {
  69712. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69713. }
  69714. else {
  69715. newFile = { textureUrl: url, data: fileData };
  69716. }
  69717. try {
  69718. // Put the scene into the database
  69719. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69720. addRequest.onsuccess = function (event) {
  69721. };
  69722. addRequest.onerror = function (event) {
  69723. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69724. };
  69725. }
  69726. catch (ex) {
  69727. callback(fileData);
  69728. }
  69729. }
  69730. else {
  69731. callback(fileData);
  69732. }
  69733. }
  69734. else {
  69735. callback();
  69736. }
  69737. }, false);
  69738. xhr.addEventListener("error", function (event) {
  69739. BABYLON.Tools.Error("error on XHR request.");
  69740. callback();
  69741. }, false);
  69742. xhr.send();
  69743. }
  69744. else {
  69745. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69746. callback();
  69747. }
  69748. };
  69749. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69750. Database.IsUASupportingBlobStorage = true;
  69751. /** Gets a boolean indicating if Database storate is enabled */
  69752. Database.IDBStorageEnabled = true;
  69753. Database._ParseURL = function (url) {
  69754. var a = document.createElement('a');
  69755. a.href = url;
  69756. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69757. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69758. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69759. return absLocation;
  69760. };
  69761. Database._ReturnFullUrlLocation = function (url) {
  69762. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69763. return (Database._ParseURL(window.location.href) + url);
  69764. }
  69765. else {
  69766. return url;
  69767. }
  69768. };
  69769. return Database;
  69770. }());
  69771. BABYLON.Database = Database;
  69772. })(BABYLON || (BABYLON = {}));
  69773. //# sourceMappingURL=babylon.database.js.map
  69774. var BABYLON;
  69775. (function (BABYLON) {
  69776. var FresnelParameters = /** @class */ (function () {
  69777. function FresnelParameters() {
  69778. this._isEnabled = true;
  69779. this.leftColor = BABYLON.Color3.White();
  69780. this.rightColor = BABYLON.Color3.Black();
  69781. this.bias = 0;
  69782. this.power = 1;
  69783. }
  69784. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69785. get: function () {
  69786. return this._isEnabled;
  69787. },
  69788. set: function (value) {
  69789. if (this._isEnabled === value) {
  69790. return;
  69791. }
  69792. this._isEnabled = value;
  69793. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69794. },
  69795. enumerable: true,
  69796. configurable: true
  69797. });
  69798. FresnelParameters.prototype.clone = function () {
  69799. var newFresnelParameters = new FresnelParameters();
  69800. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69801. return newFresnelParameters;
  69802. };
  69803. FresnelParameters.prototype.serialize = function () {
  69804. var serializationObject = {};
  69805. serializationObject.isEnabled = this.isEnabled;
  69806. serializationObject.leftColor = this.leftColor.asArray();
  69807. serializationObject.rightColor = this.rightColor.asArray();
  69808. serializationObject.bias = this.bias;
  69809. serializationObject.power = this.power;
  69810. return serializationObject;
  69811. };
  69812. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69813. var fresnelParameters = new FresnelParameters();
  69814. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69815. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69816. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69817. fresnelParameters.bias = parsedFresnelParameters.bias;
  69818. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69819. return fresnelParameters;
  69820. };
  69821. return FresnelParameters;
  69822. }());
  69823. BABYLON.FresnelParameters = FresnelParameters;
  69824. })(BABYLON || (BABYLON = {}));
  69825. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69826. var BABYLON;
  69827. (function (BABYLON) {
  69828. var MultiMaterial = /** @class */ (function (_super) {
  69829. __extends(MultiMaterial, _super);
  69830. function MultiMaterial(name, scene) {
  69831. var _this = _super.call(this, name, scene, true) || this;
  69832. scene.multiMaterials.push(_this);
  69833. _this.subMaterials = new Array();
  69834. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69835. return _this;
  69836. }
  69837. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69838. get: function () {
  69839. return this._subMaterials;
  69840. },
  69841. set: function (value) {
  69842. this._subMaterials = value;
  69843. this._hookArray(value);
  69844. },
  69845. enumerable: true,
  69846. configurable: true
  69847. });
  69848. MultiMaterial.prototype._hookArray = function (array) {
  69849. var _this = this;
  69850. var oldPush = array.push;
  69851. array.push = function () {
  69852. var items = [];
  69853. for (var _i = 0; _i < arguments.length; _i++) {
  69854. items[_i] = arguments[_i];
  69855. }
  69856. var result = oldPush.apply(array, items);
  69857. _this._markAllSubMeshesAsTexturesDirty();
  69858. return result;
  69859. };
  69860. var oldSplice = array.splice;
  69861. array.splice = function (index, deleteCount) {
  69862. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69863. _this._markAllSubMeshesAsTexturesDirty();
  69864. return deleted;
  69865. };
  69866. };
  69867. // Properties
  69868. MultiMaterial.prototype.getSubMaterial = function (index) {
  69869. if (index < 0 || index >= this.subMaterials.length) {
  69870. return this.getScene().defaultMaterial;
  69871. }
  69872. return this.subMaterials[index];
  69873. };
  69874. MultiMaterial.prototype.getActiveTextures = function () {
  69875. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69876. if (subMaterial) {
  69877. return subMaterial.getActiveTextures();
  69878. }
  69879. else {
  69880. return [];
  69881. }
  69882. }));
  69883. var _a;
  69884. };
  69885. // Methods
  69886. MultiMaterial.prototype.getClassName = function () {
  69887. return "MultiMaterial";
  69888. };
  69889. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69890. for (var index = 0; index < this.subMaterials.length; index++) {
  69891. var subMaterial = this.subMaterials[index];
  69892. if (subMaterial) {
  69893. if (subMaterial.storeEffectOnSubMeshes) {
  69894. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69895. return false;
  69896. }
  69897. continue;
  69898. }
  69899. if (!subMaterial.isReady(mesh)) {
  69900. return false;
  69901. }
  69902. }
  69903. }
  69904. return true;
  69905. };
  69906. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69907. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69908. for (var index = 0; index < this.subMaterials.length; index++) {
  69909. var subMaterial = null;
  69910. var current = this.subMaterials[index];
  69911. if (cloneChildren && current) {
  69912. subMaterial = current.clone(name + "-" + current.name);
  69913. }
  69914. else {
  69915. subMaterial = this.subMaterials[index];
  69916. }
  69917. newMultiMaterial.subMaterials.push(subMaterial);
  69918. }
  69919. return newMultiMaterial;
  69920. };
  69921. MultiMaterial.prototype.serialize = function () {
  69922. var serializationObject = {};
  69923. serializationObject.name = this.name;
  69924. serializationObject.id = this.id;
  69925. if (BABYLON.Tags) {
  69926. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69927. }
  69928. serializationObject.materials = [];
  69929. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69930. var subMat = this.subMaterials[matIndex];
  69931. if (subMat) {
  69932. serializationObject.materials.push(subMat.id);
  69933. }
  69934. else {
  69935. serializationObject.materials.push(null);
  69936. }
  69937. }
  69938. return serializationObject;
  69939. };
  69940. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69941. var scene = this.getScene();
  69942. if (!scene) {
  69943. return;
  69944. }
  69945. var index = scene.multiMaterials.indexOf(this);
  69946. if (index >= 0) {
  69947. scene.multiMaterials.splice(index, 1);
  69948. }
  69949. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69950. };
  69951. return MultiMaterial;
  69952. }(BABYLON.Material));
  69953. BABYLON.MultiMaterial = MultiMaterial;
  69954. })(BABYLON || (BABYLON = {}));
  69955. //# sourceMappingURL=babylon.multiMaterial.js.map
  69956. var BABYLON;
  69957. (function (BABYLON) {
  69958. var FreeCameraTouchInput = /** @class */ (function () {
  69959. function FreeCameraTouchInput() {
  69960. this._offsetX = null;
  69961. this._offsetY = null;
  69962. this._pointerPressed = new Array();
  69963. this.touchAngularSensibility = 200000.0;
  69964. this.touchMoveSensibility = 250.0;
  69965. }
  69966. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69967. var _this = this;
  69968. var previousPosition = null;
  69969. if (this._pointerInput === undefined) {
  69970. this._onLostFocus = function (evt) {
  69971. _this._offsetX = null;
  69972. _this._offsetY = null;
  69973. };
  69974. this._pointerInput = function (p, s) {
  69975. var evt = p.event;
  69976. if (evt.pointerType === "mouse") {
  69977. return;
  69978. }
  69979. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69980. if (!noPreventDefault) {
  69981. evt.preventDefault();
  69982. }
  69983. _this._pointerPressed.push(evt.pointerId);
  69984. if (_this._pointerPressed.length !== 1) {
  69985. return;
  69986. }
  69987. previousPosition = {
  69988. x: evt.clientX,
  69989. y: evt.clientY
  69990. };
  69991. }
  69992. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69993. if (!noPreventDefault) {
  69994. evt.preventDefault();
  69995. }
  69996. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69997. if (index === -1) {
  69998. return;
  69999. }
  70000. _this._pointerPressed.splice(index, 1);
  70001. if (index != 0) {
  70002. return;
  70003. }
  70004. previousPosition = null;
  70005. _this._offsetX = null;
  70006. _this._offsetY = null;
  70007. }
  70008. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70009. if (!noPreventDefault) {
  70010. evt.preventDefault();
  70011. }
  70012. if (!previousPosition) {
  70013. return;
  70014. }
  70015. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70016. if (index != 0) {
  70017. return;
  70018. }
  70019. _this._offsetX = evt.clientX - previousPosition.x;
  70020. _this._offsetY = -(evt.clientY - previousPosition.y);
  70021. }
  70022. };
  70023. }
  70024. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70025. if (this._onLostFocus) {
  70026. element.addEventListener("blur", this._onLostFocus);
  70027. }
  70028. };
  70029. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70030. if (this._pointerInput && element) {
  70031. if (this._observer) {
  70032. this.camera.getScene().onPointerObservable.remove(this._observer);
  70033. this._observer = null;
  70034. }
  70035. if (this._onLostFocus) {
  70036. element.removeEventListener("blur", this._onLostFocus);
  70037. this._onLostFocus = null;
  70038. }
  70039. this._pointerPressed = [];
  70040. this._offsetX = null;
  70041. this._offsetY = null;
  70042. }
  70043. };
  70044. FreeCameraTouchInput.prototype.checkInputs = function () {
  70045. if (this._offsetX && this._offsetY) {
  70046. var camera = this.camera;
  70047. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70048. if (this._pointerPressed.length > 1) {
  70049. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70050. }
  70051. else {
  70052. var speed = camera._computeLocalCameraSpeed();
  70053. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70054. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70055. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70056. }
  70057. }
  70058. };
  70059. FreeCameraTouchInput.prototype.getClassName = function () {
  70060. return "FreeCameraTouchInput";
  70061. };
  70062. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70063. return "touch";
  70064. };
  70065. __decorate([
  70066. BABYLON.serialize()
  70067. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70068. __decorate([
  70069. BABYLON.serialize()
  70070. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70071. return FreeCameraTouchInput;
  70072. }());
  70073. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70074. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70075. })(BABYLON || (BABYLON = {}));
  70076. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70077. var BABYLON;
  70078. (function (BABYLON) {
  70079. // We're mainly based on the logic defined into the FreeCamera code
  70080. var TouchCamera = /** @class */ (function (_super) {
  70081. __extends(TouchCamera, _super);
  70082. //-- end properties for backward compatibility for inputs
  70083. function TouchCamera(name, position, scene) {
  70084. var _this = _super.call(this, name, position, scene) || this;
  70085. _this.inputs.addTouch();
  70086. _this._setupInputs();
  70087. return _this;
  70088. }
  70089. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70090. //-- Begin properties for backward compatibility for inputs
  70091. get: function () {
  70092. var touch = this.inputs.attached["touch"];
  70093. if (touch)
  70094. return touch.touchAngularSensibility;
  70095. return 0;
  70096. },
  70097. set: function (value) {
  70098. var touch = this.inputs.attached["touch"];
  70099. if (touch)
  70100. touch.touchAngularSensibility = value;
  70101. },
  70102. enumerable: true,
  70103. configurable: true
  70104. });
  70105. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70106. get: function () {
  70107. var touch = this.inputs.attached["touch"];
  70108. if (touch)
  70109. return touch.touchMoveSensibility;
  70110. return 0;
  70111. },
  70112. set: function (value) {
  70113. var touch = this.inputs.attached["touch"];
  70114. if (touch)
  70115. touch.touchMoveSensibility = value;
  70116. },
  70117. enumerable: true,
  70118. configurable: true
  70119. });
  70120. TouchCamera.prototype.getClassName = function () {
  70121. return "TouchCamera";
  70122. };
  70123. TouchCamera.prototype._setupInputs = function () {
  70124. var mouse = this.inputs.attached["mouse"];
  70125. if (mouse) {
  70126. mouse.touchEnabled = false;
  70127. }
  70128. };
  70129. return TouchCamera;
  70130. }(BABYLON.FreeCamera));
  70131. BABYLON.TouchCamera = TouchCamera;
  70132. })(BABYLON || (BABYLON = {}));
  70133. //# sourceMappingURL=babylon.touchCamera.js.map
  70134. var BABYLON;
  70135. (function (BABYLON) {
  70136. var ProceduralTexture = /** @class */ (function (_super) {
  70137. __extends(ProceduralTexture, _super);
  70138. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70139. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70140. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70141. if (isCube === void 0) { isCube = false; }
  70142. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70143. _this.isCube = isCube;
  70144. _this.isEnabled = true;
  70145. _this._currentRefreshId = -1;
  70146. _this._refreshRate = 1;
  70147. _this._vertexBuffers = {};
  70148. _this._uniforms = new Array();
  70149. _this._samplers = new Array();
  70150. _this._textures = {};
  70151. _this._floats = {};
  70152. _this._floatsArrays = {};
  70153. _this._colors3 = {};
  70154. _this._colors4 = {};
  70155. _this._vectors2 = {};
  70156. _this._vectors3 = {};
  70157. _this._matrices = {};
  70158. _this._fallbackTextureUsed = false;
  70159. scene.proceduralTextures.push(_this);
  70160. _this._engine = scene.getEngine();
  70161. _this.name = name;
  70162. _this.isRenderTarget = true;
  70163. _this._size = size;
  70164. _this._generateMipMaps = generateMipMaps;
  70165. _this.setFragment(fragment);
  70166. _this._fallbackTexture = fallbackTexture;
  70167. if (isCube) {
  70168. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70169. _this.setFloat("face", 0);
  70170. }
  70171. else {
  70172. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70173. }
  70174. // VBO
  70175. var vertices = [];
  70176. vertices.push(1, 1);
  70177. vertices.push(-1, 1);
  70178. vertices.push(-1, -1);
  70179. vertices.push(1, -1);
  70180. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70181. _this._createIndexBuffer();
  70182. return _this;
  70183. }
  70184. ProceduralTexture.prototype._createIndexBuffer = function () {
  70185. var engine = this._engine;
  70186. // Indices
  70187. var indices = [];
  70188. indices.push(0);
  70189. indices.push(1);
  70190. indices.push(2);
  70191. indices.push(0);
  70192. indices.push(2);
  70193. indices.push(3);
  70194. this._indexBuffer = engine.createIndexBuffer(indices);
  70195. };
  70196. ProceduralTexture.prototype._rebuild = function () {
  70197. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70198. if (vb) {
  70199. vb._rebuild();
  70200. }
  70201. this._createIndexBuffer();
  70202. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70203. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70204. }
  70205. };
  70206. ProceduralTexture.prototype.reset = function () {
  70207. if (this._effect === undefined) {
  70208. return;
  70209. }
  70210. var engine = this._engine;
  70211. engine._releaseEffect(this._effect);
  70212. };
  70213. ProceduralTexture.prototype.isReady = function () {
  70214. var _this = this;
  70215. var engine = this._engine;
  70216. var shaders;
  70217. if (!this._fragment) {
  70218. return false;
  70219. }
  70220. if (this._fallbackTextureUsed) {
  70221. return true;
  70222. }
  70223. if (this._fragment.fragmentElement !== undefined) {
  70224. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70225. }
  70226. else {
  70227. shaders = { vertex: "procedural", fragment: this._fragment };
  70228. }
  70229. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70230. _this.releaseInternalTexture();
  70231. if (_this._fallbackTexture) {
  70232. _this._texture = _this._fallbackTexture._texture;
  70233. if (_this._texture) {
  70234. _this._texture.incrementReferences();
  70235. }
  70236. }
  70237. _this._fallbackTextureUsed = true;
  70238. });
  70239. return this._effect.isReady();
  70240. };
  70241. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70242. this._currentRefreshId = -1;
  70243. };
  70244. ProceduralTexture.prototype.setFragment = function (fragment) {
  70245. this._fragment = fragment;
  70246. };
  70247. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70248. get: function () {
  70249. return this._refreshRate;
  70250. },
  70251. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70252. set: function (value) {
  70253. this._refreshRate = value;
  70254. this.resetRefreshCounter();
  70255. },
  70256. enumerable: true,
  70257. configurable: true
  70258. });
  70259. ProceduralTexture.prototype._shouldRender = function () {
  70260. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70261. return false;
  70262. }
  70263. if (this._fallbackTextureUsed) {
  70264. return false;
  70265. }
  70266. if (this._currentRefreshId === -1) { // At least render once
  70267. this._currentRefreshId = 1;
  70268. return true;
  70269. }
  70270. if (this.refreshRate === this._currentRefreshId) {
  70271. this._currentRefreshId = 1;
  70272. return true;
  70273. }
  70274. this._currentRefreshId++;
  70275. return false;
  70276. };
  70277. ProceduralTexture.prototype.getRenderSize = function () {
  70278. return this._size;
  70279. };
  70280. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70281. if (this._fallbackTextureUsed) {
  70282. return;
  70283. }
  70284. this.releaseInternalTexture();
  70285. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70286. };
  70287. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70288. if (this._uniforms.indexOf(uniformName) === -1) {
  70289. this._uniforms.push(uniformName);
  70290. }
  70291. };
  70292. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70293. if (this._samplers.indexOf(name) === -1) {
  70294. this._samplers.push(name);
  70295. }
  70296. this._textures[name] = texture;
  70297. return this;
  70298. };
  70299. ProceduralTexture.prototype.setFloat = function (name, value) {
  70300. this._checkUniform(name);
  70301. this._floats[name] = value;
  70302. return this;
  70303. };
  70304. ProceduralTexture.prototype.setFloats = function (name, value) {
  70305. this._checkUniform(name);
  70306. this._floatsArrays[name] = value;
  70307. return this;
  70308. };
  70309. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70310. this._checkUniform(name);
  70311. this._colors3[name] = value;
  70312. return this;
  70313. };
  70314. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70315. this._checkUniform(name);
  70316. this._colors4[name] = value;
  70317. return this;
  70318. };
  70319. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70320. this._checkUniform(name);
  70321. this._vectors2[name] = value;
  70322. return this;
  70323. };
  70324. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70325. this._checkUniform(name);
  70326. this._vectors3[name] = value;
  70327. return this;
  70328. };
  70329. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70330. this._checkUniform(name);
  70331. this._matrices[name] = value;
  70332. return this;
  70333. };
  70334. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70335. var scene = this.getScene();
  70336. if (!scene) {
  70337. return;
  70338. }
  70339. var engine = this._engine;
  70340. // Render
  70341. engine.enableEffect(this._effect);
  70342. engine.setState(false);
  70343. // Texture
  70344. for (var name in this._textures) {
  70345. this._effect.setTexture(name, this._textures[name]);
  70346. }
  70347. // Float
  70348. for (name in this._floats) {
  70349. this._effect.setFloat(name, this._floats[name]);
  70350. }
  70351. // Floats
  70352. for (name in this._floatsArrays) {
  70353. this._effect.setArray(name, this._floatsArrays[name]);
  70354. }
  70355. // Color3
  70356. for (name in this._colors3) {
  70357. this._effect.setColor3(name, this._colors3[name]);
  70358. }
  70359. // Color4
  70360. for (name in this._colors4) {
  70361. var color = this._colors4[name];
  70362. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70363. }
  70364. // Vector2
  70365. for (name in this._vectors2) {
  70366. this._effect.setVector2(name, this._vectors2[name]);
  70367. }
  70368. // Vector3
  70369. for (name in this._vectors3) {
  70370. this._effect.setVector3(name, this._vectors3[name]);
  70371. }
  70372. // Matrix
  70373. for (name in this._matrices) {
  70374. this._effect.setMatrix(name, this._matrices[name]);
  70375. }
  70376. if (!this._texture) {
  70377. return;
  70378. }
  70379. if (this.isCube) {
  70380. for (var face = 0; face < 6; face++) {
  70381. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70382. // VBOs
  70383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70384. this._effect.setFloat("face", face);
  70385. // Clear
  70386. engine.clear(scene.clearColor, true, true, true);
  70387. // Draw order
  70388. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70389. // Mipmaps
  70390. if (face === 5) {
  70391. engine.generateMipMapsForCubemap(this._texture);
  70392. }
  70393. }
  70394. }
  70395. else {
  70396. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70397. // VBOs
  70398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70399. // Clear
  70400. engine.clear(scene.clearColor, true, true, true);
  70401. // Draw order
  70402. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70403. }
  70404. // Unbind
  70405. engine.unBindFramebuffer(this._texture, this.isCube);
  70406. if (this.onGenerated) {
  70407. this.onGenerated();
  70408. }
  70409. };
  70410. ProceduralTexture.prototype.clone = function () {
  70411. var textureSize = this.getSize();
  70412. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70413. // Base texture
  70414. newTexture.hasAlpha = this.hasAlpha;
  70415. newTexture.level = this.level;
  70416. // RenderTarget Texture
  70417. newTexture.coordinatesMode = this.coordinatesMode;
  70418. return newTexture;
  70419. };
  70420. ProceduralTexture.prototype.dispose = function () {
  70421. var scene = this.getScene();
  70422. if (!scene) {
  70423. return;
  70424. }
  70425. var index = scene.proceduralTextures.indexOf(this);
  70426. if (index >= 0) {
  70427. scene.proceduralTextures.splice(index, 1);
  70428. }
  70429. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70430. if (vertexBuffer) {
  70431. vertexBuffer.dispose();
  70432. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70433. }
  70434. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70435. this._indexBuffer = null;
  70436. }
  70437. _super.prototype.dispose.call(this);
  70438. };
  70439. return ProceduralTexture;
  70440. }(BABYLON.Texture));
  70441. BABYLON.ProceduralTexture = ProceduralTexture;
  70442. })(BABYLON || (BABYLON = {}));
  70443. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70444. var BABYLON;
  70445. (function (BABYLON) {
  70446. var CustomProceduralTexture = /** @class */ (function (_super) {
  70447. __extends(CustomProceduralTexture, _super);
  70448. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70449. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70450. _this._animate = true;
  70451. _this._time = 0;
  70452. _this._texturePath = texturePath;
  70453. //Try to load json
  70454. _this.loadJson(texturePath);
  70455. _this.refreshRate = 1;
  70456. return _this;
  70457. }
  70458. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70459. var _this = this;
  70460. var noConfigFile = function () {
  70461. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70462. try {
  70463. _this.setFragment(_this._texturePath);
  70464. }
  70465. catch (ex) {
  70466. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70467. }
  70468. };
  70469. var configFileUrl = jsonUrl + "/config.json";
  70470. var xhr = new XMLHttpRequest();
  70471. xhr.open("GET", configFileUrl, true);
  70472. xhr.addEventListener("load", function () {
  70473. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70474. try {
  70475. _this._config = JSON.parse(xhr.response);
  70476. _this.updateShaderUniforms();
  70477. _this.updateTextures();
  70478. _this.setFragment(_this._texturePath + "/custom");
  70479. _this._animate = _this._config.animate;
  70480. _this.refreshRate = _this._config.refreshrate;
  70481. }
  70482. catch (ex) {
  70483. noConfigFile();
  70484. }
  70485. }
  70486. else {
  70487. noConfigFile();
  70488. }
  70489. }, false);
  70490. xhr.addEventListener("error", function () {
  70491. noConfigFile();
  70492. }, false);
  70493. try {
  70494. xhr.send();
  70495. }
  70496. catch (ex) {
  70497. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70498. }
  70499. };
  70500. CustomProceduralTexture.prototype.isReady = function () {
  70501. if (!_super.prototype.isReady.call(this)) {
  70502. return false;
  70503. }
  70504. for (var name in this._textures) {
  70505. var texture = this._textures[name];
  70506. if (!texture.isReady()) {
  70507. return false;
  70508. }
  70509. }
  70510. return true;
  70511. };
  70512. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70513. var scene = this.getScene();
  70514. if (this._animate && scene) {
  70515. this._time += scene.getAnimationRatio() * 0.03;
  70516. this.updateShaderUniforms();
  70517. }
  70518. _super.prototype.render.call(this, useCameraPostProcess);
  70519. };
  70520. CustomProceduralTexture.prototype.updateTextures = function () {
  70521. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70522. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70523. }
  70524. };
  70525. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70526. if (this._config) {
  70527. for (var j = 0; j < this._config.uniforms.length; j++) {
  70528. var uniform = this._config.uniforms[j];
  70529. switch (uniform.type) {
  70530. case "float":
  70531. this.setFloat(uniform.name, uniform.value);
  70532. break;
  70533. case "color3":
  70534. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70535. break;
  70536. case "color4":
  70537. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70538. break;
  70539. case "vector2":
  70540. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70541. break;
  70542. case "vector3":
  70543. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70544. break;
  70545. }
  70546. }
  70547. }
  70548. this.setFloat("time", this._time);
  70549. };
  70550. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70551. get: function () {
  70552. return this._animate;
  70553. },
  70554. set: function (value) {
  70555. this._animate = value;
  70556. },
  70557. enumerable: true,
  70558. configurable: true
  70559. });
  70560. return CustomProceduralTexture;
  70561. }(BABYLON.ProceduralTexture));
  70562. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70563. })(BABYLON || (BABYLON = {}));
  70564. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70565. var BABYLON;
  70566. (function (BABYLON) {
  70567. var FreeCameraGamepadInput = /** @class */ (function () {
  70568. function FreeCameraGamepadInput() {
  70569. this.gamepadAngularSensibility = 200;
  70570. this.gamepadMoveSensibility = 40;
  70571. // private members
  70572. this._cameraTransform = BABYLON.Matrix.Identity();
  70573. this._deltaTransform = BABYLON.Vector3.Zero();
  70574. this._vector3 = BABYLON.Vector3.Zero();
  70575. this._vector2 = BABYLON.Vector2.Zero();
  70576. }
  70577. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70578. var _this = this;
  70579. var manager = this.camera.getScene().gamepadManager;
  70580. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70581. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70582. // prioritize XBOX gamepads.
  70583. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70584. _this.gamepad = gamepad;
  70585. }
  70586. }
  70587. });
  70588. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70589. if (_this.gamepad === gamepad) {
  70590. _this.gamepad = null;
  70591. }
  70592. });
  70593. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70594. };
  70595. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70596. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70597. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70598. this.gamepad = null;
  70599. };
  70600. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70601. if (this.gamepad && this.gamepad.leftStick) {
  70602. var camera = this.camera;
  70603. var LSValues = this.gamepad.leftStick;
  70604. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70605. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70606. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70607. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70608. var RSValues = this.gamepad.rightStick;
  70609. if (RSValues) {
  70610. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70611. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70612. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70613. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70614. }
  70615. else {
  70616. RSValues = { x: 0, y: 0 };
  70617. }
  70618. if (!camera.rotationQuaternion) {
  70619. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70620. }
  70621. else {
  70622. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70623. }
  70624. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70625. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70626. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70627. camera.cameraDirection.addInPlace(this._deltaTransform);
  70628. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70629. camera.cameraRotation.addInPlace(this._vector2);
  70630. }
  70631. };
  70632. FreeCameraGamepadInput.prototype.getClassName = function () {
  70633. return "FreeCameraGamepadInput";
  70634. };
  70635. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70636. return "gamepad";
  70637. };
  70638. __decorate([
  70639. BABYLON.serialize()
  70640. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70641. __decorate([
  70642. BABYLON.serialize()
  70643. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70644. return FreeCameraGamepadInput;
  70645. }());
  70646. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70647. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70648. })(BABYLON || (BABYLON = {}));
  70649. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70650. var BABYLON;
  70651. (function (BABYLON) {
  70652. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70653. function ArcRotateCameraGamepadInput() {
  70654. this.gamepadRotationSensibility = 80;
  70655. this.gamepadMoveSensibility = 40;
  70656. }
  70657. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70658. var _this = this;
  70659. var manager = this.camera.getScene().gamepadManager;
  70660. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70661. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70662. // prioritize XBOX gamepads.
  70663. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70664. _this.gamepad = gamepad;
  70665. }
  70666. }
  70667. });
  70668. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70669. if (_this.gamepad === gamepad) {
  70670. _this.gamepad = null;
  70671. }
  70672. });
  70673. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70674. };
  70675. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70676. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70677. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70678. this.gamepad = null;
  70679. };
  70680. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70681. if (this.gamepad) {
  70682. var camera = this.camera;
  70683. var RSValues = this.gamepad.rightStick;
  70684. if (RSValues) {
  70685. if (RSValues.x != 0) {
  70686. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70687. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70688. camera.inertialAlphaOffset += normalizedRX;
  70689. }
  70690. }
  70691. if (RSValues.y != 0) {
  70692. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70693. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70694. camera.inertialBetaOffset += normalizedRY;
  70695. }
  70696. }
  70697. }
  70698. var LSValues = this.gamepad.leftStick;
  70699. if (LSValues && LSValues.y != 0) {
  70700. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70701. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70702. this.camera.inertialRadiusOffset -= normalizedLY;
  70703. }
  70704. }
  70705. }
  70706. };
  70707. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70708. return "ArcRotateCameraGamepadInput";
  70709. };
  70710. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70711. return "gamepad";
  70712. };
  70713. __decorate([
  70714. BABYLON.serialize()
  70715. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70716. __decorate([
  70717. BABYLON.serialize()
  70718. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70719. return ArcRotateCameraGamepadInput;
  70720. }());
  70721. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70722. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70723. })(BABYLON || (BABYLON = {}));
  70724. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70725. var BABYLON;
  70726. (function (BABYLON) {
  70727. var GamepadManager = /** @class */ (function () {
  70728. function GamepadManager(_scene) {
  70729. var _this = this;
  70730. this._scene = _scene;
  70731. this._babylonGamepads = [];
  70732. this._oneGamepadConnected = false;
  70733. this._isMonitoring = false;
  70734. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70735. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70736. this._gamepadEventSupported = false;
  70737. }
  70738. else {
  70739. this._gamepadEventSupported = 'GamepadEvent' in window;
  70740. this._gamepadSupport = (navigator.getGamepads ||
  70741. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70742. }
  70743. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70744. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70745. for (var i in _this._babylonGamepads) {
  70746. var gamepad = _this._babylonGamepads[i];
  70747. if (gamepad && gamepad._isConnected) {
  70748. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70749. }
  70750. }
  70751. });
  70752. this._onGamepadConnectedEvent = function (evt) {
  70753. var gamepad = evt.gamepad;
  70754. if (gamepad.index in _this._babylonGamepads) {
  70755. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70756. return;
  70757. }
  70758. }
  70759. var newGamepad;
  70760. if (_this._babylonGamepads[gamepad.index]) {
  70761. newGamepad = _this._babylonGamepads[gamepad.index];
  70762. newGamepad.browserGamepad = gamepad;
  70763. newGamepad._isConnected = true;
  70764. }
  70765. else {
  70766. newGamepad = _this._addNewGamepad(gamepad);
  70767. }
  70768. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70769. _this._startMonitoringGamepads();
  70770. };
  70771. this._onGamepadDisconnectedEvent = function (evt) {
  70772. var gamepad = evt.gamepad;
  70773. // Remove the gamepad from the list of gamepads to monitor.
  70774. for (var i in _this._babylonGamepads) {
  70775. if (_this._babylonGamepads[i].index === gamepad.index) {
  70776. var disconnectedGamepad = _this._babylonGamepads[i];
  70777. disconnectedGamepad._isConnected = false;
  70778. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70779. break;
  70780. }
  70781. }
  70782. };
  70783. if (this._gamepadSupport) {
  70784. //first add already-connected gamepads
  70785. this._updateGamepadObjects();
  70786. if (this._babylonGamepads.length) {
  70787. this._startMonitoringGamepads();
  70788. }
  70789. // Checking if the gamepad connected event is supported (like in Firefox)
  70790. if (this._gamepadEventSupported) {
  70791. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70792. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70793. }
  70794. else {
  70795. this._startMonitoringGamepads();
  70796. }
  70797. }
  70798. }
  70799. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70800. get: function () {
  70801. return this._babylonGamepads;
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. GamepadManager.prototype.getGamepadByType = function (type) {
  70807. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70808. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70809. var gamepad = _a[_i];
  70810. if (gamepad && gamepad.type === type) {
  70811. return gamepad;
  70812. }
  70813. }
  70814. return null;
  70815. };
  70816. GamepadManager.prototype.dispose = function () {
  70817. if (this._gamepadEventSupported) {
  70818. if (this._onGamepadConnectedEvent) {
  70819. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70820. }
  70821. if (this._onGamepadDisconnectedEvent) {
  70822. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70823. }
  70824. this._onGamepadConnectedEvent = null;
  70825. this._onGamepadDisconnectedEvent = null;
  70826. }
  70827. this._babylonGamepads.forEach(function (gamepad) {
  70828. gamepad.dispose();
  70829. });
  70830. this.onGamepadConnectedObservable.clear();
  70831. this.onGamepadDisconnectedObservable.clear();
  70832. this._oneGamepadConnected = false;
  70833. this._stopMonitoringGamepads();
  70834. this._babylonGamepads = [];
  70835. };
  70836. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70837. if (!this._oneGamepadConnected) {
  70838. this._oneGamepadConnected = true;
  70839. }
  70840. var newGamepad;
  70841. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70842. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70843. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70844. }
  70845. // if pose is supported, use the (WebVR) pose enabled controller
  70846. else if (gamepad.pose) {
  70847. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70848. }
  70849. else {
  70850. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70851. }
  70852. this._babylonGamepads[newGamepad.index] = newGamepad;
  70853. return newGamepad;
  70854. };
  70855. GamepadManager.prototype._startMonitoringGamepads = function () {
  70856. if (!this._isMonitoring) {
  70857. this._isMonitoring = true;
  70858. //back-comp
  70859. if (!this._scene) {
  70860. this._checkGamepadsStatus();
  70861. }
  70862. }
  70863. };
  70864. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70865. this._isMonitoring = false;
  70866. };
  70867. GamepadManager.prototype._checkGamepadsStatus = function () {
  70868. var _this = this;
  70869. // Hack to be compatible Chrome
  70870. this._updateGamepadObjects();
  70871. for (var i in this._babylonGamepads) {
  70872. var gamepad = this._babylonGamepads[i];
  70873. if (!gamepad || !gamepad.isConnected) {
  70874. continue;
  70875. }
  70876. gamepad.update();
  70877. }
  70878. if (this._isMonitoring && !this._scene) {
  70879. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70880. }
  70881. };
  70882. // This function is called only on Chrome, which does not properly support
  70883. // connection/disconnection events and forces you to recopy again the gamepad object
  70884. GamepadManager.prototype._updateGamepadObjects = function () {
  70885. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70886. for (var i = 0; i < gamepads.length; i++) {
  70887. var gamepad = gamepads[i];
  70888. if (gamepad) {
  70889. if (!this._babylonGamepads[gamepad.index]) {
  70890. var newGamepad = this._addNewGamepad(gamepad);
  70891. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70892. }
  70893. else {
  70894. // Forced to copy again this object for Chrome for unknown reason
  70895. this._babylonGamepads[i].browserGamepad = gamepad;
  70896. if (!this._babylonGamepads[i].isConnected) {
  70897. this._babylonGamepads[i]._isConnected = true;
  70898. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70899. }
  70900. }
  70901. }
  70902. }
  70903. };
  70904. return GamepadManager;
  70905. }());
  70906. BABYLON.GamepadManager = GamepadManager;
  70907. })(BABYLON || (BABYLON = {}));
  70908. //# sourceMappingURL=babylon.gamepadManager.js.map
  70909. var BABYLON;
  70910. (function (BABYLON) {
  70911. var StickValues = /** @class */ (function () {
  70912. function StickValues(x, y) {
  70913. this.x = x;
  70914. this.y = y;
  70915. }
  70916. return StickValues;
  70917. }());
  70918. BABYLON.StickValues = StickValues;
  70919. var Gamepad = /** @class */ (function () {
  70920. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70921. if (leftStickX === void 0) { leftStickX = 0; }
  70922. if (leftStickY === void 0) { leftStickY = 1; }
  70923. if (rightStickX === void 0) { rightStickX = 2; }
  70924. if (rightStickY === void 0) { rightStickY = 3; }
  70925. this.id = id;
  70926. this.index = index;
  70927. this.browserGamepad = browserGamepad;
  70928. this._isConnected = true;
  70929. this._invertLeftStickY = false;
  70930. this.type = Gamepad.GAMEPAD;
  70931. this._leftStickAxisX = leftStickX;
  70932. this._leftStickAxisY = leftStickY;
  70933. this._rightStickAxisX = rightStickX;
  70934. this._rightStickAxisY = rightStickY;
  70935. if (this.browserGamepad.axes.length >= 2) {
  70936. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70937. }
  70938. if (this.browserGamepad.axes.length >= 4) {
  70939. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70940. }
  70941. }
  70942. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70943. get: function () {
  70944. return this._isConnected;
  70945. },
  70946. enumerable: true,
  70947. configurable: true
  70948. });
  70949. Gamepad.prototype.onleftstickchanged = function (callback) {
  70950. this._onleftstickchanged = callback;
  70951. };
  70952. Gamepad.prototype.onrightstickchanged = function (callback) {
  70953. this._onrightstickchanged = callback;
  70954. };
  70955. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70956. get: function () {
  70957. return this._leftStick;
  70958. },
  70959. set: function (newValues) {
  70960. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70961. this._onleftstickchanged(newValues);
  70962. }
  70963. this._leftStick = newValues;
  70964. },
  70965. enumerable: true,
  70966. configurable: true
  70967. });
  70968. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70969. get: function () {
  70970. return this._rightStick;
  70971. },
  70972. set: function (newValues) {
  70973. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70974. this._onrightstickchanged(newValues);
  70975. }
  70976. this._rightStick = newValues;
  70977. },
  70978. enumerable: true,
  70979. configurable: true
  70980. });
  70981. Gamepad.prototype.update = function () {
  70982. if (this._leftStick) {
  70983. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70984. if (this._invertLeftStickY) {
  70985. this.leftStick.y *= -1;
  70986. }
  70987. }
  70988. if (this._rightStick) {
  70989. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70990. }
  70991. };
  70992. Gamepad.prototype.dispose = function () {
  70993. };
  70994. Gamepad.GAMEPAD = 0;
  70995. Gamepad.GENERIC = 1;
  70996. Gamepad.XBOX = 2;
  70997. Gamepad.POSE_ENABLED = 3;
  70998. return Gamepad;
  70999. }());
  71000. BABYLON.Gamepad = Gamepad;
  71001. var GenericPad = /** @class */ (function (_super) {
  71002. __extends(GenericPad, _super);
  71003. function GenericPad(id, index, browserGamepad) {
  71004. var _this = _super.call(this, id, index, browserGamepad) || this;
  71005. _this.onButtonDownObservable = new BABYLON.Observable();
  71006. _this.onButtonUpObservable = new BABYLON.Observable();
  71007. _this.type = Gamepad.GENERIC;
  71008. _this._buttons = new Array(browserGamepad.buttons.length);
  71009. return _this;
  71010. }
  71011. GenericPad.prototype.onbuttondown = function (callback) {
  71012. this._onbuttondown = callback;
  71013. };
  71014. GenericPad.prototype.onbuttonup = function (callback) {
  71015. this._onbuttonup = callback;
  71016. };
  71017. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71018. if (newValue !== currentValue) {
  71019. if (newValue === 1) {
  71020. if (this._onbuttondown) {
  71021. this._onbuttondown(buttonIndex);
  71022. }
  71023. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71024. }
  71025. if (newValue === 0) {
  71026. if (this._onbuttonup) {
  71027. this._onbuttonup(buttonIndex);
  71028. }
  71029. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71030. }
  71031. }
  71032. return newValue;
  71033. };
  71034. GenericPad.prototype.update = function () {
  71035. _super.prototype.update.call(this);
  71036. for (var index = 0; index < this._buttons.length; index++) {
  71037. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71038. }
  71039. };
  71040. GenericPad.prototype.dispose = function () {
  71041. _super.prototype.dispose.call(this);
  71042. this.onButtonDownObservable.clear();
  71043. this.onButtonUpObservable.clear();
  71044. };
  71045. return GenericPad;
  71046. }(Gamepad));
  71047. BABYLON.GenericPad = GenericPad;
  71048. })(BABYLON || (BABYLON = {}));
  71049. //# sourceMappingURL=babylon.gamepad.js.map
  71050. var BABYLON;
  71051. (function (BABYLON) {
  71052. /**
  71053. * Defines supported buttons for XBox360 compatible gamepads
  71054. */
  71055. var Xbox360Button;
  71056. (function (Xbox360Button) {
  71057. /** A */
  71058. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71059. /** B */
  71060. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71061. /** X */
  71062. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71063. /** Y */
  71064. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71065. /** Start */
  71066. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71067. /** Back */
  71068. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71069. /** Left button */
  71070. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71071. /** Right button */
  71072. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71073. /** Left stick */
  71074. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71075. /** Right stick */
  71076. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71077. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71078. /** Defines values for XBox360 DPad */
  71079. var Xbox360Dpad;
  71080. (function (Xbox360Dpad) {
  71081. /** Up */
  71082. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71083. /** Down */
  71084. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71085. /** Left */
  71086. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71087. /** Right */
  71088. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71089. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71090. /**
  71091. * Defines a XBox360 gamepad
  71092. */
  71093. var Xbox360Pad = /** @class */ (function (_super) {
  71094. __extends(Xbox360Pad, _super);
  71095. /**
  71096. * Creates a new XBox360 gamepad object
  71097. * @param id defines the id of this gamepad
  71098. * @param index defines its index
  71099. * @param gamepad defines the internal HTML gamepad object
  71100. * @param xboxOne defines if it is a XBox One gamepad
  71101. */
  71102. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71103. if (xboxOne === void 0) { xboxOne = false; }
  71104. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71105. _this._leftTrigger = 0;
  71106. _this._rightTrigger = 0;
  71107. /** Observable raised when a button is pressed */
  71108. _this.onButtonDownObservable = new BABYLON.Observable();
  71109. /** Observable raised when a button is released */
  71110. _this.onButtonUpObservable = new BABYLON.Observable();
  71111. /** Observable raised when a pad is pressed */
  71112. _this.onPadDownObservable = new BABYLON.Observable();
  71113. /** Observable raised when a pad is released */
  71114. _this.onPadUpObservable = new BABYLON.Observable();
  71115. _this._buttonA = 0;
  71116. _this._buttonB = 0;
  71117. _this._buttonX = 0;
  71118. _this._buttonY = 0;
  71119. _this._buttonBack = 0;
  71120. _this._buttonStart = 0;
  71121. _this._buttonLB = 0;
  71122. _this._buttonRB = 0;
  71123. _this._buttonLeftStick = 0;
  71124. _this._buttonRightStick = 0;
  71125. _this._dPadUp = 0;
  71126. _this._dPadDown = 0;
  71127. _this._dPadLeft = 0;
  71128. _this._dPadRight = 0;
  71129. _this._isXboxOnePad = false;
  71130. _this.type = BABYLON.Gamepad.XBOX;
  71131. _this._isXboxOnePad = xboxOne;
  71132. return _this;
  71133. }
  71134. /**
  71135. * Defines the callback to call when left trigger is pressed
  71136. * @param callback defines the callback to use
  71137. */
  71138. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71139. this._onlefttriggerchanged = callback;
  71140. };
  71141. /**
  71142. * Defines the callback to call when right trigger is pressed
  71143. * @param callback defines the callback to use
  71144. */
  71145. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71146. this._onrighttriggerchanged = callback;
  71147. };
  71148. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71149. /**
  71150. * Gets or sets left trigger value
  71151. */
  71152. get: function () {
  71153. return this._leftTrigger;
  71154. },
  71155. set: function (newValue) {
  71156. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71157. this._onlefttriggerchanged(newValue);
  71158. }
  71159. this._leftTrigger = newValue;
  71160. },
  71161. enumerable: true,
  71162. configurable: true
  71163. });
  71164. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71165. /**
  71166. * Gets or sets right trigger value
  71167. */
  71168. get: function () {
  71169. return this._rightTrigger;
  71170. },
  71171. set: function (newValue) {
  71172. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71173. this._onrighttriggerchanged(newValue);
  71174. }
  71175. this._rightTrigger = newValue;
  71176. },
  71177. enumerable: true,
  71178. configurable: true
  71179. });
  71180. /**
  71181. * Defines the callback to call when a button is pressed
  71182. * @param callback defines the callback to use
  71183. */
  71184. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71185. this._onbuttondown = callback;
  71186. };
  71187. /**
  71188. * Defines the callback to call when a button is released
  71189. * @param callback defines the callback to use
  71190. */
  71191. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71192. this._onbuttonup = callback;
  71193. };
  71194. /**
  71195. * Defines the callback to call when a pad is pressed
  71196. * @param callback defines the callback to use
  71197. */
  71198. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71199. this._ondpaddown = callback;
  71200. };
  71201. /**
  71202. * Defines the callback to call when a pad is released
  71203. * @param callback defines the callback to use
  71204. */
  71205. Xbox360Pad.prototype.ondpadup = function (callback) {
  71206. this._ondpadup = callback;
  71207. };
  71208. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71209. if (newValue !== currentValue) {
  71210. if (newValue === 1) {
  71211. if (this._onbuttondown) {
  71212. this._onbuttondown(buttonType);
  71213. }
  71214. this.onButtonDownObservable.notifyObservers(buttonType);
  71215. }
  71216. if (newValue === 0) {
  71217. if (this._onbuttonup) {
  71218. this._onbuttonup(buttonType);
  71219. }
  71220. this.onButtonUpObservable.notifyObservers(buttonType);
  71221. }
  71222. }
  71223. return newValue;
  71224. };
  71225. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71226. if (newValue !== currentValue) {
  71227. if (newValue === 1) {
  71228. if (this._ondpaddown) {
  71229. this._ondpaddown(buttonType);
  71230. }
  71231. this.onPadDownObservable.notifyObservers(buttonType);
  71232. }
  71233. if (newValue === 0) {
  71234. if (this._ondpadup) {
  71235. this._ondpadup(buttonType);
  71236. }
  71237. this.onPadUpObservable.notifyObservers(buttonType);
  71238. }
  71239. }
  71240. return newValue;
  71241. };
  71242. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71243. /** Gets or sets value of A button */
  71244. get: function () {
  71245. return this._buttonA;
  71246. },
  71247. set: function (value) {
  71248. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71249. },
  71250. enumerable: true,
  71251. configurable: true
  71252. });
  71253. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71254. /** Gets or sets value of B button */
  71255. get: function () {
  71256. return this._buttonB;
  71257. },
  71258. set: function (value) {
  71259. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71260. },
  71261. enumerable: true,
  71262. configurable: true
  71263. });
  71264. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71265. /** Gets or sets value of X button */
  71266. get: function () {
  71267. return this._buttonX;
  71268. },
  71269. set: function (value) {
  71270. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71271. },
  71272. enumerable: true,
  71273. configurable: true
  71274. });
  71275. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71276. /** Gets or sets value of Y button */
  71277. get: function () {
  71278. return this._buttonY;
  71279. },
  71280. set: function (value) {
  71281. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71282. },
  71283. enumerable: true,
  71284. configurable: true
  71285. });
  71286. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71287. /** Gets or sets value of Start button */
  71288. get: function () {
  71289. return this._buttonStart;
  71290. },
  71291. set: function (value) {
  71292. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71293. },
  71294. enumerable: true,
  71295. configurable: true
  71296. });
  71297. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71298. /** Gets or sets value of Back button */
  71299. get: function () {
  71300. return this._buttonBack;
  71301. },
  71302. set: function (value) {
  71303. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71304. },
  71305. enumerable: true,
  71306. configurable: true
  71307. });
  71308. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71309. /** Gets or sets value of Left button */
  71310. get: function () {
  71311. return this._buttonLB;
  71312. },
  71313. set: function (value) {
  71314. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71315. },
  71316. enumerable: true,
  71317. configurable: true
  71318. });
  71319. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71320. /** Gets or sets value of Right button */
  71321. get: function () {
  71322. return this._buttonRB;
  71323. },
  71324. set: function (value) {
  71325. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71326. },
  71327. enumerable: true,
  71328. configurable: true
  71329. });
  71330. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71331. /** Gets or sets value of left stick */
  71332. get: function () {
  71333. return this._buttonLeftStick;
  71334. },
  71335. set: function (value) {
  71336. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71337. },
  71338. enumerable: true,
  71339. configurable: true
  71340. });
  71341. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71342. /** Gets or sets value of right stick */
  71343. get: function () {
  71344. return this._buttonRightStick;
  71345. },
  71346. set: function (value) {
  71347. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71348. },
  71349. enumerable: true,
  71350. configurable: true
  71351. });
  71352. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71353. /** Gets or sets value of DPad up */
  71354. get: function () {
  71355. return this._dPadUp;
  71356. },
  71357. set: function (value) {
  71358. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71359. },
  71360. enumerable: true,
  71361. configurable: true
  71362. });
  71363. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71364. /** Gets or sets value of DPad down */
  71365. get: function () {
  71366. return this._dPadDown;
  71367. },
  71368. set: function (value) {
  71369. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71370. },
  71371. enumerable: true,
  71372. configurable: true
  71373. });
  71374. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71375. /** Gets or sets value of DPad left */
  71376. get: function () {
  71377. return this._dPadLeft;
  71378. },
  71379. set: function (value) {
  71380. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71381. },
  71382. enumerable: true,
  71383. configurable: true
  71384. });
  71385. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71386. /** Gets or sets value of DPad right */
  71387. get: function () {
  71388. return this._dPadRight;
  71389. },
  71390. set: function (value) {
  71391. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71392. },
  71393. enumerable: true,
  71394. configurable: true
  71395. });
  71396. /**
  71397. * Force the gamepad to synchronize with device values
  71398. */
  71399. Xbox360Pad.prototype.update = function () {
  71400. _super.prototype.update.call(this);
  71401. if (this._isXboxOnePad) {
  71402. this.buttonA = this.browserGamepad.buttons[0].value;
  71403. this.buttonB = this.browserGamepad.buttons[1].value;
  71404. this.buttonX = this.browserGamepad.buttons[2].value;
  71405. this.buttonY = this.browserGamepad.buttons[3].value;
  71406. this.buttonLB = this.browserGamepad.buttons[4].value;
  71407. this.buttonRB = this.browserGamepad.buttons[5].value;
  71408. this.leftTrigger = this.browserGamepad.axes[2];
  71409. this.rightTrigger = this.browserGamepad.axes[5];
  71410. this.buttonBack = this.browserGamepad.buttons[9].value;
  71411. this.buttonStart = this.browserGamepad.buttons[8].value;
  71412. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71413. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71414. this.dPadUp = this.browserGamepad.buttons[11].value;
  71415. this.dPadDown = this.browserGamepad.buttons[12].value;
  71416. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71417. this.dPadRight = this.browserGamepad.buttons[14].value;
  71418. }
  71419. else {
  71420. this.buttonA = this.browserGamepad.buttons[0].value;
  71421. this.buttonB = this.browserGamepad.buttons[1].value;
  71422. this.buttonX = this.browserGamepad.buttons[2].value;
  71423. this.buttonY = this.browserGamepad.buttons[3].value;
  71424. this.buttonLB = this.browserGamepad.buttons[4].value;
  71425. this.buttonRB = this.browserGamepad.buttons[5].value;
  71426. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71427. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71428. this.buttonBack = this.browserGamepad.buttons[8].value;
  71429. this.buttonStart = this.browserGamepad.buttons[9].value;
  71430. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71431. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71432. this.dPadUp = this.browserGamepad.buttons[12].value;
  71433. this.dPadDown = this.browserGamepad.buttons[13].value;
  71434. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71435. this.dPadRight = this.browserGamepad.buttons[15].value;
  71436. }
  71437. };
  71438. Xbox360Pad.prototype.dispose = function () {
  71439. _super.prototype.dispose.call(this);
  71440. this.onButtonDownObservable.clear();
  71441. this.onButtonUpObservable.clear();
  71442. this.onPadDownObservable.clear();
  71443. this.onPadUpObservable.clear();
  71444. };
  71445. return Xbox360Pad;
  71446. }(BABYLON.Gamepad));
  71447. BABYLON.Xbox360Pad = Xbox360Pad;
  71448. })(BABYLON || (BABYLON = {}));
  71449. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71450. var BABYLON;
  71451. (function (BABYLON) {
  71452. /**
  71453. * Defines the types of pose enabled controllers that are supported
  71454. */
  71455. var PoseEnabledControllerType;
  71456. (function (PoseEnabledControllerType) {
  71457. /**
  71458. * HTC Vive
  71459. */
  71460. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71461. /**
  71462. * Oculus Rift
  71463. */
  71464. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71465. /**
  71466. * Windows mixed reality
  71467. */
  71468. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71469. /**
  71470. * Samsung gear VR
  71471. */
  71472. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71473. /**
  71474. * Google Daydream
  71475. */
  71476. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71477. /**
  71478. * Generic
  71479. */
  71480. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71481. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71482. /**
  71483. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71484. */
  71485. var PoseEnabledControllerHelper = /** @class */ (function () {
  71486. function PoseEnabledControllerHelper() {
  71487. }
  71488. /**
  71489. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71490. * @param vrGamepad the gamepad to initialized
  71491. * @returns a vr controller of the type the gamepad identified as
  71492. */
  71493. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71494. // Oculus Touch
  71495. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71496. return new BABYLON.OculusTouchController(vrGamepad);
  71497. }
  71498. // Windows Mixed Reality controllers
  71499. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71500. return new BABYLON.WindowsMotionController(vrGamepad);
  71501. }
  71502. // HTC Vive
  71503. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71504. return new BABYLON.ViveController(vrGamepad);
  71505. }
  71506. // Samsung/Oculus Gear VR or Oculus Go
  71507. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71508. return new BABYLON.GearVRController(vrGamepad);
  71509. }
  71510. // Google Daydream
  71511. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71512. return new BABYLON.DaydreamController(vrGamepad);
  71513. }
  71514. // Generic
  71515. else {
  71516. return new BABYLON.GenericController(vrGamepad);
  71517. }
  71518. };
  71519. return PoseEnabledControllerHelper;
  71520. }());
  71521. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71522. /**
  71523. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71524. */
  71525. var PoseEnabledController = /** @class */ (function (_super) {
  71526. __extends(PoseEnabledController, _super);
  71527. /**
  71528. * Creates a new PoseEnabledController from a gamepad
  71529. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71530. */
  71531. function PoseEnabledController(browserGamepad) {
  71532. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71533. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71534. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71535. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71536. /**
  71537. * The device position in babylon space
  71538. */
  71539. _this.devicePosition = BABYLON.Vector3.Zero();
  71540. /**
  71541. * The device rotation in babylon space
  71542. */
  71543. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71544. /**
  71545. * The scale factor of the device in babylon space
  71546. */
  71547. _this.deviceScaleFactor = 1;
  71548. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71549. /**
  71550. * Internal, matrix used to convert room space to babylon space
  71551. */
  71552. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71553. /**
  71554. * Node to be used when casting a ray from the controller
  71555. */
  71556. _this._pointingPoseNode = null;
  71557. _this._workingMatrix = BABYLON.Matrix.Identity();
  71558. /**
  71559. * @hidden
  71560. */
  71561. _this._meshAttachedObservable = new BABYLON.Observable();
  71562. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71563. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71564. _this.position = BABYLON.Vector3.Zero();
  71565. _this.rotationQuaternion = new BABYLON.Quaternion();
  71566. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71567. _this._calculatedRotation = new BABYLON.Quaternion();
  71568. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71569. return _this;
  71570. }
  71571. /**
  71572. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71573. */
  71574. PoseEnabledController.prototype.update = function () {
  71575. _super.prototype.update.call(this);
  71576. var pose = this.browserGamepad.pose;
  71577. this.updateFromDevice(pose);
  71578. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71579. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71580. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71581. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71582. if (this._mesh) {
  71583. this._mesh.position.copyFrom(this.devicePosition);
  71584. if (this._mesh.rotationQuaternion) {
  71585. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71586. }
  71587. }
  71588. };
  71589. /**
  71590. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71591. * @param poseData raw pose fromthe device
  71592. */
  71593. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71594. if (poseData) {
  71595. this.rawPose = poseData;
  71596. if (poseData.position) {
  71597. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71598. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71599. this._deviceRoomPosition.z *= -1;
  71600. }
  71601. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71602. this._calculatedPosition.addInPlace(this.position);
  71603. }
  71604. var pose = this.rawPose;
  71605. if (poseData.orientation && pose.orientation) {
  71606. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71607. if (this._mesh) {
  71608. if (this._mesh.getScene().useRightHandedSystem) {
  71609. this._deviceRoomRotationQuaternion.z *= -1;
  71610. this._deviceRoomRotationQuaternion.w *= -1;
  71611. }
  71612. else {
  71613. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71614. }
  71615. }
  71616. // if the camera is set, rotate to the camera's rotation
  71617. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71618. }
  71619. }
  71620. };
  71621. /**
  71622. * Attaches a mesh to the controller
  71623. * @param mesh the mesh to be attached
  71624. */
  71625. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71626. if (this._mesh) {
  71627. this._mesh.parent = null;
  71628. }
  71629. this._mesh = mesh;
  71630. if (this._poseControlledCamera) {
  71631. this._mesh.parent = this._poseControlledCamera;
  71632. }
  71633. if (!this._mesh.rotationQuaternion) {
  71634. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71635. }
  71636. this._meshAttachedObservable.notifyObservers(mesh);
  71637. };
  71638. /**
  71639. * Attaches the controllers mesh to a camera
  71640. * @param camera the camera the mesh should be attached to
  71641. */
  71642. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71643. this._poseControlledCamera = camera;
  71644. if (this._mesh) {
  71645. this._mesh.parent = this._poseControlledCamera;
  71646. }
  71647. };
  71648. /**
  71649. * Disposes of the controller
  71650. */
  71651. PoseEnabledController.prototype.dispose = function () {
  71652. if (this._mesh) {
  71653. this._mesh.dispose();
  71654. }
  71655. this._mesh = null;
  71656. _super.prototype.dispose.call(this);
  71657. };
  71658. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71659. /**
  71660. * The mesh that is attached to the controller
  71661. */
  71662. get: function () {
  71663. return this._mesh;
  71664. },
  71665. enumerable: true,
  71666. configurable: true
  71667. });
  71668. /**
  71669. * Gets the ray of the controller in the direction the controller is pointing
  71670. * @param length the length the resulting ray should be
  71671. * @returns a ray in the direction the controller is pointing
  71672. */
  71673. PoseEnabledController.prototype.getForwardRay = function (length) {
  71674. if (length === void 0) { length = 100; }
  71675. if (!this.mesh) {
  71676. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71677. }
  71678. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71679. var origin = m.getTranslation();
  71680. var forward = new BABYLON.Vector3(0, 0, -1);
  71681. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71682. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71683. return new BABYLON.Ray(origin, direction, length);
  71684. };
  71685. /**
  71686. * Name of the child mesh that can be used to cast a ray from the controller
  71687. */
  71688. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71689. return PoseEnabledController;
  71690. }(BABYLON.Gamepad));
  71691. BABYLON.PoseEnabledController = PoseEnabledController;
  71692. })(BABYLON || (BABYLON = {}));
  71693. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71694. var BABYLON;
  71695. (function (BABYLON) {
  71696. /**
  71697. * Defines the WebVRController object that represents controllers tracked in 3D space
  71698. */
  71699. var WebVRController = /** @class */ (function (_super) {
  71700. __extends(WebVRController, _super);
  71701. /**
  71702. * Creates a new WebVRController from a gamepad
  71703. * @param vrGamepad the gamepad that the WebVRController should be created from
  71704. */
  71705. function WebVRController(vrGamepad) {
  71706. var _this = _super.call(this, vrGamepad) || this;
  71707. // Observables
  71708. /**
  71709. * Fired when the trigger state has changed
  71710. */
  71711. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71712. /**
  71713. * Fired when the main button state has changed
  71714. */
  71715. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71716. /**
  71717. * Fired when the secondary button state has changed
  71718. */
  71719. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71720. /**
  71721. * Fired when the pad state has changed
  71722. */
  71723. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71724. /**
  71725. * Fired when controllers stick values have changed
  71726. */
  71727. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71728. /**
  71729. * X and Y axis corrisponding to the controllers joystick
  71730. */
  71731. _this.pad = { x: 0, y: 0 };
  71732. // avoid GC, store state in a tmp object
  71733. _this._changes = {
  71734. pressChanged: false,
  71735. touchChanged: false,
  71736. valueChanged: false,
  71737. changed: false
  71738. };
  71739. _this._buttons = new Array(vrGamepad.buttons.length);
  71740. _this.hand = vrGamepad.hand;
  71741. return _this;
  71742. }
  71743. /**
  71744. * Fired when a controller button's state has changed
  71745. * @param callback the callback containing the button that was modified
  71746. */
  71747. WebVRController.prototype.onButtonStateChange = function (callback) {
  71748. this._onButtonStateChange = callback;
  71749. };
  71750. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71751. /**
  71752. * The default controller model for the controller
  71753. */
  71754. get: function () {
  71755. return this._defaultModel;
  71756. },
  71757. enumerable: true,
  71758. configurable: true
  71759. });
  71760. /**
  71761. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71762. */
  71763. WebVRController.prototype.update = function () {
  71764. _super.prototype.update.call(this);
  71765. for (var index = 0; index < this._buttons.length; index++) {
  71766. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71767. }
  71768. ;
  71769. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71770. this.pad.x = this.leftStick.x;
  71771. this.pad.y = this.leftStick.y;
  71772. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71773. }
  71774. };
  71775. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71776. if (!newState) {
  71777. newState = {
  71778. pressed: false,
  71779. touched: false,
  71780. value: 0
  71781. };
  71782. }
  71783. if (!currentState) {
  71784. this._buttons[buttonIndex] = {
  71785. pressed: newState.pressed,
  71786. touched: newState.touched,
  71787. value: newState.value
  71788. };
  71789. return;
  71790. }
  71791. this._checkChanges(newState, currentState);
  71792. if (this._changes.changed) {
  71793. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71794. this._handleButtonChange(buttonIndex, newState, this._changes);
  71795. }
  71796. this._buttons[buttonIndex].pressed = newState.pressed;
  71797. this._buttons[buttonIndex].touched = newState.touched;
  71798. // oculus triggers are never 0, thou not touched.
  71799. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71800. };
  71801. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71802. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71803. this._changes.touchChanged = newState.touched !== currentState.touched;
  71804. this._changes.valueChanged = newState.value !== currentState.value;
  71805. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71806. return this._changes;
  71807. };
  71808. /**
  71809. * Disposes of th webVRCOntroller
  71810. */
  71811. WebVRController.prototype.dispose = function () {
  71812. _super.prototype.dispose.call(this);
  71813. this.onTriggerStateChangedObservable.clear();
  71814. this.onMainButtonStateChangedObservable.clear();
  71815. this.onSecondaryButtonStateChangedObservable.clear();
  71816. this.onPadStateChangedObservable.clear();
  71817. this.onPadValuesChangedObservable.clear();
  71818. };
  71819. return WebVRController;
  71820. }(BABYLON.PoseEnabledController));
  71821. BABYLON.WebVRController = WebVRController;
  71822. })(BABYLON || (BABYLON = {}));
  71823. //# sourceMappingURL=babylon.webVRController.js.map
  71824. var BABYLON;
  71825. (function (BABYLON) {
  71826. /**
  71827. * Oculus Touch Controller
  71828. */
  71829. var OculusTouchController = /** @class */ (function (_super) {
  71830. __extends(OculusTouchController, _super);
  71831. /**
  71832. * Creates a new OculusTouchController from a gamepad
  71833. * @param vrGamepad the gamepad that the controller should be created from
  71834. */
  71835. function OculusTouchController(vrGamepad) {
  71836. var _this = _super.call(this, vrGamepad) || this;
  71837. /**
  71838. * Fired when the secondary trigger on this controller is modified
  71839. */
  71840. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71841. /**
  71842. * Fired when the thumb rest on this controller is modified
  71843. */
  71844. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71845. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71846. return _this;
  71847. }
  71848. /**
  71849. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71850. * @param scene scene in which to add meshes
  71851. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71852. */
  71853. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71854. var _this = this;
  71855. var meshName;
  71856. // Hand
  71857. if (this.hand === 'left') {
  71858. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71859. }
  71860. else { // Right is the default if no hand is specified
  71861. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71862. }
  71863. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71864. /*
  71865. Parent Mesh name: oculus_touch_left
  71866. - body
  71867. - trigger
  71868. - thumbstick
  71869. - grip
  71870. - button_y
  71871. - button_x
  71872. - button_enter
  71873. */
  71874. _this._defaultModel = newMeshes[1];
  71875. _this.attachToMesh(_this._defaultModel);
  71876. if (meshLoaded) {
  71877. meshLoaded(_this._defaultModel);
  71878. }
  71879. });
  71880. };
  71881. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71882. /**
  71883. * Fired when the A button on this controller is modified
  71884. */
  71885. get: function () {
  71886. if (this.hand === 'right') {
  71887. return this.onMainButtonStateChangedObservable;
  71888. }
  71889. else {
  71890. throw new Error('No A button on left hand');
  71891. }
  71892. },
  71893. enumerable: true,
  71894. configurable: true
  71895. });
  71896. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71897. /**
  71898. * Fired when the B button on this controller is modified
  71899. */
  71900. get: function () {
  71901. if (this.hand === 'right') {
  71902. return this.onSecondaryButtonStateChangedObservable;
  71903. }
  71904. else {
  71905. throw new Error('No B button on left hand');
  71906. }
  71907. },
  71908. enumerable: true,
  71909. configurable: true
  71910. });
  71911. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71912. /**
  71913. * Fired when the X button on this controller is modified
  71914. */
  71915. get: function () {
  71916. if (this.hand === 'left') {
  71917. return this.onMainButtonStateChangedObservable;
  71918. }
  71919. else {
  71920. throw new Error('No X button on right hand');
  71921. }
  71922. },
  71923. enumerable: true,
  71924. configurable: true
  71925. });
  71926. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71927. /**
  71928. * Fired when the Y button on this controller is modified
  71929. */
  71930. get: function () {
  71931. if (this.hand === 'left') {
  71932. return this.onSecondaryButtonStateChangedObservable;
  71933. }
  71934. else {
  71935. throw new Error('No Y button on right hand');
  71936. }
  71937. },
  71938. enumerable: true,
  71939. configurable: true
  71940. });
  71941. /**
  71942. * Called once for each button that changed state since the last frame
  71943. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71944. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71945. * 2) secondary trigger (same)
  71946. * 3) A (right) X (left), touch, pressed = value
  71947. * 4) B / Y
  71948. * 5) thumb rest
  71949. * @param buttonIdx Which button index changed
  71950. * @param state New state of the button
  71951. * @param changes Which properties on the state changed since last frame
  71952. */
  71953. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71954. var notifyObject = state; //{ state: state, changes: changes };
  71955. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71956. switch (buttonIdx) {
  71957. case 0:
  71958. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71959. return;
  71960. case 1: // index trigger
  71961. if (this._defaultModel) {
  71962. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71963. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71964. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71965. }
  71966. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71967. return;
  71968. case 2: // secondary trigger
  71969. if (this._defaultModel) {
  71970. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71971. }
  71972. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71973. return;
  71974. case 3:
  71975. if (this._defaultModel) {
  71976. if (notifyObject.pressed) {
  71977. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71978. }
  71979. else {
  71980. (this._defaultModel.getChildren()[1]).position.y = 0;
  71981. }
  71982. }
  71983. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71984. return;
  71985. case 4:
  71986. if (this._defaultModel) {
  71987. if (notifyObject.pressed) {
  71988. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71989. }
  71990. else {
  71991. (this._defaultModel.getChildren()[2]).position.y = 0;
  71992. }
  71993. }
  71994. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71995. return;
  71996. case 5:
  71997. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71998. return;
  71999. }
  72000. };
  72001. /**
  72002. * Base Url for the controller model.
  72003. */
  72004. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72005. /**
  72006. * File name for the left controller model.
  72007. */
  72008. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72009. /**
  72010. * File name for the right controller model.
  72011. */
  72012. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72013. return OculusTouchController;
  72014. }(BABYLON.WebVRController));
  72015. BABYLON.OculusTouchController = OculusTouchController;
  72016. })(BABYLON || (BABYLON = {}));
  72017. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72018. var BABYLON;
  72019. (function (BABYLON) {
  72020. /**
  72021. * Vive Controller
  72022. */
  72023. var ViveController = /** @class */ (function (_super) {
  72024. __extends(ViveController, _super);
  72025. /**
  72026. * Creates a new ViveController from a gamepad
  72027. * @param vrGamepad the gamepad that the controller should be created from
  72028. */
  72029. function ViveController(vrGamepad) {
  72030. var _this = _super.call(this, vrGamepad) || this;
  72031. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72032. _this._invertLeftStickY = true;
  72033. return _this;
  72034. }
  72035. /**
  72036. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72037. * @param scene scene in which to add meshes
  72038. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72039. */
  72040. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72041. var _this = this;
  72042. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72043. /*
  72044. Parent Mesh name: ViveWand
  72045. - body
  72046. - r_gripper
  72047. - l_gripper
  72048. - menu_button
  72049. - system_button
  72050. - trackpad
  72051. - trigger
  72052. - LED
  72053. */
  72054. _this._defaultModel = newMeshes[1];
  72055. _this.attachToMesh(_this._defaultModel);
  72056. if (meshLoaded) {
  72057. meshLoaded(_this._defaultModel);
  72058. }
  72059. });
  72060. };
  72061. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72062. /**
  72063. * Fired when the left button on this controller is modified
  72064. */
  72065. get: function () {
  72066. return this.onMainButtonStateChangedObservable;
  72067. },
  72068. enumerable: true,
  72069. configurable: true
  72070. });
  72071. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72072. /**
  72073. * Fired when the right button on this controller is modified
  72074. */
  72075. get: function () {
  72076. return this.onMainButtonStateChangedObservable;
  72077. },
  72078. enumerable: true,
  72079. configurable: true
  72080. });
  72081. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72082. /**
  72083. * Fired when the menu button on this controller is modified
  72084. */
  72085. get: function () {
  72086. return this.onSecondaryButtonStateChangedObservable;
  72087. },
  72088. enumerable: true,
  72089. configurable: true
  72090. });
  72091. /**
  72092. * Called once for each button that changed state since the last frame
  72093. * Vive mapping:
  72094. * 0: touchpad
  72095. * 1: trigger
  72096. * 2: left AND right buttons
  72097. * 3: menu button
  72098. * @param buttonIdx Which button index changed
  72099. * @param state New state of the button
  72100. * @param changes Which properties on the state changed since last frame
  72101. */
  72102. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72103. var notifyObject = state; //{ state: state, changes: changes };
  72104. switch (buttonIdx) {
  72105. case 0:
  72106. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72107. return;
  72108. case 1: // index trigger
  72109. if (this._defaultModel) {
  72110. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72111. }
  72112. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72113. return;
  72114. case 2: // left AND right button
  72115. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72116. return;
  72117. case 3:
  72118. if (this._defaultModel) {
  72119. if (notifyObject.pressed) {
  72120. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72121. }
  72122. else {
  72123. (this._defaultModel.getChildren()[2]).position.y = 0;
  72124. }
  72125. }
  72126. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72127. return;
  72128. }
  72129. };
  72130. /**
  72131. * Base Url for the controller model.
  72132. */
  72133. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72134. /**
  72135. * File name for the controller model.
  72136. */
  72137. ViveController.MODEL_FILENAME = 'wand.babylon';
  72138. return ViveController;
  72139. }(BABYLON.WebVRController));
  72140. BABYLON.ViveController = ViveController;
  72141. })(BABYLON || (BABYLON = {}));
  72142. //# sourceMappingURL=babylon.viveController.js.map
  72143. var BABYLON;
  72144. (function (BABYLON) {
  72145. /**
  72146. * Generic Controller
  72147. */
  72148. var GenericController = /** @class */ (function (_super) {
  72149. __extends(GenericController, _super);
  72150. /**
  72151. * Creates a new GenericController from a gamepad
  72152. * @param vrGamepad the gamepad that the controller should be created from
  72153. */
  72154. function GenericController(vrGamepad) {
  72155. return _super.call(this, vrGamepad) || this;
  72156. }
  72157. /**
  72158. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72159. * @param scene scene in which to add meshes
  72160. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72161. */
  72162. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72163. var _this = this;
  72164. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72165. _this._defaultModel = newMeshes[1];
  72166. _this.attachToMesh(_this._defaultModel);
  72167. if (meshLoaded) {
  72168. meshLoaded(_this._defaultModel);
  72169. }
  72170. });
  72171. };
  72172. /**
  72173. * Called once for each button that changed state since the last frame
  72174. * @param buttonIdx Which button index changed
  72175. * @param state New state of the button
  72176. * @param changes Which properties on the state changed since last frame
  72177. */
  72178. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72179. console.log("Button id: " + buttonIdx + "state: ");
  72180. console.dir(state);
  72181. };
  72182. /**
  72183. * Base Url for the controller model.
  72184. */
  72185. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72186. /**
  72187. * File name for the controller model.
  72188. */
  72189. GenericController.MODEL_FILENAME = 'generic.babylon';
  72190. return GenericController;
  72191. }(BABYLON.WebVRController));
  72192. BABYLON.GenericController = GenericController;
  72193. })(BABYLON || (BABYLON = {}));
  72194. //# sourceMappingURL=babylon.genericController.js.map
  72195. var BABYLON;
  72196. (function (BABYLON) {
  72197. /**
  72198. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72199. */
  72200. var LoadedMeshInfo = /** @class */ (function () {
  72201. function LoadedMeshInfo() {
  72202. /**
  72203. * Map of the button meshes contained in the controller
  72204. */
  72205. this.buttonMeshes = {};
  72206. /**
  72207. * Map of the axis meshes contained in the controller
  72208. */
  72209. this.axisMeshes = {};
  72210. }
  72211. return LoadedMeshInfo;
  72212. }());
  72213. /**
  72214. * Defines the WindowsMotionController object that the state of the windows motion controller
  72215. */
  72216. var WindowsMotionController = /** @class */ (function (_super) {
  72217. __extends(WindowsMotionController, _super);
  72218. /**
  72219. * Creates a new WindowsMotionController from a gamepad
  72220. * @param vrGamepad the gamepad that the controller should be created from
  72221. */
  72222. function WindowsMotionController(vrGamepad) {
  72223. var _this = _super.call(this, vrGamepad) || this;
  72224. _this._mapping = {
  72225. // Semantic button names
  72226. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72227. // A mapping of the button name to glTF model node name
  72228. // that should be transformed by button value.
  72229. buttonMeshNames: {
  72230. 'trigger': 'SELECT',
  72231. 'menu': 'MENU',
  72232. 'grip': 'GRASP',
  72233. 'thumbstick': 'THUMBSTICK_PRESS',
  72234. 'trackpad': 'TOUCHPAD_PRESS'
  72235. },
  72236. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72237. buttonObservableNames: {
  72238. 'trigger': 'onTriggerStateChangedObservable',
  72239. 'menu': 'onSecondaryButtonStateChangedObservable',
  72240. 'grip': 'onMainButtonStateChangedObservable',
  72241. 'thumbstick': 'onPadStateChangedObservable',
  72242. 'trackpad': 'onTrackpadChangedObservable'
  72243. },
  72244. // A mapping of the axis name to glTF model node name
  72245. // that should be transformed by axis value.
  72246. // This array mirrors the browserGamepad.axes array, such that
  72247. // the mesh corresponding to axis 0 is in this array index 0.
  72248. axisMeshNames: [
  72249. 'THUMBSTICK_X',
  72250. 'THUMBSTICK_Y',
  72251. 'TOUCHPAD_TOUCH_X',
  72252. 'TOUCHPAD_TOUCH_Y'
  72253. ],
  72254. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72255. };
  72256. /**
  72257. * Fired when the trackpad on this controller is clicked
  72258. */
  72259. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72260. /**
  72261. * Fired when the trackpad on this controller is modified
  72262. */
  72263. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72264. /**
  72265. * The current x and y values of this controller's trackpad
  72266. */
  72267. _this.trackpad = { x: 0, y: 0 };
  72268. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72269. _this._loadedMeshInfo = null;
  72270. return _this;
  72271. }
  72272. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72273. /**
  72274. * Fired when the trigger on this controller is modified
  72275. */
  72276. get: function () {
  72277. return this.onTriggerStateChangedObservable;
  72278. },
  72279. enumerable: true,
  72280. configurable: true
  72281. });
  72282. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72283. /**
  72284. * Fired when the menu button on this controller is modified
  72285. */
  72286. get: function () {
  72287. return this.onSecondaryButtonStateChangedObservable;
  72288. },
  72289. enumerable: true,
  72290. configurable: true
  72291. });
  72292. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72293. /**
  72294. * Fired when the grip button on this controller is modified
  72295. */
  72296. get: function () {
  72297. return this.onMainButtonStateChangedObservable;
  72298. },
  72299. enumerable: true,
  72300. configurable: true
  72301. });
  72302. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72303. /**
  72304. * Fired when the thumbstick button on this controller is modified
  72305. */
  72306. get: function () {
  72307. return this.onPadStateChangedObservable;
  72308. },
  72309. enumerable: true,
  72310. configurable: true
  72311. });
  72312. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72313. /**
  72314. * Fired when the touchpad button on this controller is modified
  72315. */
  72316. get: function () {
  72317. return this.onTrackpadChangedObservable;
  72318. },
  72319. enumerable: true,
  72320. configurable: true
  72321. });
  72322. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72323. /**
  72324. * Fired when the touchpad values on this controller are modified
  72325. */
  72326. get: function () {
  72327. return this.onTrackpadValuesChangedObservable;
  72328. },
  72329. enumerable: true,
  72330. configurable: true
  72331. });
  72332. /**
  72333. * Called once per frame by the engine.
  72334. */
  72335. WindowsMotionController.prototype.update = function () {
  72336. _super.prototype.update.call(this);
  72337. if (this.browserGamepad.axes) {
  72338. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72339. this.trackpad.x = this.browserGamepad["axes"][2];
  72340. this.trackpad.y = this.browserGamepad["axes"][3];
  72341. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72342. }
  72343. // Only need to animate axes if there is a loaded mesh
  72344. if (this._loadedMeshInfo) {
  72345. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72346. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72347. }
  72348. }
  72349. }
  72350. };
  72351. /**
  72352. * Called once for each button that changed state since the last frame
  72353. * @param buttonIdx Which button index changed
  72354. * @param state New state of the button
  72355. * @param changes Which properties on the state changed since last frame
  72356. */
  72357. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72358. var buttonName = this._mapping.buttons[buttonIdx];
  72359. if (!buttonName) {
  72360. return;
  72361. }
  72362. // Only emit events for buttons that we know how to map from index to name
  72363. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72364. if (observable) {
  72365. observable.notifyObservers(state);
  72366. }
  72367. this._lerpButtonTransform(buttonName, state.value);
  72368. };
  72369. /**
  72370. * Moves the buttons on the controller mesh based on their current state
  72371. * @param buttonName the name of the button to move
  72372. * @param buttonValue the value of the button which determines the buttons new position
  72373. */
  72374. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72375. // If there is no loaded mesh, there is nothing to transform.
  72376. if (!this._loadedMeshInfo) {
  72377. return;
  72378. }
  72379. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72380. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72381. return;
  72382. }
  72383. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72384. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72385. };
  72386. /**
  72387. * Moves the axis on the controller mesh based on its current state
  72388. * @param axis the index of the axis
  72389. * @param axisValue the value of the axis which determines the meshes new position
  72390. * @hidden
  72391. */
  72392. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72393. if (!this._loadedMeshInfo) {
  72394. return;
  72395. }
  72396. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72397. if (!meshInfo) {
  72398. return;
  72399. }
  72400. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72401. return;
  72402. }
  72403. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72404. var lerpValue = axisValue * 0.5 + 0.5;
  72405. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72406. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72407. };
  72408. /**
  72409. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72410. * @param scene scene in which to add meshes
  72411. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72412. */
  72413. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72414. var _this = this;
  72415. if (forceDefault === void 0) { forceDefault = false; }
  72416. var path;
  72417. var filename;
  72418. // Checking if GLB loader is present
  72419. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72420. // Determine the device specific folder based on the ID suffix
  72421. var device = 'default';
  72422. if (this.id && !forceDefault) {
  72423. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72424. device = ((match && match[0]) || device);
  72425. }
  72426. // Hand
  72427. if (this.hand === 'left') {
  72428. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72429. }
  72430. else { // Right is the default if no hand is specified
  72431. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72432. }
  72433. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72434. }
  72435. else {
  72436. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72437. path = BABYLON.GenericController.MODEL_BASE_URL;
  72438. filename = BABYLON.GenericController.MODEL_FILENAME;
  72439. }
  72440. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72441. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72442. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72443. if (!_this._loadedMeshInfo) {
  72444. return;
  72445. }
  72446. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72447. _this.attachToMesh(_this._defaultModel);
  72448. if (meshLoaded) {
  72449. meshLoaded(_this._defaultModel);
  72450. }
  72451. }, null, function (scene, message) {
  72452. BABYLON.Tools.Log(message);
  72453. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72454. if (!forceDefault) {
  72455. _this.initControllerMesh(scene, meshLoaded, true);
  72456. }
  72457. });
  72458. };
  72459. /**
  72460. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72461. * can be transformed by button presses and axes values, based on this._mapping.
  72462. *
  72463. * @param scene scene in which the meshes exist
  72464. * @param meshes list of meshes that make up the controller model to process
  72465. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72466. */
  72467. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72468. var loadedMeshInfo = null;
  72469. // Create a new mesh to contain the glTF hierarchy
  72470. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72471. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72472. var childMesh = null;
  72473. for (var i = 0; i < meshes.length; i++) {
  72474. var mesh = meshes[i];
  72475. if (!mesh.parent) {
  72476. // Exclude controller meshes from picking results
  72477. mesh.isPickable = false;
  72478. // Handle root node, attach to the new parentMesh
  72479. childMesh = mesh;
  72480. break;
  72481. }
  72482. }
  72483. if (childMesh) {
  72484. childMesh.setParent(parentMesh);
  72485. // Create our mesh info. Note that this method will always return non-null.
  72486. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72487. }
  72488. else {
  72489. BABYLON.Tools.Warn('Could not find root node in model file.');
  72490. }
  72491. return loadedMeshInfo;
  72492. };
  72493. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72494. var loadedMeshInfo = new LoadedMeshInfo();
  72495. var i;
  72496. loadedMeshInfo.rootNode = rootNode;
  72497. // Reset the caches
  72498. loadedMeshInfo.buttonMeshes = {};
  72499. loadedMeshInfo.axisMeshes = {};
  72500. // Button Meshes
  72501. for (i = 0; i < this._mapping.buttons.length; i++) {
  72502. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72503. if (!buttonMeshName) {
  72504. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72505. continue;
  72506. }
  72507. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72508. if (!buttonMesh) {
  72509. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72510. continue;
  72511. }
  72512. var buttonMeshInfo = {
  72513. index: i,
  72514. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72515. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72516. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72517. };
  72518. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72519. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72520. }
  72521. else {
  72522. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72523. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72524. '(VALUE: ' + !!buttonMeshInfo.value +
  72525. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72526. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72527. ')');
  72528. }
  72529. }
  72530. // Axis Meshes
  72531. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72532. var axisMeshName = this._mapping.axisMeshNames[i];
  72533. if (!axisMeshName) {
  72534. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72535. continue;
  72536. }
  72537. var axisMesh = getChildByName(rootNode, axisMeshName);
  72538. if (!axisMesh) {
  72539. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72540. continue;
  72541. }
  72542. var axisMeshInfo = {
  72543. index: i,
  72544. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72545. min: getImmediateChildByName(axisMesh, 'MIN'),
  72546. max: getImmediateChildByName(axisMesh, 'MAX')
  72547. };
  72548. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72549. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72550. }
  72551. else {
  72552. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72553. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72554. '(VALUE: ' + !!axisMeshInfo.value +
  72555. ', MIN: ' + !!axisMeshInfo.min +
  72556. ', MAX:' + !!axisMeshInfo.max +
  72557. ')');
  72558. }
  72559. }
  72560. // Pointing Ray
  72561. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72562. if (!loadedMeshInfo.pointingPoseNode) {
  72563. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72564. }
  72565. return loadedMeshInfo;
  72566. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72567. function getChildByName(node, name) {
  72568. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72569. }
  72570. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72571. function getImmediateChildByName(node, name) {
  72572. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72573. }
  72574. };
  72575. /**
  72576. * Gets the ray of the controller in the direction the controller is pointing
  72577. * @param length the length the resulting ray should be
  72578. * @returns a ray in the direction the controller is pointing
  72579. */
  72580. WindowsMotionController.prototype.getForwardRay = function (length) {
  72581. if (length === void 0) { length = 100; }
  72582. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72583. return _super.prototype.getForwardRay.call(this, length);
  72584. }
  72585. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72586. var origin = m.getTranslation();
  72587. var forward = new BABYLON.Vector3(0, 0, -1);
  72588. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72589. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72590. return new BABYLON.Ray(origin, direction, length);
  72591. };
  72592. /**
  72593. * Disposes of the controller
  72594. */
  72595. WindowsMotionController.prototype.dispose = function () {
  72596. _super.prototype.dispose.call(this);
  72597. this.onTrackpadChangedObservable.clear();
  72598. };
  72599. /**
  72600. * The base url used to load the left and right controller models
  72601. */
  72602. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72603. /**
  72604. * The name of the left controller model file
  72605. */
  72606. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72607. /**
  72608. * The name of the right controller model file
  72609. */
  72610. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72611. /**
  72612. * The controller name prefix for this controller type
  72613. */
  72614. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72615. /**
  72616. * The controller id pattern for this controller type
  72617. */
  72618. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72619. return WindowsMotionController;
  72620. }(BABYLON.WebVRController));
  72621. BABYLON.WindowsMotionController = WindowsMotionController;
  72622. })(BABYLON || (BABYLON = {}));
  72623. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72624. var BABYLON;
  72625. (function (BABYLON) {
  72626. /**
  72627. * Gear VR Controller
  72628. */
  72629. var GearVRController = /** @class */ (function (_super) {
  72630. __extends(GearVRController, _super);
  72631. /**
  72632. * Creates a new GearVRController from a gamepad
  72633. * @param vrGamepad the gamepad that the controller should be created from
  72634. */
  72635. function GearVRController(vrGamepad) {
  72636. var _this = _super.call(this, vrGamepad) || this;
  72637. _this._buttonIndexToObservableNameMap = [
  72638. 'onTrackpadChangedObservable',
  72639. 'onTriggerStateChangedObservable' // Trigger
  72640. ];
  72641. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72642. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72643. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72644. return _this;
  72645. }
  72646. /**
  72647. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72648. * @param scene scene in which to add meshes
  72649. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72650. */
  72651. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72652. var _this = this;
  72653. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72654. _this._defaultModel = newMeshes[1];
  72655. _this.attachToMesh(_this._defaultModel);
  72656. if (meshLoaded) {
  72657. meshLoaded(_this._defaultModel);
  72658. }
  72659. });
  72660. };
  72661. /**
  72662. * Called once for each button that changed state since the last frame
  72663. * @param buttonIdx Which button index changed
  72664. * @param state New state of the button
  72665. * @param changes Which properties on the state changed since last frame
  72666. */
  72667. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72668. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72669. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72670. // Only emit events for buttons that we know how to map from index to observable
  72671. var observable = this[observableName];
  72672. if (observable) {
  72673. observable.notifyObservers(state);
  72674. }
  72675. }
  72676. };
  72677. /**
  72678. * Base Url for the controller model.
  72679. */
  72680. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72681. /**
  72682. * File name for the controller model.
  72683. */
  72684. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72685. /**
  72686. * Gamepad Id prefix used to identify this controller.
  72687. */
  72688. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72689. return GearVRController;
  72690. }(BABYLON.WebVRController));
  72691. BABYLON.GearVRController = GearVRController;
  72692. })(BABYLON || (BABYLON = {}));
  72693. //# sourceMappingURL=babylon.gearVRController.js.map
  72694. var BABYLON;
  72695. (function (BABYLON) {
  72696. /**
  72697. * Google Daydream controller
  72698. */
  72699. var DaydreamController = /** @class */ (function (_super) {
  72700. __extends(DaydreamController, _super);
  72701. /**
  72702. * Creates a new DaydreamController from a gamepad
  72703. * @param vrGamepad the gamepad that the controller should be created from
  72704. */
  72705. function DaydreamController(vrGamepad) {
  72706. var _this = _super.call(this, vrGamepad) || this;
  72707. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72708. return _this;
  72709. }
  72710. /**
  72711. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72712. * @param scene scene in which to add meshes
  72713. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72714. */
  72715. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72716. var _this = this;
  72717. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72718. _this._defaultModel = newMeshes[1];
  72719. _this.attachToMesh(_this._defaultModel);
  72720. if (meshLoaded) {
  72721. meshLoaded(_this._defaultModel);
  72722. }
  72723. });
  72724. };
  72725. /**
  72726. * Called once for each button that changed state since the last frame
  72727. * @param buttonIdx Which button index changed
  72728. * @param state New state of the button
  72729. * @param changes Which properties on the state changed since last frame
  72730. */
  72731. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72732. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72733. if (buttonIdx === 0) {
  72734. var observable = this.onTriggerStateChangedObservable;
  72735. if (observable) {
  72736. observable.notifyObservers(state);
  72737. }
  72738. }
  72739. else {
  72740. // If the app or home buttons are ever made available
  72741. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72742. }
  72743. };
  72744. /**
  72745. * Base Url for the controller model.
  72746. */
  72747. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72748. /**
  72749. * File name for the controller model.
  72750. */
  72751. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72752. /**
  72753. * Gamepad Id prefix used to identify Daydream Controller.
  72754. */
  72755. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72756. return DaydreamController;
  72757. }(BABYLON.WebVRController));
  72758. BABYLON.DaydreamController = DaydreamController;
  72759. })(BABYLON || (BABYLON = {}));
  72760. //# sourceMappingURL=babylon.daydreamController.js.map
  72761. var BABYLON;
  72762. (function (BABYLON) {
  72763. var FollowCamera = /** @class */ (function (_super) {
  72764. __extends(FollowCamera, _super);
  72765. function FollowCamera(name, position, scene, lockedTarget) {
  72766. if (lockedTarget === void 0) { lockedTarget = null; }
  72767. var _this = _super.call(this, name, position, scene) || this;
  72768. _this.radius = 12;
  72769. _this.rotationOffset = 0;
  72770. _this.heightOffset = 4;
  72771. _this.cameraAcceleration = 0.05;
  72772. _this.maxCameraSpeed = 20;
  72773. _this.lockedTarget = lockedTarget;
  72774. return _this;
  72775. }
  72776. FollowCamera.prototype.getRadians = function (degrees) {
  72777. return degrees * Math.PI / 180;
  72778. };
  72779. FollowCamera.prototype.follow = function (cameraTarget) {
  72780. if (!cameraTarget)
  72781. return;
  72782. var yRotation;
  72783. if (cameraTarget.rotationQuaternion) {
  72784. var rotMatrix = new BABYLON.Matrix();
  72785. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72786. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72787. }
  72788. else {
  72789. yRotation = cameraTarget.rotation.y;
  72790. }
  72791. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72792. var targetPosition = cameraTarget.getAbsolutePosition();
  72793. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72794. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72795. var dx = targetX - this.position.x;
  72796. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72797. var dz = (targetZ) - this.position.z;
  72798. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72799. var vy = dy * this.cameraAcceleration;
  72800. var vz = dz * this.cameraAcceleration * 2;
  72801. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72802. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72803. }
  72804. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72805. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72806. }
  72807. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72808. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72809. }
  72810. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72811. this.setTarget(targetPosition);
  72812. };
  72813. FollowCamera.prototype._checkInputs = function () {
  72814. _super.prototype._checkInputs.call(this);
  72815. if (this.lockedTarget) {
  72816. this.follow(this.lockedTarget);
  72817. }
  72818. };
  72819. FollowCamera.prototype.getClassName = function () {
  72820. return "FollowCamera";
  72821. };
  72822. __decorate([
  72823. BABYLON.serialize()
  72824. ], FollowCamera.prototype, "radius", void 0);
  72825. __decorate([
  72826. BABYLON.serialize()
  72827. ], FollowCamera.prototype, "rotationOffset", void 0);
  72828. __decorate([
  72829. BABYLON.serialize()
  72830. ], FollowCamera.prototype, "heightOffset", void 0);
  72831. __decorate([
  72832. BABYLON.serialize()
  72833. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72834. __decorate([
  72835. BABYLON.serialize()
  72836. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72837. __decorate([
  72838. BABYLON.serializeAsMeshReference("lockedTargetId")
  72839. ], FollowCamera.prototype, "lockedTarget", void 0);
  72840. return FollowCamera;
  72841. }(BABYLON.TargetCamera));
  72842. BABYLON.FollowCamera = FollowCamera;
  72843. var ArcFollowCamera = /** @class */ (function (_super) {
  72844. __extends(ArcFollowCamera, _super);
  72845. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72846. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72847. _this.alpha = alpha;
  72848. _this.beta = beta;
  72849. _this.radius = radius;
  72850. _this.target = target;
  72851. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72852. _this.follow();
  72853. return _this;
  72854. }
  72855. ArcFollowCamera.prototype.follow = function () {
  72856. if (!this.target) {
  72857. return;
  72858. }
  72859. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72860. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72861. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72862. var targetPosition = this.target.getAbsolutePosition();
  72863. this.position = targetPosition.add(this._cartesianCoordinates);
  72864. this.setTarget(targetPosition);
  72865. };
  72866. ArcFollowCamera.prototype._checkInputs = function () {
  72867. _super.prototype._checkInputs.call(this);
  72868. this.follow();
  72869. };
  72870. ArcFollowCamera.prototype.getClassName = function () {
  72871. return "ArcFollowCamera";
  72872. };
  72873. return ArcFollowCamera;
  72874. }(BABYLON.TargetCamera));
  72875. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72876. })(BABYLON || (BABYLON = {}));
  72877. //# sourceMappingURL=babylon.followCamera.js.map
  72878. var BABYLON;
  72879. (function (BABYLON) {
  72880. // We're mainly based on the logic defined into the FreeCamera code
  72881. var UniversalCamera = /** @class */ (function (_super) {
  72882. __extends(UniversalCamera, _super);
  72883. //-- end properties for backward compatibility for inputs
  72884. function UniversalCamera(name, position, scene) {
  72885. var _this = _super.call(this, name, position, scene) || this;
  72886. _this.inputs.addGamepad();
  72887. return _this;
  72888. }
  72889. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72890. //-- Begin properties for backward compatibility for inputs
  72891. get: function () {
  72892. var gamepad = this.inputs.attached["gamepad"];
  72893. if (gamepad)
  72894. return gamepad.gamepadAngularSensibility;
  72895. return 0;
  72896. },
  72897. set: function (value) {
  72898. var gamepad = this.inputs.attached["gamepad"];
  72899. if (gamepad)
  72900. gamepad.gamepadAngularSensibility = value;
  72901. },
  72902. enumerable: true,
  72903. configurable: true
  72904. });
  72905. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72906. get: function () {
  72907. var gamepad = this.inputs.attached["gamepad"];
  72908. if (gamepad)
  72909. return gamepad.gamepadMoveSensibility;
  72910. return 0;
  72911. },
  72912. set: function (value) {
  72913. var gamepad = this.inputs.attached["gamepad"];
  72914. if (gamepad)
  72915. gamepad.gamepadMoveSensibility = value;
  72916. },
  72917. enumerable: true,
  72918. configurable: true
  72919. });
  72920. UniversalCamera.prototype.getClassName = function () {
  72921. return "UniversalCamera";
  72922. };
  72923. return UniversalCamera;
  72924. }(BABYLON.TouchCamera));
  72925. BABYLON.UniversalCamera = UniversalCamera;
  72926. })(BABYLON || (BABYLON = {}));
  72927. //# sourceMappingURL=babylon.universalCamera.js.map
  72928. var BABYLON;
  72929. (function (BABYLON) {
  72930. // We're mainly based on the logic defined into the FreeCamera code
  72931. var GamepadCamera = /** @class */ (function (_super) {
  72932. __extends(GamepadCamera, _super);
  72933. //-- end properties for backward compatibility for inputs
  72934. function GamepadCamera(name, position, scene) {
  72935. return _super.call(this, name, position, scene) || this;
  72936. }
  72937. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72938. //-- Begin properties for backward compatibility for inputs
  72939. get: function () {
  72940. var gamepad = this.inputs.attached["gamepad"];
  72941. if (gamepad)
  72942. return gamepad.gamepadAngularSensibility;
  72943. return 0;
  72944. },
  72945. set: function (value) {
  72946. var gamepad = this.inputs.attached["gamepad"];
  72947. if (gamepad)
  72948. gamepad.gamepadAngularSensibility = value;
  72949. },
  72950. enumerable: true,
  72951. configurable: true
  72952. });
  72953. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72954. get: function () {
  72955. var gamepad = this.inputs.attached["gamepad"];
  72956. if (gamepad)
  72957. return gamepad.gamepadMoveSensibility;
  72958. return 0;
  72959. },
  72960. set: function (value) {
  72961. var gamepad = this.inputs.attached["gamepad"];
  72962. if (gamepad)
  72963. gamepad.gamepadMoveSensibility = value;
  72964. },
  72965. enumerable: true,
  72966. configurable: true
  72967. });
  72968. GamepadCamera.prototype.getClassName = function () {
  72969. return "GamepadCamera";
  72970. };
  72971. return GamepadCamera;
  72972. }(BABYLON.UniversalCamera));
  72973. BABYLON.GamepadCamera = GamepadCamera;
  72974. })(BABYLON || (BABYLON = {}));
  72975. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72976. var BABYLON;
  72977. (function (BABYLON) {
  72978. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72979. function PostProcessRenderPipelineManager() {
  72980. this._renderPipelines = {};
  72981. }
  72982. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72983. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72984. };
  72985. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72986. if (unique === void 0) { unique = false; }
  72987. var renderPipeline = this._renderPipelines[renderPipelineName];
  72988. if (!renderPipeline) {
  72989. return;
  72990. }
  72991. renderPipeline._attachCameras(cameras, unique);
  72992. };
  72993. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72994. var renderPipeline = this._renderPipelines[renderPipelineName];
  72995. if (!renderPipeline) {
  72996. return;
  72997. }
  72998. renderPipeline._detachCameras(cameras);
  72999. };
  73000. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73001. var renderPipeline = this._renderPipelines[renderPipelineName];
  73002. if (!renderPipeline) {
  73003. return;
  73004. }
  73005. renderPipeline._enableEffect(renderEffectName, cameras);
  73006. };
  73007. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73008. var renderPipeline = this._renderPipelines[renderPipelineName];
  73009. if (!renderPipeline) {
  73010. return;
  73011. }
  73012. renderPipeline._disableEffect(renderEffectName, cameras);
  73013. };
  73014. PostProcessRenderPipelineManager.prototype.update = function () {
  73015. for (var renderPipelineName in this._renderPipelines) {
  73016. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73017. var pipeline = this._renderPipelines[renderPipelineName];
  73018. if (!pipeline.isSupported) {
  73019. pipeline.dispose();
  73020. delete this._renderPipelines[renderPipelineName];
  73021. }
  73022. else {
  73023. pipeline._update();
  73024. }
  73025. }
  73026. }
  73027. };
  73028. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73029. for (var renderPipelineName in this._renderPipelines) {
  73030. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73031. var pipeline = this._renderPipelines[renderPipelineName];
  73032. pipeline._rebuild();
  73033. }
  73034. }
  73035. };
  73036. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73037. for (var renderPipelineName in this._renderPipelines) {
  73038. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73039. var pipeline = this._renderPipelines[renderPipelineName];
  73040. pipeline.dispose();
  73041. }
  73042. }
  73043. };
  73044. return PostProcessRenderPipelineManager;
  73045. }());
  73046. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73047. })(BABYLON || (BABYLON = {}));
  73048. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73049. var BABYLON;
  73050. (function (BABYLON) {
  73051. /**
  73052. * This represents a set of one or more post processes in Babylon.
  73053. * A post process can be used to apply a shader to a texture after it is rendered.
  73054. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73055. */
  73056. var PostProcessRenderEffect = /** @class */ (function () {
  73057. /**
  73058. * Instantiates a post process render effect.
  73059. * A post process can be used to apply a shader to a texture after it is rendered.
  73060. * @param engine The engine the effect is tied to
  73061. * @param name The name of the effect
  73062. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73063. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73064. */
  73065. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73066. this._name = name;
  73067. this._singleInstance = singleInstance || true;
  73068. this._getPostProcesses = getPostProcesses;
  73069. this._cameras = {};
  73070. this._indicesForCamera = {};
  73071. this._postProcesses = {};
  73072. }
  73073. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73074. /**
  73075. * Checks if all the post processes in the effect are supported.
  73076. */
  73077. get: function () {
  73078. for (var index in this._postProcesses) {
  73079. if (this._postProcesses.hasOwnProperty(index)) {
  73080. var pps = this._postProcesses[index];
  73081. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73082. if (!pps[ppIndex].isSupported) {
  73083. return false;
  73084. }
  73085. }
  73086. }
  73087. }
  73088. return true;
  73089. },
  73090. enumerable: true,
  73091. configurable: true
  73092. });
  73093. /**
  73094. * Updates the current state of the effect
  73095. */
  73096. PostProcessRenderEffect.prototype._update = function () {
  73097. };
  73098. /**
  73099. * Attaches the effect on cameras
  73100. * @param cameras The camera to attach to.
  73101. */
  73102. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73103. var _this = this;
  73104. var cameraKey;
  73105. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73106. if (!cams) {
  73107. return;
  73108. }
  73109. for (var i = 0; i < cams.length; i++) {
  73110. var camera = cams[i];
  73111. var cameraName = camera.name;
  73112. if (this._singleInstance) {
  73113. cameraKey = 0;
  73114. }
  73115. else {
  73116. cameraKey = cameraName;
  73117. }
  73118. if (!this._postProcesses[cameraKey]) {
  73119. var postProcess = this._getPostProcesses();
  73120. if (postProcess) {
  73121. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73122. }
  73123. }
  73124. if (!this._indicesForCamera[cameraName]) {
  73125. this._indicesForCamera[cameraName] = [];
  73126. }
  73127. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73128. var index = camera.attachPostProcess(postProcess);
  73129. _this._indicesForCamera[cameraName].push(index);
  73130. });
  73131. if (!this._cameras[cameraName]) {
  73132. this._cameras[cameraName] = camera;
  73133. }
  73134. }
  73135. };
  73136. /**
  73137. * Detatches the effect on cameras
  73138. * @param cameras The camera to detatch from.
  73139. */
  73140. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73141. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73142. if (!cams) {
  73143. return;
  73144. }
  73145. for (var i = 0; i < cams.length; i++) {
  73146. var camera = cams[i];
  73147. var cameraName = camera.name;
  73148. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73149. camera.detachPostProcess(postProcess);
  73150. });
  73151. if (this._cameras[cameraName]) {
  73152. //this._indicesForCamera.splice(index, 1);
  73153. this._cameras[cameraName] = null;
  73154. }
  73155. }
  73156. };
  73157. /**
  73158. * Enables the effect on given cameras
  73159. * @param cameras The camera to enable.
  73160. */
  73161. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73162. var _this = this;
  73163. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73164. if (!cams) {
  73165. return;
  73166. }
  73167. for (var i = 0; i < cams.length; i++) {
  73168. var camera = cams[i];
  73169. var cameraName = camera.name;
  73170. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73171. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73172. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73173. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73174. });
  73175. }
  73176. }
  73177. }
  73178. };
  73179. /**
  73180. * Disables the effect on the given cameras
  73181. * @param cameras The camera to disable.
  73182. */
  73183. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73184. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73185. if (!cams) {
  73186. return;
  73187. }
  73188. for (var i = 0; i < cams.length; i++) {
  73189. var camera = cams[i];
  73190. var cameraName = camera.name;
  73191. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73192. camera.detachPostProcess(postProcess);
  73193. });
  73194. }
  73195. };
  73196. /**
  73197. * Gets a list of the post processes contained in the effect.
  73198. * @param camera The camera to get the post processes on.
  73199. * @returns The list of the post processes in the effect.
  73200. */
  73201. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73202. if (this._singleInstance) {
  73203. return this._postProcesses[0];
  73204. }
  73205. else {
  73206. if (!camera) {
  73207. return null;
  73208. }
  73209. return this._postProcesses[camera.name];
  73210. }
  73211. };
  73212. return PostProcessRenderEffect;
  73213. }());
  73214. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73215. })(BABYLON || (BABYLON = {}));
  73216. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73217. var BABYLON;
  73218. (function (BABYLON) {
  73219. var PostProcessRenderPipeline = /** @class */ (function () {
  73220. function PostProcessRenderPipeline(engine, name) {
  73221. this.engine = engine;
  73222. this._name = name;
  73223. this._renderEffects = {};
  73224. this._renderEffectsForIsolatedPass = new Array();
  73225. this._cameras = [];
  73226. }
  73227. PostProcessRenderPipeline.prototype.getClassName = function () {
  73228. return "PostProcessRenderPipeline";
  73229. };
  73230. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73231. get: function () {
  73232. for (var renderEffectName in this._renderEffects) {
  73233. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73234. if (!this._renderEffects[renderEffectName].isSupported) {
  73235. return false;
  73236. }
  73237. }
  73238. }
  73239. return true;
  73240. },
  73241. enumerable: true,
  73242. configurable: true
  73243. });
  73244. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73245. this._renderEffects[renderEffect._name] = renderEffect;
  73246. };
  73247. // private
  73248. PostProcessRenderPipeline.prototype._rebuild = function () {
  73249. };
  73250. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73251. var renderEffects = this._renderEffects[renderEffectName];
  73252. if (!renderEffects) {
  73253. return;
  73254. }
  73255. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73256. };
  73257. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73258. var renderEffects = this._renderEffects[renderEffectName];
  73259. if (!renderEffects) {
  73260. return;
  73261. }
  73262. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73263. };
  73264. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73265. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73266. if (!cams) {
  73267. return;
  73268. }
  73269. var indicesToDelete = [];
  73270. var i;
  73271. for (i = 0; i < cams.length; i++) {
  73272. var camera = cams[i];
  73273. var cameraName = camera.name;
  73274. if (this._cameras.indexOf(camera) === -1) {
  73275. this._cameras[cameraName] = camera;
  73276. }
  73277. else if (unique) {
  73278. indicesToDelete.push(i);
  73279. }
  73280. }
  73281. for (i = 0; i < indicesToDelete.length; i++) {
  73282. cameras.splice(indicesToDelete[i], 1);
  73283. }
  73284. for (var renderEffectName in this._renderEffects) {
  73285. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73286. this._renderEffects[renderEffectName]._attachCameras(cams);
  73287. }
  73288. }
  73289. };
  73290. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73291. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73292. if (!cams) {
  73293. return;
  73294. }
  73295. for (var renderEffectName in this._renderEffects) {
  73296. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73297. this._renderEffects[renderEffectName]._detachCameras(cams);
  73298. }
  73299. }
  73300. for (var i = 0; i < cams.length; i++) {
  73301. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73302. }
  73303. };
  73304. PostProcessRenderPipeline.prototype._update = function () {
  73305. for (var renderEffectName in this._renderEffects) {
  73306. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73307. this._renderEffects[renderEffectName]._update();
  73308. }
  73309. }
  73310. for (var i = 0; i < this._cameras.length; i++) {
  73311. var cameraName = this._cameras[i].name;
  73312. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73313. this._renderEffectsForIsolatedPass[cameraName]._update();
  73314. }
  73315. }
  73316. };
  73317. PostProcessRenderPipeline.prototype._reset = function () {
  73318. this._renderEffects = {};
  73319. this._renderEffectsForIsolatedPass = new Array();
  73320. };
  73321. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73322. // 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)
  73323. var effectKeys = Object.keys(this._renderEffects);
  73324. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73325. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73326. if (postProcesses) {
  73327. postProcesses[0].samples = sampleCount;
  73328. return true;
  73329. }
  73330. }
  73331. return false;
  73332. };
  73333. PostProcessRenderPipeline.prototype.dispose = function () {
  73334. // Must be implemented by children
  73335. };
  73336. __decorate([
  73337. BABYLON.serialize()
  73338. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73339. return PostProcessRenderPipeline;
  73340. }());
  73341. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73342. })(BABYLON || (BABYLON = {}));
  73343. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73344. var BABYLON;
  73345. (function (BABYLON) {
  73346. /**
  73347. * This represents a depth renderer in Babylon.
  73348. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73349. */
  73350. var DepthRenderer = /** @class */ (function () {
  73351. /**
  73352. * Instantiates a depth renderer
  73353. * @param scene The scene the renderer belongs to
  73354. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73355. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73356. */
  73357. function DepthRenderer(scene, type, camera) {
  73358. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73359. if (camera === void 0) { camera = null; }
  73360. var _this = this;
  73361. this._scene = scene;
  73362. this._camera = camera;
  73363. var engine = scene.getEngine();
  73364. // Render target
  73365. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73366. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73367. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73368. this._depthMap.refreshRate = 1;
  73369. this._depthMap.renderParticles = false;
  73370. this._depthMap.renderList = null;
  73371. // Camera to get depth map from to support multiple concurrent cameras
  73372. this._depthMap.activeCamera = this._camera;
  73373. this._depthMap.ignoreCameraViewport = true;
  73374. this._depthMap.useCameraPostProcesses = false;
  73375. // set default depth value to 1.0 (far away)
  73376. this._depthMap.onClearObservable.add(function (engine) {
  73377. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73378. });
  73379. // Custom render function
  73380. var renderSubMesh = function (subMesh) {
  73381. var mesh = subMesh.getRenderingMesh();
  73382. var scene = _this._scene;
  73383. var engine = scene.getEngine();
  73384. var material = subMesh.getMaterial();
  73385. if (!material) {
  73386. return;
  73387. }
  73388. // Culling and reverse (right handed system)
  73389. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73390. // Managing instances
  73391. var batch = mesh._getInstancesRenderList(subMesh._id);
  73392. if (batch.mustReturn) {
  73393. return;
  73394. }
  73395. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73396. var camera = _this._camera || scene.activeCamera;
  73397. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73398. engine.enableEffect(_this._effect);
  73399. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73400. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73401. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73402. // Alpha test
  73403. if (material && material.needAlphaTesting()) {
  73404. var alphaTexture = material.getAlphaTestTexture();
  73405. if (alphaTexture) {
  73406. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73407. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73408. }
  73409. }
  73410. // Bones
  73411. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73412. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73413. }
  73414. // Draw
  73415. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73416. }
  73417. };
  73418. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73419. var index;
  73420. if (depthOnlySubMeshes.length) {
  73421. engine.setColorWrite(false);
  73422. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73423. renderSubMesh(depthOnlySubMeshes.data[index]);
  73424. }
  73425. engine.setColorWrite(true);
  73426. }
  73427. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73428. renderSubMesh(opaqueSubMeshes.data[index]);
  73429. }
  73430. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73431. renderSubMesh(alphaTestSubMeshes.data[index]);
  73432. }
  73433. };
  73434. }
  73435. /**
  73436. * Creates the depth rendering effect and checks if the effect is ready.
  73437. * @param subMesh The submesh to be used to render the depth map of
  73438. * @param useInstances If multiple world instances should be used
  73439. * @returns if the depth renderer is ready to render the depth map
  73440. */
  73441. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73442. var material = subMesh.getMaterial();
  73443. if (material.disableDepthWrite) {
  73444. return false;
  73445. }
  73446. var defines = [];
  73447. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73448. var mesh = subMesh.getMesh();
  73449. // Alpha test
  73450. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73451. defines.push("#define ALPHATEST");
  73452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73453. attribs.push(BABYLON.VertexBuffer.UVKind);
  73454. defines.push("#define UV1");
  73455. }
  73456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73457. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73458. defines.push("#define UV2");
  73459. }
  73460. }
  73461. // Bones
  73462. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73465. if (mesh.numBoneInfluencers > 4) {
  73466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73468. }
  73469. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73470. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73471. }
  73472. else {
  73473. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73474. }
  73475. // Instances
  73476. if (useInstances) {
  73477. defines.push("#define INSTANCES");
  73478. attribs.push("world0");
  73479. attribs.push("world1");
  73480. attribs.push("world2");
  73481. attribs.push("world3");
  73482. }
  73483. // Get correct effect
  73484. var join = defines.join("\n");
  73485. if (this._cachedDefines !== join) {
  73486. this._cachedDefines = join;
  73487. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73488. }
  73489. return this._effect.isReady();
  73490. };
  73491. /**
  73492. * Gets the texture which the depth map will be written to.
  73493. * @returns The depth map texture
  73494. */
  73495. DepthRenderer.prototype.getDepthMap = function () {
  73496. return this._depthMap;
  73497. };
  73498. /**
  73499. * Disposes of the depth renderer.
  73500. */
  73501. DepthRenderer.prototype.dispose = function () {
  73502. this._depthMap.dispose();
  73503. };
  73504. return DepthRenderer;
  73505. }());
  73506. BABYLON.DepthRenderer = DepthRenderer;
  73507. })(BABYLON || (BABYLON = {}));
  73508. //# sourceMappingURL=babylon.depthRenderer.js.map
  73509. var BABYLON;
  73510. (function (BABYLON) {
  73511. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73512. __extends(SSAORenderingPipeline, _super);
  73513. /**
  73514. * @constructor
  73515. * @param {string} name - The rendering pipeline name
  73516. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73517. * @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 }
  73518. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73519. */
  73520. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73521. var _this = _super.call(this, scene.getEngine(), name) || this;
  73522. // Members
  73523. /**
  73524. * The PassPostProcess id in the pipeline that contains the original scene color
  73525. */
  73526. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73527. /**
  73528. * The SSAO PostProcess id in the pipeline
  73529. */
  73530. _this.SSAORenderEffect = "SSAORenderEffect";
  73531. /**
  73532. * The horizontal blur PostProcess id in the pipeline
  73533. */
  73534. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73535. /**
  73536. * The vertical blur PostProcess id in the pipeline
  73537. */
  73538. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73539. /**
  73540. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73541. */
  73542. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73543. /**
  73544. * The output strength of the SSAO post-process. Default value is 1.0.
  73545. */
  73546. _this.totalStrength = 1.0;
  73547. /**
  73548. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73549. */
  73550. _this.radius = 0.0001;
  73551. /**
  73552. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73553. * Must not be equal to fallOff and superior to fallOff.
  73554. * Default value is 0.975
  73555. */
  73556. _this.area = 0.0075;
  73557. /**
  73558. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73559. * Must not be equal to area and inferior to area.
  73560. * Default value is 0.0
  73561. */
  73562. _this.fallOff = 0.000001;
  73563. /**
  73564. * The base color of the SSAO post-process
  73565. * The final result is "base + ssao" between [0, 1]
  73566. */
  73567. _this.base = 0.5;
  73568. _this._firstUpdate = true;
  73569. _this._scene = scene;
  73570. // Set up assets
  73571. _this._createRandomTexture();
  73572. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73573. var ssaoRatio = ratio.ssaoRatio || ratio;
  73574. var combineRatio = ratio.combineRatio || ratio;
  73575. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73576. _this._createSSAOPostProcess(ssaoRatio);
  73577. _this._createBlurPostProcess(ssaoRatio);
  73578. _this._createSSAOCombinePostProcess(combineRatio);
  73579. // Set up pipeline
  73580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73582. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73583. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73584. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73585. // Finish
  73586. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73587. if (cameras)
  73588. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73589. return _this;
  73590. }
  73591. // Public Methods
  73592. /**
  73593. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73594. */
  73595. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73596. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73597. for (var i = 0; i < this._scene.cameras.length; i++) {
  73598. var camera = this._scene.cameras[i];
  73599. this._originalColorPostProcess.dispose(camera);
  73600. this._ssaoPostProcess.dispose(camera);
  73601. this._blurHPostProcess.dispose(camera);
  73602. this._blurVPostProcess.dispose(camera);
  73603. this._ssaoCombinePostProcess.dispose(camera);
  73604. }
  73605. this._randomTexture.dispose();
  73606. if (disableDepthRender)
  73607. this._scene.disableDepthRenderer();
  73608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73609. _super.prototype.dispose.call(this);
  73610. };
  73611. // Private Methods
  73612. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73613. var _this = this;
  73614. var size = 16;
  73615. 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);
  73616. 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);
  73617. this._blurHPostProcess.onActivateObservable.add(function () {
  73618. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73619. _this._blurHPostProcess.kernel = size * dw;
  73620. });
  73621. this._blurVPostProcess.onActivateObservable.add(function () {
  73622. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73623. _this._blurVPostProcess.kernel = size * dw;
  73624. });
  73625. };
  73626. SSAORenderingPipeline.prototype._rebuild = function () {
  73627. this._firstUpdate = true;
  73628. _super.prototype._rebuild.call(this);
  73629. };
  73630. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73631. var _this = this;
  73632. var numSamples = 16;
  73633. var sampleSphere = [
  73634. 0.5381, 0.1856, -0.4319,
  73635. 0.1379, 0.2486, 0.4430,
  73636. 0.3371, 0.5679, -0.0057,
  73637. -0.6999, -0.0451, -0.0019,
  73638. 0.0689, -0.1598, -0.8547,
  73639. 0.0560, 0.0069, -0.1843,
  73640. -0.0146, 0.1402, 0.0762,
  73641. 0.0100, -0.1924, -0.0344,
  73642. -0.3577, -0.5301, -0.4358,
  73643. -0.3169, 0.1063, 0.0158,
  73644. 0.0103, -0.5869, 0.0046,
  73645. -0.0897, -0.4940, 0.3287,
  73646. 0.7119, -0.0154, -0.0918,
  73647. -0.0533, 0.0596, -0.5411,
  73648. 0.0352, -0.0631, 0.5460,
  73649. -0.4776, 0.2847, -0.0271
  73650. ];
  73651. var samplesFactor = 1.0 / numSamples;
  73652. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73653. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73654. "area", "fallOff", "base", "range", "viewport"
  73655. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73656. this._ssaoPostProcess.onApply = function (effect) {
  73657. if (_this._firstUpdate) {
  73658. effect.setArray3("sampleSphere", sampleSphere);
  73659. effect.setFloat("samplesFactor", samplesFactor);
  73660. effect.setFloat("randTextureTiles", 4.0);
  73661. }
  73662. effect.setFloat("totalStrength", _this.totalStrength);
  73663. effect.setFloat("radius", _this.radius);
  73664. effect.setFloat("area", _this.area);
  73665. effect.setFloat("fallOff", _this.fallOff);
  73666. effect.setFloat("base", _this.base);
  73667. effect.setTexture("textureSampler", _this._depthTexture);
  73668. effect.setTexture("randomSampler", _this._randomTexture);
  73669. };
  73670. };
  73671. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73672. var _this = this;
  73673. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73674. this._ssaoCombinePostProcess.onApply = function (effect) {
  73675. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73676. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73677. };
  73678. };
  73679. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73680. var size = 512;
  73681. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73682. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73683. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73684. var context = this._randomTexture.getContext();
  73685. var rand = function (min, max) {
  73686. return Math.random() * (max - min) + min;
  73687. };
  73688. var randVector = BABYLON.Vector3.Zero();
  73689. for (var x = 0; x < size; x++) {
  73690. for (var y = 0; y < size; y++) {
  73691. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73692. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73693. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73694. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73695. context.fillRect(x, y, 1, 1);
  73696. }
  73697. }
  73698. this._randomTexture.update(false);
  73699. };
  73700. __decorate([
  73701. BABYLON.serialize()
  73702. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73703. __decorate([
  73704. BABYLON.serialize()
  73705. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73706. __decorate([
  73707. BABYLON.serialize()
  73708. ], SSAORenderingPipeline.prototype, "area", void 0);
  73709. __decorate([
  73710. BABYLON.serialize()
  73711. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73712. __decorate([
  73713. BABYLON.serialize()
  73714. ], SSAORenderingPipeline.prototype, "base", void 0);
  73715. return SSAORenderingPipeline;
  73716. }(BABYLON.PostProcessRenderPipeline));
  73717. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73718. })(BABYLON || (BABYLON = {}));
  73719. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73720. var BABYLON;
  73721. (function (BABYLON) {
  73722. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73723. __extends(SSAO2RenderingPipeline, _super);
  73724. /**
  73725. * @constructor
  73726. * @param {string} name - The rendering pipeline name
  73727. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73728. * @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 }
  73729. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73730. */
  73731. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73732. var _this = _super.call(this, scene.getEngine(), name) || this;
  73733. // Members
  73734. /**
  73735. * The PassPostProcess id in the pipeline that contains the original scene color
  73736. */
  73737. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73738. /**
  73739. * The SSAO PostProcess id in the pipeline
  73740. */
  73741. _this.SSAORenderEffect = "SSAORenderEffect";
  73742. /**
  73743. * The horizontal blur PostProcess id in the pipeline
  73744. */
  73745. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73746. /**
  73747. * The vertical blur PostProcess id in the pipeline
  73748. */
  73749. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73750. /**
  73751. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73752. */
  73753. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73754. /**
  73755. * The output strength of the SSAO post-process. Default value is 1.0.
  73756. */
  73757. _this.totalStrength = 1.0;
  73758. /**
  73759. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73760. */
  73761. _this.maxZ = 100.0;
  73762. /**
  73763. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73764. */
  73765. _this.minZAspect = 0.2;
  73766. /**
  73767. * Number of samples used for the SSAO calculations. Default value is 8
  73768. */
  73769. _this._samples = 8;
  73770. /**
  73771. * Are we using bilateral blur ?
  73772. */
  73773. _this._expensiveBlur = true;
  73774. /**
  73775. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73776. */
  73777. _this.radius = 2.0;
  73778. /**
  73779. * The base color of the SSAO post-process
  73780. * The final result is "base + ssao" between [0, 1]
  73781. */
  73782. _this.base = 0.1;
  73783. _this._firstUpdate = true;
  73784. _this._scene = scene;
  73785. _this._ratio = ratio;
  73786. if (!_this.isSupported) {
  73787. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73788. return _this;
  73789. }
  73790. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73791. var blurRatio = _this._ratio.blurRatio || ratio;
  73792. // Set up assets
  73793. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73794. _this._createRandomTexture();
  73795. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73796. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73797. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73798. _this._createSSAOPostProcess(1.0);
  73799. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73800. _this._createSSAOCombinePostProcess(blurRatio);
  73801. // Set up pipeline
  73802. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73803. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73804. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73805. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73806. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73807. // Finish
  73808. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73809. if (cameras)
  73810. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73811. return _this;
  73812. }
  73813. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73814. get: function () {
  73815. return this._samples;
  73816. },
  73817. set: function (n) {
  73818. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73819. this._samples = n;
  73820. this._sampleSphere = this._generateHemisphere();
  73821. this._firstUpdate = true;
  73822. },
  73823. enumerable: true,
  73824. configurable: true
  73825. });
  73826. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73827. get: function () {
  73828. return this._expensiveBlur;
  73829. },
  73830. set: function (b) {
  73831. 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"]);
  73832. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73833. this._expensiveBlur = b;
  73834. this._firstUpdate = true;
  73835. },
  73836. enumerable: true,
  73837. configurable: true
  73838. });
  73839. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73840. /**
  73841. * Support test.
  73842. */
  73843. get: function () {
  73844. var engine = BABYLON.Engine.LastCreatedEngine;
  73845. if (!engine) {
  73846. return false;
  73847. }
  73848. return engine.getCaps().drawBuffersExtension;
  73849. },
  73850. enumerable: true,
  73851. configurable: true
  73852. });
  73853. // Public Methods
  73854. /**
  73855. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73856. */
  73857. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73858. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73859. for (var i = 0; i < this._scene.cameras.length; i++) {
  73860. var camera = this._scene.cameras[i];
  73861. this._originalColorPostProcess.dispose(camera);
  73862. this._ssaoPostProcess.dispose(camera);
  73863. this._blurHPostProcess.dispose(camera);
  73864. this._blurVPostProcess.dispose(camera);
  73865. this._ssaoCombinePostProcess.dispose(camera);
  73866. }
  73867. this._randomTexture.dispose();
  73868. if (disableGeometryBufferRenderer)
  73869. this._scene.disableGeometryBufferRenderer();
  73870. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73871. _super.prototype.dispose.call(this);
  73872. };
  73873. // Private Methods
  73874. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73875. var _this = this;
  73876. this._samplerOffsets = [];
  73877. var expensive = this.expensiveBlur;
  73878. for (var i = -8; i < 8; i++) {
  73879. this._samplerOffsets.push(i * 2 + 0.5);
  73880. }
  73881. 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");
  73882. this._blurHPostProcess.onApply = function (effect) {
  73883. if (!_this._scene.activeCamera) {
  73884. return;
  73885. }
  73886. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73887. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73888. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73889. effect.setFloat("radius", _this.radius);
  73890. effect.setTexture("depthSampler", _this._depthTexture);
  73891. if (_this._firstUpdate) {
  73892. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73893. }
  73894. };
  73895. 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");
  73896. this._blurVPostProcess.onApply = function (effect) {
  73897. if (!_this._scene.activeCamera) {
  73898. return;
  73899. }
  73900. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73901. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73902. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73903. effect.setFloat("radius", _this.radius);
  73904. effect.setTexture("depthSampler", _this._depthTexture);
  73905. if (_this._firstUpdate) {
  73906. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73907. _this._firstUpdate = false;
  73908. }
  73909. };
  73910. };
  73911. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73912. this._firstUpdate = true;
  73913. _super.prototype._rebuild.call(this);
  73914. };
  73915. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73916. var numSamples = this.samples;
  73917. var result = [];
  73918. var vector, scale;
  73919. var rand = function (min, max) {
  73920. return Math.random() * (max - min) + min;
  73921. };
  73922. var i = 0;
  73923. while (i < numSamples) {
  73924. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73925. vector.normalize();
  73926. scale = i / numSamples;
  73927. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73928. vector.scaleInPlace(scale);
  73929. result.push(vector.x, vector.y, vector.z);
  73930. i++;
  73931. }
  73932. return result;
  73933. };
  73934. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73935. var _this = this;
  73936. var numSamples = this.samples;
  73937. this._sampleSphere = this._generateHemisphere();
  73938. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73939. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73940. "base", "range", "projection", "near", "far", "texelSize",
  73941. "xViewport", "yViewport", "maxZ", "minZAspect"
  73942. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73943. this._ssaoPostProcess.onApply = function (effect) {
  73944. if (_this._firstUpdate) {
  73945. effect.setArray3("sampleSphere", _this._sampleSphere);
  73946. effect.setFloat("randTextureTiles", 4.0);
  73947. }
  73948. if (!_this._scene.activeCamera) {
  73949. return;
  73950. }
  73951. effect.setFloat("samplesFactor", 1 / _this.samples);
  73952. effect.setFloat("totalStrength", _this.totalStrength);
  73953. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73954. effect.setFloat("radius", _this.radius);
  73955. effect.setFloat("maxZ", _this.maxZ);
  73956. effect.setFloat("minZAspect", _this.minZAspect);
  73957. effect.setFloat("base", _this.base);
  73958. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73959. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73960. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73961. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73962. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73963. effect.setTexture("textureSampler", _this._depthTexture);
  73964. effect.setTexture("normalSampler", _this._normalTexture);
  73965. effect.setTexture("randomSampler", _this._randomTexture);
  73966. };
  73967. };
  73968. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73969. var _this = this;
  73970. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73971. this._ssaoCombinePostProcess.onApply = function (effect) {
  73972. var viewport = _this._scene.activeCamera.viewport;
  73973. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73974. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73975. };
  73976. };
  73977. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73978. var size = 512;
  73979. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73980. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73981. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73982. var context = this._randomTexture.getContext();
  73983. var rand = function (min, max) {
  73984. return Math.random() * (max - min) + min;
  73985. };
  73986. var randVector = BABYLON.Vector3.Zero();
  73987. for (var x = 0; x < size; x++) {
  73988. for (var y = 0; y < size; y++) {
  73989. randVector.x = rand(0.0, 1.0);
  73990. randVector.y = rand(0.0, 1.0);
  73991. randVector.z = 0.0;
  73992. randVector.normalize();
  73993. randVector.scaleInPlace(255);
  73994. randVector.x = Math.floor(randVector.x);
  73995. randVector.y = Math.floor(randVector.y);
  73996. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73997. context.fillRect(x, y, 1, 1);
  73998. }
  73999. }
  74000. this._randomTexture.update(false);
  74001. };
  74002. /**
  74003. * Serialize the rendering pipeline (Used when exporting)
  74004. * @returns the serialized object
  74005. */
  74006. SSAO2RenderingPipeline.prototype.serialize = function () {
  74007. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74008. serializationObject.customType = "SSAO2RenderingPipeline";
  74009. return serializationObject;
  74010. };
  74011. /**
  74012. * Parse the serialized pipeline
  74013. * @param source Source pipeline.
  74014. * @param scene The scene to load the pipeline to.
  74015. * @param rootUrl The URL of the serialized pipeline.
  74016. * @returns An instantiated pipeline from the serialized object.
  74017. */
  74018. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74019. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74020. };
  74021. __decorate([
  74022. BABYLON.serialize()
  74023. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74024. __decorate([
  74025. BABYLON.serialize()
  74026. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74027. __decorate([
  74028. BABYLON.serialize()
  74029. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74030. __decorate([
  74031. BABYLON.serialize("samples")
  74032. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74033. __decorate([
  74034. BABYLON.serialize()
  74035. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74036. __decorate([
  74037. BABYLON.serialize("expensiveBlur")
  74038. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74039. __decorate([
  74040. BABYLON.serialize()
  74041. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74042. __decorate([
  74043. BABYLON.serialize()
  74044. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74045. return SSAO2RenderingPipeline;
  74046. }(BABYLON.PostProcessRenderPipeline));
  74047. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74048. })(BABYLON || (BABYLON = {}));
  74049. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74050. // BABYLON.JS Chromatic Aberration GLSL Shader
  74051. // Author: Olivier Guyot
  74052. // Separates very slightly R, G and B colors on the edges of the screen
  74053. // Inspired by Francois Tarlier & Martins Upitis
  74054. var BABYLON;
  74055. (function (BABYLON) {
  74056. var LensRenderingPipeline = /** @class */ (function (_super) {
  74057. __extends(LensRenderingPipeline, _super);
  74058. /**
  74059. * @constructor
  74060. *
  74061. * Effect parameters are as follow:
  74062. * {
  74063. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74064. * edge_blur: number; // from 0 to x (1 for realism)
  74065. * distortion: number; // from 0 to x (1 for realism)
  74066. * grain_amount: number; // from 0 to 1
  74067. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74068. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74069. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74070. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74071. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74072. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74073. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74074. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74075. * }
  74076. * Note: if an effect parameter is unset, effect is disabled
  74077. *
  74078. * @param {string} name - The rendering pipeline name
  74079. * @param {object} parameters - An object containing all parameters (see above)
  74080. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74081. * @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)
  74082. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74083. */
  74084. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74085. if (ratio === void 0) { ratio = 1.0; }
  74086. var _this = _super.call(this, scene.getEngine(), name) || this;
  74087. // Lens effects can be of the following:
  74088. // - chromatic aberration (slight shift of RGB colors)
  74089. // - blur on the edge of the lens
  74090. // - lens distortion
  74091. // - depth-of-field blur & highlights enhancing
  74092. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74093. // - grain effect (noise or custom texture)
  74094. // Two additional texture samplers are needed:
  74095. // - depth map (for depth-of-field)
  74096. // - grain texture
  74097. /**
  74098. * The chromatic aberration PostProcess id in the pipeline
  74099. */
  74100. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74101. /**
  74102. * The highlights enhancing PostProcess id in the pipeline
  74103. */
  74104. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74105. /**
  74106. * The depth-of-field PostProcess id in the pipeline
  74107. */
  74108. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74109. _this._scene = scene;
  74110. // Fetch texture samplers
  74111. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74112. if (parameters.grain_texture) {
  74113. _this._grainTexture = parameters.grain_texture;
  74114. }
  74115. else {
  74116. _this._createGrainTexture();
  74117. }
  74118. // save parameters
  74119. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74120. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74121. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74122. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74123. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74124. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74125. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74126. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74127. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74128. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74129. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74130. // Create effects
  74131. _this._createChromaticAberrationPostProcess(ratio);
  74132. _this._createHighlightsPostProcess(ratio);
  74133. _this._createDepthOfFieldPostProcess(ratio / 4);
  74134. // Set up pipeline
  74135. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74136. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74137. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74138. if (_this._highlightsGain === -1) {
  74139. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74140. }
  74141. // Finish
  74142. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74143. if (cameras) {
  74144. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74145. }
  74146. return _this;
  74147. }
  74148. // public methods (self explanatory)
  74149. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74150. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74151. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74152. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74153. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74154. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74155. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74156. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74157. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74158. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74159. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74160. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74161. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74162. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74163. };
  74164. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74165. this._highlightsPostProcess.updateEffect();
  74166. };
  74167. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74168. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74169. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74170. this._highlightsGain = amount;
  74171. };
  74172. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74173. if (this._highlightsGain === -1) {
  74174. this._highlightsGain = 1.0;
  74175. }
  74176. this._highlightsThreshold = amount;
  74177. };
  74178. LensRenderingPipeline.prototype.disableHighlights = function () {
  74179. this._highlightsGain = -1;
  74180. };
  74181. /**
  74182. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74183. */
  74184. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74185. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74186. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74187. this._chromaticAberrationPostProcess = null;
  74188. this._highlightsPostProcess = null;
  74189. this._depthOfFieldPostProcess = null;
  74190. this._grainTexture.dispose();
  74191. if (disableDepthRender)
  74192. this._scene.disableDepthRenderer();
  74193. };
  74194. // colors shifting and distortion
  74195. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74196. var _this = this;
  74197. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74198. [], // samplers
  74199. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74200. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74201. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74202. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74203. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74204. effect.setFloat('radialIntensity', 1);
  74205. effect.setFloat2('direction', 17, 17);
  74206. effect.setFloat2('centerPosition', 0.5, 0.5);
  74207. };
  74208. };
  74209. // highlights enhancing
  74210. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74211. var _this = this;
  74212. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74213. [], // samplers
  74214. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74215. this._highlightsPostProcess.onApply = function (effect) {
  74216. effect.setFloat('gain', _this._highlightsGain);
  74217. effect.setFloat('threshold', _this._highlightsThreshold);
  74218. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74219. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74220. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74221. };
  74222. };
  74223. // colors shifting and distortion
  74224. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74225. var _this = this;
  74226. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74227. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74228. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74229. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74230. this._depthOfFieldPostProcess.onApply = function (effect) {
  74231. effect.setTexture("depthSampler", _this._depthTexture);
  74232. effect.setTexture("grainSampler", _this._grainTexture);
  74233. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74234. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74235. effect.setFloat('grain_amount', _this._grainAmount);
  74236. effect.setBool('blur_noise', _this._blurNoise);
  74237. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74238. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74239. effect.setFloat('distortion', _this._distortion);
  74240. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74241. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74242. effect.setFloat('aperture', _this._dofAperture);
  74243. effect.setFloat('darken', _this._dofDarken);
  74244. effect.setFloat('edge_blur', _this._edgeBlur);
  74245. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74246. if (_this._scene.activeCamera) {
  74247. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74248. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74249. }
  74250. };
  74251. };
  74252. // creates a black and white random noise texture, 512x512
  74253. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74254. var size = 512;
  74255. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74256. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74257. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74258. var context = this._grainTexture.getContext();
  74259. var rand = function (min, max) {
  74260. return Math.random() * (max - min) + min;
  74261. };
  74262. var value;
  74263. for (var x = 0; x < size; x++) {
  74264. for (var y = 0; y < size; y++) {
  74265. value = Math.floor(rand(0.42, 0.58) * 255);
  74266. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74267. context.fillRect(x, y, 1, 1);
  74268. }
  74269. }
  74270. this._grainTexture.update(false);
  74271. };
  74272. return LensRenderingPipeline;
  74273. }(BABYLON.PostProcessRenderPipeline));
  74274. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74275. })(BABYLON || (BABYLON = {}));
  74276. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74277. var BABYLON;
  74278. (function (BABYLON) {
  74279. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74280. __extends(StandardRenderingPipeline, _super);
  74281. /**
  74282. * @constructor
  74283. * @param {string} name - The rendering pipeline name
  74284. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74285. * @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)
  74286. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74287. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74288. */
  74289. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74290. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74291. var _this = _super.call(this, scene.getEngine(), name) || this;
  74292. _this.downSampleX4PostProcess = null;
  74293. _this.brightPassPostProcess = null;
  74294. _this.blurHPostProcesses = [];
  74295. _this.blurVPostProcesses = [];
  74296. _this.textureAdderPostProcess = null;
  74297. _this.volumetricLightPostProcess = null;
  74298. _this.volumetricLightSmoothXPostProcess = null;
  74299. _this.volumetricLightSmoothYPostProcess = null;
  74300. _this.volumetricLightMergePostProces = null;
  74301. _this.volumetricLightFinalPostProcess = null;
  74302. _this.luminancePostProcess = null;
  74303. _this.luminanceDownSamplePostProcesses = [];
  74304. _this.hdrPostProcess = null;
  74305. _this.textureAdderFinalPostProcess = null;
  74306. _this.lensFlareFinalPostProcess = null;
  74307. _this.hdrFinalPostProcess = null;
  74308. _this.lensFlarePostProcess = null;
  74309. _this.lensFlareComposePostProcess = null;
  74310. _this.motionBlurPostProcess = null;
  74311. _this.depthOfFieldPostProcess = null;
  74312. // Values
  74313. _this.brightThreshold = 1.0;
  74314. _this.blurWidth = 512.0;
  74315. _this.horizontalBlur = false;
  74316. _this.exposure = 1.0;
  74317. _this.lensTexture = null;
  74318. _this.volumetricLightCoefficient = 0.2;
  74319. _this.volumetricLightPower = 4.0;
  74320. _this.volumetricLightBlurScale = 64.0;
  74321. _this.sourceLight = null;
  74322. _this.hdrMinimumLuminance = 1.0;
  74323. _this.hdrDecreaseRate = 0.5;
  74324. _this.hdrIncreaseRate = 0.5;
  74325. _this.lensColorTexture = null;
  74326. _this.lensFlareStrength = 20.0;
  74327. _this.lensFlareGhostDispersal = 1.4;
  74328. _this.lensFlareHaloWidth = 0.7;
  74329. _this.lensFlareDistortionStrength = 16.0;
  74330. _this.lensStarTexture = null;
  74331. _this.lensFlareDirtTexture = null;
  74332. _this.depthOfFieldDistance = 10.0;
  74333. _this.depthOfFieldBlurWidth = 64.0;
  74334. _this.motionStrength = 1.0;
  74335. // IAnimatable
  74336. _this.animations = [];
  74337. _this._currentDepthOfFieldSource = null;
  74338. _this._hdrCurrentLuminance = 1.0;
  74339. // Getters and setters
  74340. _this._bloomEnabled = true;
  74341. _this._depthOfFieldEnabled = false;
  74342. _this._vlsEnabled = false;
  74343. _this._lensFlareEnabled = false;
  74344. _this._hdrEnabled = false;
  74345. _this._motionBlurEnabled = false;
  74346. _this._motionBlurSamples = 64.0;
  74347. _this._volumetricLightStepsCount = 50.0;
  74348. _this._cameras = cameras || [];
  74349. // Initialize
  74350. _this._scene = scene;
  74351. _this._basePostProcess = originalPostProcess;
  74352. _this._ratio = ratio;
  74353. // Misc
  74354. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74355. // Finish
  74356. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74357. _this._buildPipeline();
  74358. return _this;
  74359. }
  74360. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74361. get: function () {
  74362. return this._bloomEnabled;
  74363. },
  74364. set: function (enabled) {
  74365. if (this._bloomEnabled === enabled) {
  74366. return;
  74367. }
  74368. this._bloomEnabled = enabled;
  74369. this._buildPipeline();
  74370. },
  74371. enumerable: true,
  74372. configurable: true
  74373. });
  74374. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74375. get: function () {
  74376. return this._depthOfFieldEnabled;
  74377. },
  74378. set: function (enabled) {
  74379. if (this._depthOfFieldEnabled === enabled) {
  74380. return;
  74381. }
  74382. this._depthOfFieldEnabled = enabled;
  74383. this._buildPipeline();
  74384. },
  74385. enumerable: true,
  74386. configurable: true
  74387. });
  74388. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74389. get: function () {
  74390. return this._lensFlareEnabled;
  74391. },
  74392. set: function (enabled) {
  74393. if (this._lensFlareEnabled === enabled) {
  74394. return;
  74395. }
  74396. this._lensFlareEnabled = enabled;
  74397. this._buildPipeline();
  74398. },
  74399. enumerable: true,
  74400. configurable: true
  74401. });
  74402. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74403. get: function () {
  74404. return this._hdrEnabled;
  74405. },
  74406. set: function (enabled) {
  74407. if (this._hdrEnabled === enabled) {
  74408. return;
  74409. }
  74410. this._hdrEnabled = enabled;
  74411. this._buildPipeline();
  74412. },
  74413. enumerable: true,
  74414. configurable: true
  74415. });
  74416. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74417. get: function () {
  74418. return this._vlsEnabled;
  74419. },
  74420. set: function (enabled) {
  74421. if (this._vlsEnabled === enabled) {
  74422. return;
  74423. }
  74424. if (enabled) {
  74425. var geometry = this._scene.enableGeometryBufferRenderer();
  74426. if (!geometry) {
  74427. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74428. return;
  74429. }
  74430. }
  74431. this._vlsEnabled = enabled;
  74432. this._buildPipeline();
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74438. get: function () {
  74439. return this._motionBlurEnabled;
  74440. },
  74441. set: function (enabled) {
  74442. if (this._motionBlurEnabled === enabled) {
  74443. return;
  74444. }
  74445. this._motionBlurEnabled = enabled;
  74446. this._buildPipeline();
  74447. },
  74448. enumerable: true,
  74449. configurable: true
  74450. });
  74451. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74452. get: function () {
  74453. return this._volumetricLightStepsCount;
  74454. },
  74455. set: function (count) {
  74456. if (this.volumetricLightPostProcess) {
  74457. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74458. }
  74459. this._volumetricLightStepsCount = count;
  74460. },
  74461. enumerable: true,
  74462. configurable: true
  74463. });
  74464. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74465. get: function () {
  74466. return this._motionBlurSamples;
  74467. },
  74468. set: function (samples) {
  74469. if (this.motionBlurPostProcess) {
  74470. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74471. }
  74472. this._motionBlurSamples = samples;
  74473. },
  74474. enumerable: true,
  74475. configurable: true
  74476. });
  74477. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74478. var _this = this;
  74479. var ratio = this._ratio;
  74480. var scene = this._scene;
  74481. this._disposePostProcesses();
  74482. this._reset();
  74483. // Create pass post-process
  74484. if (!this._basePostProcess) {
  74485. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74486. this.originalPostProcess.onApply = function (effect) {
  74487. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74488. };
  74489. }
  74490. else {
  74491. this.originalPostProcess = this._basePostProcess;
  74492. }
  74493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74494. this._currentDepthOfFieldSource = this.originalPostProcess;
  74495. if (this._bloomEnabled) {
  74496. // Create down sample X4 post-process
  74497. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74498. // Create bright pass post-process
  74499. this._createBrightPassPostProcess(scene, ratio / 2);
  74500. // Create gaussian blur post-processes (down sampling blurs)
  74501. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74502. // Create texture adder post-process
  74503. this._createTextureAdderPostProcess(scene, ratio);
  74504. // Create depth-of-field source post-process
  74505. 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);
  74506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74507. }
  74508. if (this._vlsEnabled) {
  74509. // Create volumetric light
  74510. this._createVolumetricLightPostProcess(scene, ratio);
  74511. // Create volumetric light final post-process
  74512. 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);
  74513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74514. }
  74515. if (this._lensFlareEnabled) {
  74516. // Create lens flare post-process
  74517. this._createLensFlarePostProcess(scene, ratio);
  74518. // Create depth-of-field source post-process post lens-flare and disable it now
  74519. 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);
  74520. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74521. }
  74522. if (this._hdrEnabled) {
  74523. // Create luminance
  74524. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74525. // Create HDR
  74526. this._createHdrPostProcess(scene, ratio);
  74527. // Create depth-of-field source post-process post hdr and disable it now
  74528. 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);
  74529. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74530. }
  74531. if (this._depthOfFieldEnabled) {
  74532. // Create gaussian blur used by depth-of-field
  74533. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74534. // Create depth-of-field post-process
  74535. this._createDepthOfFieldPostProcess(scene, ratio);
  74536. }
  74537. if (this._motionBlurEnabled) {
  74538. // Create motion blur post-process
  74539. this._createMotionBlurPostProcess(scene, ratio);
  74540. }
  74541. if (this._cameras !== null) {
  74542. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74543. }
  74544. };
  74545. // Down Sample X4 Post-Processs
  74546. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74547. var _this = this;
  74548. var downSampleX4Offsets = new Array(32);
  74549. 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);
  74550. this.downSampleX4PostProcess.onApply = function (effect) {
  74551. var id = 0;
  74552. var width = _this.downSampleX4PostProcess.width;
  74553. var height = _this.downSampleX4PostProcess.height;
  74554. for (var i = -2; i < 2; i++) {
  74555. for (var j = -2; j < 2; j++) {
  74556. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74557. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74558. id += 2;
  74559. }
  74560. }
  74561. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74562. };
  74563. // Add to pipeline
  74564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74565. };
  74566. // Brightpass Post-Process
  74567. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74568. var _this = this;
  74569. var brightOffsets = new Array(8);
  74570. 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);
  74571. this.brightPassPostProcess.onApply = function (effect) {
  74572. var sU = (1.0 / _this.brightPassPostProcess.width);
  74573. var sV = (1.0 / _this.brightPassPostProcess.height);
  74574. brightOffsets[0] = -0.5 * sU;
  74575. brightOffsets[1] = 0.5 * sV;
  74576. brightOffsets[2] = 0.5 * sU;
  74577. brightOffsets[3] = 0.5 * sV;
  74578. brightOffsets[4] = -0.5 * sU;
  74579. brightOffsets[5] = -0.5 * sV;
  74580. brightOffsets[6] = 0.5 * sU;
  74581. brightOffsets[7] = -0.5 * sV;
  74582. effect.setArray2("dsOffsets", brightOffsets);
  74583. effect.setFloat("brightThreshold", _this.brightThreshold);
  74584. };
  74585. // Add to pipeline
  74586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74587. };
  74588. // Create blur H&V post-processes
  74589. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74590. var _this = this;
  74591. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74592. var engine = scene.getEngine();
  74593. 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);
  74594. 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);
  74595. blurX.onActivateObservable.add(function () {
  74596. var dw = blurX.width / engine.getRenderWidth();
  74597. blurX.kernel = _this[blurWidthKey] * dw;
  74598. });
  74599. blurY.onActivateObservable.add(function () {
  74600. var dw = blurY.height / engine.getRenderHeight();
  74601. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74602. });
  74603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74604. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74605. this.blurHPostProcesses.push(blurX);
  74606. this.blurVPostProcesses.push(blurY);
  74607. };
  74608. // Create texture adder post-process
  74609. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74610. var _this = this;
  74611. 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);
  74612. this.textureAdderPostProcess.onApply = function (effect) {
  74613. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74614. effect.setTexture("lensSampler", _this.lensTexture);
  74615. effect.setFloat("exposure", _this.exposure);
  74616. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74617. };
  74618. // Add to pipeline
  74619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74620. };
  74621. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74622. var _this = this;
  74623. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74624. geometryRenderer.enablePosition = true;
  74625. var geometry = geometryRenderer.getGBuffer();
  74626. // Base post-process
  74627. 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));
  74628. var depthValues = BABYLON.Vector2.Zero();
  74629. this.volumetricLightPostProcess.onApply = function (effect) {
  74630. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74631. var generator = _this.sourceLight.getShadowGenerator();
  74632. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74633. effect.setTexture("positionSampler", geometry.textures[2]);
  74634. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74635. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74636. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74637. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74638. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74639. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74640. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74641. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74642. effect.setVector2("depthValues", depthValues);
  74643. }
  74644. };
  74645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74646. // Smooth
  74647. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74648. // Merge
  74649. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74650. this.volumetricLightMergePostProces.onApply = function (effect) {
  74651. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74652. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74653. };
  74654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74655. };
  74656. // Create luminance
  74657. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74658. var _this = this;
  74659. // Create luminance
  74660. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74661. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74662. var offsets = [];
  74663. this.luminancePostProcess.onApply = function (effect) {
  74664. var sU = (1.0 / _this.luminancePostProcess.width);
  74665. var sV = (1.0 / _this.luminancePostProcess.height);
  74666. offsets[0] = -0.5 * sU;
  74667. offsets[1] = 0.5 * sV;
  74668. offsets[2] = 0.5 * sU;
  74669. offsets[3] = 0.5 * sV;
  74670. offsets[4] = -0.5 * sU;
  74671. offsets[5] = -0.5 * sV;
  74672. offsets[6] = 0.5 * sU;
  74673. offsets[7] = -0.5 * sV;
  74674. effect.setArray2("lumOffsets", offsets);
  74675. };
  74676. // Add to pipeline
  74677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74678. // Create down sample luminance
  74679. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74680. var size = Math.pow(3, i);
  74681. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74682. if (i === 0) {
  74683. defines += "#define FINAL_DOWN_SAMPLER";
  74684. }
  74685. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74686. this.luminanceDownSamplePostProcesses.push(postProcess);
  74687. }
  74688. // Create callbacks and add effects
  74689. var lastLuminance = this.luminancePostProcess;
  74690. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74691. var downSampleOffsets = new Array(18);
  74692. pp.onApply = function (effect) {
  74693. if (!lastLuminance) {
  74694. return;
  74695. }
  74696. var id = 0;
  74697. for (var x = -1; x < 2; x++) {
  74698. for (var y = -1; y < 2; y++) {
  74699. downSampleOffsets[id] = x / lastLuminance.width;
  74700. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74701. id += 2;
  74702. }
  74703. }
  74704. effect.setArray2("dsOffsets", downSampleOffsets);
  74705. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74706. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74707. lastLuminance = _this.luminancePostProcess;
  74708. }
  74709. else {
  74710. lastLuminance = pp;
  74711. }
  74712. };
  74713. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74714. pp.onAfterRender = function (effect) {
  74715. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74716. 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);
  74717. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74718. };
  74719. }
  74720. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74721. });
  74722. };
  74723. // Create HDR post-process
  74724. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74725. var _this = this;
  74726. 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);
  74727. var outputLiminance = 1;
  74728. var time = 0;
  74729. var lastTime = 0;
  74730. this.hdrPostProcess.onApply = function (effect) {
  74731. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74732. time += scene.getEngine().getDeltaTime();
  74733. if (outputLiminance < 0) {
  74734. outputLiminance = _this._hdrCurrentLuminance;
  74735. }
  74736. else {
  74737. var dt = (lastTime - time) / 1000.0;
  74738. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74739. outputLiminance += _this.hdrDecreaseRate * dt;
  74740. }
  74741. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74742. outputLiminance -= _this.hdrIncreaseRate * dt;
  74743. }
  74744. else {
  74745. outputLiminance = _this._hdrCurrentLuminance;
  74746. }
  74747. }
  74748. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74749. effect.setFloat("averageLuminance", outputLiminance);
  74750. lastTime = time;
  74751. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74752. };
  74753. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74754. };
  74755. // Create lens flare post-process
  74756. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74757. var _this = this;
  74758. 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);
  74759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74760. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74761. 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);
  74762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74763. var resolution = new BABYLON.Vector2(0, 0);
  74764. // Lens flare
  74765. this.lensFlarePostProcess.onApply = function (effect) {
  74766. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74767. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74768. effect.setFloat("strength", _this.lensFlareStrength);
  74769. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74770. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74771. // Shift
  74772. resolution.x = _this.lensFlarePostProcess.width;
  74773. resolution.y = _this.lensFlarePostProcess.height;
  74774. effect.setVector2("resolution", resolution);
  74775. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74776. };
  74777. // Compose
  74778. 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);
  74779. 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);
  74780. this.lensFlareComposePostProcess.onApply = function (effect) {
  74781. if (!_this._scene.activeCamera) {
  74782. return;
  74783. }
  74784. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74785. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74786. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74787. // Lens start rotation matrix
  74788. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74789. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74790. 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));
  74791. camRot *= 4.0;
  74792. 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);
  74793. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74794. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74795. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74796. };
  74797. };
  74798. // Create depth-of-field post-process
  74799. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74800. var _this = this;
  74801. 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);
  74802. this.depthOfFieldPostProcess.onApply = function (effect) {
  74803. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74804. effect.setTexture("depthSampler", _this._getDepthTexture());
  74805. effect.setFloat("distance", _this.depthOfFieldDistance);
  74806. };
  74807. // Add to pipeline
  74808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74809. };
  74810. // Create motion blur post-process
  74811. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74812. var _this = this;
  74813. 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);
  74814. var motionScale = 0;
  74815. var prevViewProjection = BABYLON.Matrix.Identity();
  74816. var invViewProjection = BABYLON.Matrix.Identity();
  74817. var viewProjection = BABYLON.Matrix.Identity();
  74818. var screenSize = BABYLON.Vector2.Zero();
  74819. this.motionBlurPostProcess.onApply = function (effect) {
  74820. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74821. viewProjection.invertToRef(invViewProjection);
  74822. effect.setMatrix("inverseViewProjection", invViewProjection);
  74823. effect.setMatrix("prevViewProjection", prevViewProjection);
  74824. prevViewProjection = viewProjection;
  74825. screenSize.x = _this.motionBlurPostProcess.width;
  74826. screenSize.y = _this.motionBlurPostProcess.height;
  74827. effect.setVector2("screenSize", screenSize);
  74828. motionScale = scene.getEngine().getFps() / 60.0;
  74829. effect.setFloat("motionScale", motionScale);
  74830. effect.setFloat("motionStrength", _this.motionStrength);
  74831. effect.setTexture("depthSampler", _this._getDepthTexture());
  74832. };
  74833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74834. };
  74835. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74836. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74837. var renderer = this._scene.enableGeometryBufferRenderer();
  74838. return renderer.getGBuffer().textures[0];
  74839. }
  74840. return this._scene.enableDepthRenderer().getDepthMap();
  74841. };
  74842. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74843. for (var i = 0; i < this._cameras.length; i++) {
  74844. var camera = this._cameras[i];
  74845. if (this.originalPostProcess) {
  74846. this.originalPostProcess.dispose(camera);
  74847. }
  74848. if (this.downSampleX4PostProcess) {
  74849. this.downSampleX4PostProcess.dispose(camera);
  74850. }
  74851. if (this.brightPassPostProcess) {
  74852. this.brightPassPostProcess.dispose(camera);
  74853. }
  74854. if (this.textureAdderPostProcess) {
  74855. this.textureAdderPostProcess.dispose(camera);
  74856. }
  74857. if (this.textureAdderFinalPostProcess) {
  74858. this.textureAdderFinalPostProcess.dispose(camera);
  74859. }
  74860. if (this.volumetricLightPostProcess) {
  74861. this.volumetricLightPostProcess.dispose(camera);
  74862. }
  74863. if (this.volumetricLightSmoothXPostProcess) {
  74864. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74865. }
  74866. if (this.volumetricLightSmoothYPostProcess) {
  74867. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74868. }
  74869. if (this.volumetricLightMergePostProces) {
  74870. this.volumetricLightMergePostProces.dispose(camera);
  74871. }
  74872. if (this.volumetricLightFinalPostProcess) {
  74873. this.volumetricLightFinalPostProcess.dispose(camera);
  74874. }
  74875. if (this.lensFlarePostProcess) {
  74876. this.lensFlarePostProcess.dispose(camera);
  74877. }
  74878. if (this.lensFlareComposePostProcess) {
  74879. this.lensFlareComposePostProcess.dispose(camera);
  74880. }
  74881. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74882. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74883. }
  74884. if (this.luminancePostProcess) {
  74885. this.luminancePostProcess.dispose(camera);
  74886. }
  74887. if (this.hdrPostProcess) {
  74888. this.hdrPostProcess.dispose(camera);
  74889. }
  74890. if (this.hdrFinalPostProcess) {
  74891. this.hdrFinalPostProcess.dispose(camera);
  74892. }
  74893. if (this.depthOfFieldPostProcess) {
  74894. this.depthOfFieldPostProcess.dispose(camera);
  74895. }
  74896. if (this.motionBlurPostProcess) {
  74897. this.motionBlurPostProcess.dispose(camera);
  74898. }
  74899. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74900. this.blurHPostProcesses[j].dispose(camera);
  74901. }
  74902. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74903. this.blurVPostProcesses[j].dispose(camera);
  74904. }
  74905. }
  74906. this.originalPostProcess = null;
  74907. this.downSampleX4PostProcess = null;
  74908. this.brightPassPostProcess = null;
  74909. this.textureAdderPostProcess = null;
  74910. this.textureAdderFinalPostProcess = null;
  74911. this.volumetricLightPostProcess = null;
  74912. this.volumetricLightSmoothXPostProcess = null;
  74913. this.volumetricLightSmoothYPostProcess = null;
  74914. this.volumetricLightMergePostProces = null;
  74915. this.volumetricLightFinalPostProcess = null;
  74916. this.lensFlarePostProcess = null;
  74917. this.lensFlareComposePostProcess = null;
  74918. this.luminancePostProcess = null;
  74919. this.hdrPostProcess = null;
  74920. this.hdrFinalPostProcess = null;
  74921. this.depthOfFieldPostProcess = null;
  74922. this.motionBlurPostProcess = null;
  74923. this.luminanceDownSamplePostProcesses = [];
  74924. this.blurHPostProcesses = [];
  74925. this.blurVPostProcesses = [];
  74926. };
  74927. /**
  74928. * Dispose of the pipeline and stop all post processes
  74929. */
  74930. StandardRenderingPipeline.prototype.dispose = function () {
  74931. this._disposePostProcesses();
  74932. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74933. _super.prototype.dispose.call(this);
  74934. };
  74935. /**
  74936. * Serialize the rendering pipeline (Used when exporting)
  74937. * @returns the serialized object
  74938. */
  74939. StandardRenderingPipeline.prototype.serialize = function () {
  74940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74941. if (this.sourceLight) {
  74942. serializationObject.sourceLightId = this.sourceLight.id;
  74943. }
  74944. serializationObject.customType = "StandardRenderingPipeline";
  74945. return serializationObject;
  74946. };
  74947. /**
  74948. * Parse the serialized pipeline
  74949. * @param source Source pipeline.
  74950. * @param scene The scene to load the pipeline to.
  74951. * @param rootUrl The URL of the serialized pipeline.
  74952. * @returns An instantiated pipeline from the serialized object.
  74953. */
  74954. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74955. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74956. if (source.sourceLightId) {
  74957. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74958. }
  74959. return p;
  74960. };
  74961. // Luminance steps
  74962. StandardRenderingPipeline.LuminanceSteps = 6;
  74963. __decorate([
  74964. BABYLON.serialize()
  74965. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74966. __decorate([
  74967. BABYLON.serialize()
  74968. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74969. __decorate([
  74970. BABYLON.serialize()
  74971. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74972. __decorate([
  74973. BABYLON.serialize()
  74974. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74975. __decorate([
  74976. BABYLON.serializeAsTexture("lensTexture")
  74977. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74978. __decorate([
  74979. BABYLON.serialize()
  74980. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74981. __decorate([
  74982. BABYLON.serialize()
  74983. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74984. __decorate([
  74985. BABYLON.serialize()
  74986. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74987. __decorate([
  74988. BABYLON.serialize()
  74989. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74990. __decorate([
  74991. BABYLON.serialize()
  74992. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74993. __decorate([
  74994. BABYLON.serialize()
  74995. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74996. __decorate([
  74997. BABYLON.serializeAsTexture("lensColorTexture")
  74998. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74999. __decorate([
  75000. BABYLON.serialize()
  75001. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75002. __decorate([
  75003. BABYLON.serialize()
  75004. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75005. __decorate([
  75006. BABYLON.serialize()
  75007. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75008. __decorate([
  75009. BABYLON.serialize()
  75010. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75011. __decorate([
  75012. BABYLON.serializeAsTexture("lensStarTexture")
  75013. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75014. __decorate([
  75015. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75016. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75017. __decorate([
  75018. BABYLON.serialize()
  75019. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75020. __decorate([
  75021. BABYLON.serialize()
  75022. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75023. __decorate([
  75024. BABYLON.serialize()
  75025. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75026. __decorate([
  75027. BABYLON.serialize()
  75028. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75029. __decorate([
  75030. BABYLON.serialize()
  75031. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75032. __decorate([
  75033. BABYLON.serialize()
  75034. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75035. __decorate([
  75036. BABYLON.serialize()
  75037. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75038. __decorate([
  75039. BABYLON.serialize()
  75040. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75041. __decorate([
  75042. BABYLON.serialize()
  75043. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75044. __decorate([
  75045. BABYLON.serialize()
  75046. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75047. __decorate([
  75048. BABYLON.serialize()
  75049. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75050. __decorate([
  75051. BABYLON.serialize()
  75052. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75053. return StandardRenderingPipeline;
  75054. }(BABYLON.PostProcessRenderPipeline));
  75055. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75056. })(BABYLON || (BABYLON = {}));
  75057. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75058. var BABYLON;
  75059. (function (BABYLON) {
  75060. var FxaaPostProcess = /** @class */ (function (_super) {
  75061. __extends(FxaaPostProcess, _super);
  75062. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75063. if (camera === void 0) { camera = null; }
  75064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75065. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75066. var defines = _this._getDefines();
  75067. _this.updateEffect(defines);
  75068. _this.onApplyObservable.add(function (effect) {
  75069. var texelSize = _this.texelSize;
  75070. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75071. });
  75072. return _this;
  75073. }
  75074. FxaaPostProcess.prototype._getDefines = function () {
  75075. var engine = this.getEngine();
  75076. if (!engine) {
  75077. return null;
  75078. }
  75079. var glInfo = engine.getGlInfo();
  75080. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75081. return "#define MALI 1\n";
  75082. }
  75083. return null;
  75084. };
  75085. return FxaaPostProcess;
  75086. }(BABYLON.PostProcess));
  75087. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75088. })(BABYLON || (BABYLON = {}));
  75089. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75090. var BABYLON;
  75091. (function (BABYLON) {
  75092. /**
  75093. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75094. */
  75095. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75096. __extends(ChromaticAberrationPostProcess, _super);
  75097. /**
  75098. * Creates a new instance ChromaticAberrationPostProcess
  75099. * @param name The name of the effect.
  75100. * @param screenWidth The width of the screen to apply the effect on.
  75101. * @param screenHeight The height of the screen to apply the effect on.
  75102. * @param options The required width/height ratio to downsize to before computing the render pass.
  75103. * @param camera The camera to apply the render pass to.
  75104. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75105. * @param engine The engine which the post process will be applied. (default: current engine)
  75106. * @param reusable If the post process can be reused on the same frame. (default: false)
  75107. * @param textureType Type of textures used when performing the post process. (default: 0)
  75108. * @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)
  75109. */
  75110. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75111. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75112. if (blockCompilation === void 0) { blockCompilation = false; }
  75113. 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;
  75114. /**
  75115. * The amount of seperation of rgb channels (default: 30)
  75116. */
  75117. _this.aberrationAmount = 30;
  75118. /**
  75119. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75120. */
  75121. _this.radialIntensity = 0;
  75122. /**
  75123. * 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))
  75124. */
  75125. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75126. /**
  75127. * 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))
  75128. */
  75129. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75130. _this.onApplyObservable.add(function (effect) {
  75131. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75132. effect.setFloat('screen_width', screenWidth);
  75133. effect.setFloat('screen_height', screenHeight);
  75134. effect.setFloat('radialIntensity', _this.radialIntensity);
  75135. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75136. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75137. });
  75138. return _this;
  75139. }
  75140. return ChromaticAberrationPostProcess;
  75141. }(BABYLON.PostProcess));
  75142. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75143. })(BABYLON || (BABYLON = {}));
  75144. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75145. var BABYLON;
  75146. (function (BABYLON) {
  75147. /**
  75148. * The GrainPostProcess adds noise to the image at mid luminance levels
  75149. */
  75150. var GrainPostProcess = /** @class */ (function (_super) {
  75151. __extends(GrainPostProcess, _super);
  75152. /**
  75153. * Creates a new instance of @see GrainPostProcess
  75154. * @param name The name of the effect.
  75155. * @param options The required width/height ratio to downsize to before computing the render pass.
  75156. * @param camera The camera to apply the render pass to.
  75157. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75158. * @param engine The engine which the post process will be applied. (default: current engine)
  75159. * @param reusable If the post process can be reused on the same frame. (default: false)
  75160. * @param textureType Type of textures used when performing the post process. (default: 0)
  75161. * @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)
  75162. */
  75163. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75164. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75165. if (blockCompilation === void 0) { blockCompilation = false; }
  75166. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75167. /**
  75168. * The intensity of the grain added (default: 30)
  75169. */
  75170. _this.intensity = 30;
  75171. /**
  75172. * If the grain should be randomized on every frame
  75173. */
  75174. _this.animated = false;
  75175. _this.onApplyObservable.add(function (effect) {
  75176. effect.setFloat('intensity', _this.intensity);
  75177. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75178. });
  75179. return _this;
  75180. }
  75181. return GrainPostProcess;
  75182. }(BABYLON.PostProcess));
  75183. BABYLON.GrainPostProcess = GrainPostProcess;
  75184. })(BABYLON || (BABYLON = {}));
  75185. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75186. var BABYLON;
  75187. (function (BABYLON) {
  75188. /**
  75189. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75190. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75191. */
  75192. var SharpenPostProcess = /** @class */ (function (_super) {
  75193. __extends(SharpenPostProcess, _super);
  75194. /**
  75195. * Creates a new instance ConvolutionPostProcess
  75196. * @param name The name of the effect.
  75197. * @param options The required width/height ratio to downsize to before computing the render pass.
  75198. * @param camera The camera to apply the render pass to.
  75199. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75200. * @param engine The engine which the post process will be applied. (default: current engine)
  75201. * @param reusable If the post process can be reused on the same frame. (default: false)
  75202. * @param textureType Type of textures used when performing the post process. (default: 0)
  75203. * @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)
  75204. */
  75205. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75206. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75207. if (blockCompilation === void 0) { blockCompilation = false; }
  75208. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75209. /**
  75210. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75211. */
  75212. _this.colorAmount = 1.0;
  75213. /**
  75214. * How much sharpness should be applied (default: 0.3)
  75215. */
  75216. _this.edgeAmount = 0.3;
  75217. _this.onApply = function (effect) {
  75218. effect.setFloat2("screenSize", _this.width, _this.height);
  75219. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75220. };
  75221. return _this;
  75222. }
  75223. return SharpenPostProcess;
  75224. }(BABYLON.PostProcess));
  75225. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75226. })(BABYLON || (BABYLON = {}));
  75227. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75228. var BABYLON;
  75229. (function (BABYLON) {
  75230. /**
  75231. * The Blur Post Process which blurs an image based on a kernel and direction.
  75232. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75233. */
  75234. var BlurPostProcess = /** @class */ (function (_super) {
  75235. __extends(BlurPostProcess, _super);
  75236. /**
  75237. * Creates a new instance BlurPostProcess
  75238. * @param name The name of the effect.
  75239. * @param direction The direction in which to blur the image.
  75240. * @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.
  75241. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75242. * @param camera The camera to apply the render pass to.
  75243. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75244. * @param engine The engine which the post process will be applied. (default: current engine)
  75245. * @param reusable If the post process can be reused on the same frame. (default: false)
  75246. * @param textureType Type of textures used when performing the post process. (default: 0)
  75247. * @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)
  75248. */
  75249. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75252. if (defines === void 0) { defines = ""; }
  75253. if (blockCompilation === void 0) { blockCompilation = false; }
  75254. 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;
  75255. _this.direction = direction;
  75256. _this.blockCompilation = blockCompilation;
  75257. _this._packedFloat = false;
  75258. _this._staticDefines = "";
  75259. _this._staticDefines = defines;
  75260. _this.onApplyObservable.add(function (effect) {
  75261. if (_this._outputTexture) {
  75262. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75263. }
  75264. else {
  75265. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75266. }
  75267. });
  75268. _this.kernel = kernel;
  75269. return _this;
  75270. }
  75271. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75272. /**
  75273. * Gets the length in pixels of the blur sample region
  75274. */
  75275. get: function () {
  75276. return this._idealKernel;
  75277. },
  75278. /**
  75279. * Sets the length in pixels of the blur sample region
  75280. */
  75281. set: function (v) {
  75282. if (this._idealKernel === v) {
  75283. return;
  75284. }
  75285. v = Math.max(v, 1);
  75286. this._idealKernel = v;
  75287. this._kernel = this._nearestBestKernel(v);
  75288. if (!this.blockCompilation) {
  75289. this._updateParameters();
  75290. }
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75296. /**
  75297. * Gets wether or not the blur is unpacking/repacking floats
  75298. */
  75299. get: function () {
  75300. return this._packedFloat;
  75301. },
  75302. /**
  75303. * Sets wether or not the blur needs to unpack/repack floats
  75304. */
  75305. set: function (v) {
  75306. if (this._packedFloat === v) {
  75307. return;
  75308. }
  75309. this._packedFloat = v;
  75310. if (!this.blockCompilation) {
  75311. this._updateParameters();
  75312. }
  75313. },
  75314. enumerable: true,
  75315. configurable: true
  75316. });
  75317. /**
  75318. * Updates the effect with the current post process compile time values and recompiles the shader.
  75319. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75320. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75321. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75322. * @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
  75323. * @param onCompiled Called when the shader has been compiled.
  75324. * @param onError Called if there is an error when compiling a shader.
  75325. */
  75326. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75327. if (defines === void 0) { defines = null; }
  75328. if (uniforms === void 0) { uniforms = null; }
  75329. if (samplers === void 0) { samplers = null; }
  75330. this._updateParameters(onCompiled, onError);
  75331. };
  75332. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75333. // Generate sampling offsets and weights
  75334. var N = this._kernel;
  75335. var centerIndex = (N - 1) / 2;
  75336. // Generate Gaussian sampling weights over kernel
  75337. var offsets = [];
  75338. var weights = [];
  75339. var totalWeight = 0;
  75340. for (var i = 0; i < N; i++) {
  75341. var u = i / (N - 1);
  75342. var w = this._gaussianWeight(u * 2.0 - 1);
  75343. offsets[i] = (i - centerIndex);
  75344. weights[i] = w;
  75345. totalWeight += w;
  75346. }
  75347. // Normalize weights
  75348. for (var i = 0; i < weights.length; i++) {
  75349. weights[i] /= totalWeight;
  75350. }
  75351. // Optimize: combine samples to take advantage of hardware linear sampling
  75352. // Walk from left to center, combining pairs (symmetrically)
  75353. var linearSamplingWeights = [];
  75354. var linearSamplingOffsets = [];
  75355. var linearSamplingMap = [];
  75356. for (var i = 0; i <= centerIndex; i += 2) {
  75357. var j = Math.min(i + 1, Math.floor(centerIndex));
  75358. var singleCenterSample = i === j;
  75359. if (singleCenterSample) {
  75360. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75361. }
  75362. else {
  75363. var sharedCell = j === centerIndex;
  75364. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75365. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75366. if (offsetLinear === 0) {
  75367. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75368. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75369. }
  75370. else {
  75371. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75372. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75373. }
  75374. }
  75375. }
  75376. for (var i = 0; i < linearSamplingMap.length; i++) {
  75377. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75378. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75379. }
  75380. // Replace with optimized
  75381. offsets = linearSamplingOffsets;
  75382. weights = linearSamplingWeights;
  75383. // Generate shaders
  75384. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75385. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75386. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75387. var defines = "";
  75388. defines += this._staticDefines;
  75389. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75390. if (this._staticDefines.indexOf("DOF") != -1) {
  75391. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75392. varyingCount--;
  75393. }
  75394. for (var i = 0; i < varyingCount; i++) {
  75395. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75396. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75397. }
  75398. var depCount = 0;
  75399. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75400. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75401. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75402. depCount++;
  75403. }
  75404. if (this.packedFloat) {
  75405. defines += "#define PACKEDFLOAT 1";
  75406. }
  75407. this.blockCompilation = false;
  75408. _super.prototype.updateEffect.call(this, defines, null, null, {
  75409. varyingCount: varyingCount,
  75410. depCount: depCount
  75411. }, onCompiled, onError);
  75412. };
  75413. /**
  75414. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75415. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75416. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75417. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75418. * The gaps between physical kernels are compensated for in the weighting of the samples
  75419. * @param idealKernel Ideal blur kernel.
  75420. * @return Nearest best kernel.
  75421. */
  75422. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75423. var v = Math.round(idealKernel);
  75424. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75425. var k = _a[_i];
  75426. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75427. return Math.max(k, 3);
  75428. }
  75429. }
  75430. return Math.max(v, 3);
  75431. };
  75432. /**
  75433. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75434. * @param x The point on the Gaussian distribution to sample.
  75435. * @return the value of the Gaussian function at x.
  75436. */
  75437. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75438. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75439. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75440. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75441. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75442. // truncated at around 1.3% of peak strength.
  75443. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75444. var sigma = (1 / 3);
  75445. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75446. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75447. var weight = (1.0 / denominator) * Math.exp(exponent);
  75448. return weight;
  75449. };
  75450. /**
  75451. * Generates a string that can be used as a floating point number in GLSL.
  75452. * @param x Value to print.
  75453. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75454. * @return GLSL float string.
  75455. */
  75456. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75457. if (decimalFigures === void 0) { decimalFigures = 8; }
  75458. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75459. };
  75460. return BlurPostProcess;
  75461. }(BABYLON.PostProcess));
  75462. BABYLON.BlurPostProcess = BlurPostProcess;
  75463. })(BABYLON || (BABYLON = {}));
  75464. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75465. var BABYLON;
  75466. (function (BABYLON) {
  75467. /**
  75468. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75469. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75470. * based on samples that have a large difference in distance than the center pixel.
  75471. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75472. */
  75473. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75474. __extends(DepthOfFieldBlurPostProcess, _super);
  75475. /**
  75476. * Creates a new instance CircleOfConfusionPostProcess
  75477. * @param name The name of the effect.
  75478. * @param scene The scene the effect belongs to.
  75479. * @param direction The direction the blur should be applied.
  75480. * @param kernel The size of the kernel used to blur.
  75481. * @param options The required width/height ratio to downsize to before computing the render pass.
  75482. * @param camera The camera to apply the render pass to.
  75483. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75484. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75485. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75486. * @param engine The engine which the post process will be applied. (default: current engine)
  75487. * @param reusable If the post process can be reused on the same frame. (default: false)
  75488. * @param textureType Type of textures used when performing the post process. (default: 0)
  75489. * @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)
  75490. */
  75491. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75492. if (imageToBlur === void 0) { imageToBlur = null; }
  75493. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75495. if (blockCompilation === void 0) { blockCompilation = false; }
  75496. 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;
  75497. _this.direction = direction;
  75498. _this.onApplyObservable.add(function (effect) {
  75499. if (imageToBlur != null) {
  75500. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75501. }
  75502. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75503. if (scene.activeCamera) {
  75504. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75505. }
  75506. });
  75507. return _this;
  75508. }
  75509. return DepthOfFieldBlurPostProcess;
  75510. }(BABYLON.BlurPostProcess));
  75511. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75512. })(BABYLON || (BABYLON = {}));
  75513. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75514. var BABYLON;
  75515. (function (BABYLON) {
  75516. /**
  75517. * Options to be set when merging outputs from the default pipeline.
  75518. */
  75519. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75520. function DepthOfFieldMergePostProcessOptions() {
  75521. }
  75522. return DepthOfFieldMergePostProcessOptions;
  75523. }());
  75524. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75525. /**
  75526. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75527. */
  75528. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75529. __extends(DepthOfFieldMergePostProcess, _super);
  75530. /**
  75531. * Creates a new instance of DepthOfFieldMergePostProcess
  75532. * @param name The name of the effect.
  75533. * @param originalFromInput Post process which's input will be used for the merge.
  75534. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75535. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75536. * @param options The required width/height ratio to downsize to before computing the render pass.
  75537. * @param camera The camera to apply the render pass to.
  75538. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75539. * @param engine The engine which the post process will be applied. (default: current engine)
  75540. * @param reusable If the post process can be reused on the same frame. (default: false)
  75541. * @param textureType Type of textures used when performing the post process. (default: 0)
  75542. * @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)
  75543. */
  75544. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75545. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75546. if (blockCompilation === void 0) { blockCompilation = false; }
  75547. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75548. _this.blurSteps = blurSteps;
  75549. _this.onApplyObservable.add(function (effect) {
  75550. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75551. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75552. blurSteps.forEach(function (step, index) {
  75553. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75554. });
  75555. });
  75556. if (!blockCompilation) {
  75557. _this.updateEffect();
  75558. }
  75559. return _this;
  75560. }
  75561. /**
  75562. * Updates the effect with the current post process compile time values and recompiles the shader.
  75563. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75564. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75565. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75566. * @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
  75567. * @param onCompiled Called when the shader has been compiled.
  75568. * @param onError Called if there is an error when compiling a shader.
  75569. */
  75570. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75571. if (defines === void 0) { defines = null; }
  75572. if (uniforms === void 0) { uniforms = null; }
  75573. if (samplers === void 0) { samplers = null; }
  75574. if (!defines) {
  75575. defines = "";
  75576. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75577. }
  75578. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75579. };
  75580. return DepthOfFieldMergePostProcess;
  75581. }(BABYLON.PostProcess));
  75582. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75583. })(BABYLON || (BABYLON = {}));
  75584. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75585. var BABYLON;
  75586. (function (BABYLON) {
  75587. /**
  75588. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75589. */
  75590. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75591. __extends(CircleOfConfusionPostProcess, _super);
  75592. /**
  75593. * Creates a new instance CircleOfConfusionPostProcess
  75594. * @param name The name of the effect.
  75595. * @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.
  75596. * @param options The required width/height ratio to downsize to before computing the render pass.
  75597. * @param camera The camera to apply the render pass to.
  75598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75599. * @param engine The engine which the post process will be applied. (default: current engine)
  75600. * @param reusable If the post process can be reused on the same frame. (default: false)
  75601. * @param textureType Type of textures used when performing the post process. (default: 0)
  75602. * @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)
  75603. */
  75604. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75606. if (blockCompilation === void 0) { blockCompilation = false; }
  75607. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75608. /**
  75609. * 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.
  75610. */
  75611. _this.lensSize = 50;
  75612. /**
  75613. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75614. */
  75615. _this.fStop = 1.4;
  75616. /**
  75617. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75618. */
  75619. _this.focusDistance = 2000;
  75620. /**
  75621. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75622. */
  75623. _this.focalLength = 50;
  75624. _this._depthTexture = null;
  75625. _this._depthTexture = depthTexture;
  75626. _this.onApplyObservable.add(function (effect) {
  75627. if (!_this._depthTexture) {
  75628. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75629. return;
  75630. }
  75631. effect.setTexture("depthSampler", _this._depthTexture);
  75632. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75633. var aperture = _this.lensSize / _this.fStop;
  75634. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75635. effect.setFloat('focusDistance', _this.focusDistance);
  75636. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75637. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75638. });
  75639. return _this;
  75640. }
  75641. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75642. /**
  75643. * 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.
  75644. */
  75645. set: function (value) {
  75646. this._depthTexture = value;
  75647. },
  75648. enumerable: true,
  75649. configurable: true
  75650. });
  75651. return CircleOfConfusionPostProcess;
  75652. }(BABYLON.PostProcess));
  75653. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75654. })(BABYLON || (BABYLON = {}));
  75655. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75656. var BABYLON;
  75657. (function (BABYLON) {
  75658. /**
  75659. * Specifies the level of max blur that should be applied when using the depth of field effect
  75660. */
  75661. var DepthOfFieldEffectBlurLevel;
  75662. (function (DepthOfFieldEffectBlurLevel) {
  75663. /**
  75664. * Subtle blur
  75665. */
  75666. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75667. /**
  75668. * Medium blur
  75669. */
  75670. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75671. /**
  75672. * Large blur
  75673. */
  75674. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75675. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75676. ;
  75677. /**
  75678. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75679. */
  75680. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75681. __extends(DepthOfFieldEffect, _super);
  75682. /**
  75683. * Creates a new instance DepthOfFieldEffect
  75684. * @param scene The scene the effect belongs to.
  75685. * @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.
  75686. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75687. * @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)
  75688. */
  75689. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75690. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75691. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75692. if (blockCompilation === void 0) { blockCompilation = false; }
  75693. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75694. return _this._effects;
  75695. }, true) || this;
  75696. /**
  75697. * Internal post processes in depth of field effect
  75698. */
  75699. _this._effects = [];
  75700. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75701. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75702. // 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)
  75703. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75704. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75705. _this._depthOfFieldBlurY = [];
  75706. _this._depthOfFieldBlurX = [];
  75707. var blurCount = 1;
  75708. var kernelSize = 15;
  75709. switch (blurLevel) {
  75710. case DepthOfFieldEffectBlurLevel.High: {
  75711. blurCount = 3;
  75712. kernelSize = 51;
  75713. break;
  75714. }
  75715. case DepthOfFieldEffectBlurLevel.Medium: {
  75716. blurCount = 2;
  75717. kernelSize = 31;
  75718. break;
  75719. }
  75720. default: {
  75721. kernelSize = 15;
  75722. blurCount = 1;
  75723. break;
  75724. }
  75725. }
  75726. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75727. var ratio = 1.0;
  75728. for (var i = 0; i < blurCount; i++) {
  75729. 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);
  75730. blurY.autoClear = false;
  75731. ratio = 0.75 / Math.pow(2, i);
  75732. 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);
  75733. blurX.autoClear = false;
  75734. _this._depthOfFieldBlurY.push(blurY);
  75735. _this._depthOfFieldBlurX.push(blurX);
  75736. }
  75737. // Set all post processes on the effect.
  75738. _this._effects = [_this._circleOfConfusion];
  75739. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75740. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75741. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75742. }
  75743. // Merge blurred images with original image based on circleOfConfusion
  75744. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75745. _this._dofMerge.autoClear = false;
  75746. _this._effects.push(_this._dofMerge);
  75747. return _this;
  75748. }
  75749. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75750. get: function () {
  75751. return this._circleOfConfusion.focalLength;
  75752. },
  75753. /**
  75754. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75755. */
  75756. set: function (value) {
  75757. this._circleOfConfusion.focalLength = value;
  75758. },
  75759. enumerable: true,
  75760. configurable: true
  75761. });
  75762. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75763. get: function () {
  75764. return this._circleOfConfusion.fStop;
  75765. },
  75766. /**
  75767. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75768. */
  75769. set: function (value) {
  75770. this._circleOfConfusion.fStop = value;
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75776. get: function () {
  75777. return this._circleOfConfusion.focusDistance;
  75778. },
  75779. /**
  75780. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75781. */
  75782. set: function (value) {
  75783. this._circleOfConfusion.focusDistance = value;
  75784. },
  75785. enumerable: true,
  75786. configurable: true
  75787. });
  75788. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75789. get: function () {
  75790. return this._circleOfConfusion.lensSize;
  75791. },
  75792. /**
  75793. * 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.
  75794. */
  75795. set: function (value) {
  75796. this._circleOfConfusion.lensSize = value;
  75797. },
  75798. enumerable: true,
  75799. configurable: true
  75800. });
  75801. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75802. /**
  75803. * 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.
  75804. */
  75805. set: function (value) {
  75806. this._circleOfConfusion.depthTexture = value;
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. /**
  75812. * Disposes each of the internal effects for a given camera.
  75813. * @param camera The camera to dispose the effect on.
  75814. */
  75815. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75816. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75817. this._effects[effectIndex].dispose(camera);
  75818. }
  75819. };
  75820. /**
  75821. * Internal
  75822. */
  75823. DepthOfFieldEffect.prototype._updateEffects = function () {
  75824. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75825. this._effects[effectIndex].updateEffect();
  75826. }
  75827. };
  75828. /**
  75829. * Internal
  75830. * @returns if all the contained post processes are ready.
  75831. */
  75832. DepthOfFieldEffect.prototype._isReady = function () {
  75833. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75834. if (!this._effects[effectIndex].isReady()) {
  75835. return false;
  75836. }
  75837. }
  75838. return true;
  75839. };
  75840. return DepthOfFieldEffect;
  75841. }(BABYLON.PostProcessRenderEffect));
  75842. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75843. })(BABYLON || (BABYLON = {}));
  75844. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75845. var BABYLON;
  75846. (function (BABYLON) {
  75847. /**
  75848. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75849. */
  75850. var BloomMergePostProcess = /** @class */ (function (_super) {
  75851. __extends(BloomMergePostProcess, _super);
  75852. /**
  75853. * Creates a new instance of @see BloomMergePostProcess
  75854. * @param name The name of the effect.
  75855. * @param originalFromInput Post process which's input will be used for the merge.
  75856. * @param blurred Blurred highlights post process which's output will be used.
  75857. * @param weight Weight of the bloom to be added to the original input.
  75858. * @param options The required width/height ratio to downsize to before computing the render pass.
  75859. * @param camera The camera to apply the render pass to.
  75860. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75861. * @param engine The engine which the post process will be applied. (default: current engine)
  75862. * @param reusable If the post process can be reused on the same frame. (default: false)
  75863. * @param textureType Type of textures used when performing the post process. (default: 0)
  75864. * @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)
  75865. */
  75866. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75867. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75868. if (blockCompilation === void 0) { blockCompilation = false; }
  75869. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75870. _this.weight = weight;
  75871. _this.onApplyObservable.add(function (effect) {
  75872. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75873. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75874. effect.setFloat("bloomWeight", _this.weight);
  75875. });
  75876. if (!blockCompilation) {
  75877. _this.updateEffect();
  75878. }
  75879. return _this;
  75880. }
  75881. return BloomMergePostProcess;
  75882. }(BABYLON.PostProcess));
  75883. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75884. })(BABYLON || (BABYLON = {}));
  75885. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75886. var BABYLON;
  75887. (function (BABYLON) {
  75888. /**
  75889. * 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.
  75890. */
  75891. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75892. __extends(ExtractHighlightsPostProcess, _super);
  75893. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75894. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75895. if (blockCompilation === void 0) { blockCompilation = false; }
  75896. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75897. /**
  75898. * The luminance threshold, pixels below this value will be set to black.
  75899. */
  75900. _this.threshold = 0.9;
  75901. /**
  75902. * Internal
  75903. */
  75904. _this._exposure = 1;
  75905. /**
  75906. * Post process which has the input texture to be used when performing highlight extraction
  75907. */
  75908. _this._inputPostProcess = null;
  75909. _this.onApplyObservable.add(function (effect) {
  75910. if (_this._inputPostProcess) {
  75911. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75912. }
  75913. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75914. effect.setFloat('exposure', _this._exposure);
  75915. });
  75916. return _this;
  75917. }
  75918. return ExtractHighlightsPostProcess;
  75919. }(BABYLON.PostProcess));
  75920. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75921. })(BABYLON || (BABYLON = {}));
  75922. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75923. var BABYLON;
  75924. (function (BABYLON) {
  75925. /**
  75926. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75927. */
  75928. var BloomEffect = /** @class */ (function (_super) {
  75929. __extends(BloomEffect, _super);
  75930. /**
  75931. * Creates a new instance of @see BloomEffect
  75932. * @param scene The scene the effect belongs to.
  75933. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75934. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75935. * @param bloomWeight The the strength of bloom.
  75936. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75937. * @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)
  75938. */
  75939. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75940. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75941. if (blockCompilation === void 0) { blockCompilation = false; }
  75942. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75943. return _this._effects;
  75944. }, true) || this;
  75945. _this.bloomScale = bloomScale;
  75946. /**
  75947. * Internal
  75948. */
  75949. _this._effects = [];
  75950. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75951. _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);
  75952. _this._blurX.alwaysForcePOT = true;
  75953. _this._blurX.autoClear = false;
  75954. _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);
  75955. _this._blurY.alwaysForcePOT = true;
  75956. _this._blurY.autoClear = false;
  75957. _this.kernel = bloomKernel;
  75958. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75959. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75960. _this._merge.autoClear = false;
  75961. _this._effects.push(_this._merge);
  75962. return _this;
  75963. }
  75964. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75965. /**
  75966. * The luminance threshold to find bright areas of the image to bloom.
  75967. */
  75968. get: function () {
  75969. return this._downscale.threshold;
  75970. },
  75971. set: function (value) {
  75972. this._downscale.threshold = value;
  75973. },
  75974. enumerable: true,
  75975. configurable: true
  75976. });
  75977. Object.defineProperty(BloomEffect.prototype, "weight", {
  75978. /**
  75979. * The strength of the bloom.
  75980. */
  75981. get: function () {
  75982. return this._merge.weight;
  75983. },
  75984. set: function (value) {
  75985. this._merge.weight = value;
  75986. },
  75987. enumerable: true,
  75988. configurable: true
  75989. });
  75990. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75991. /**
  75992. * Specifies the size of the bloom blur kernel, relative to the final output size
  75993. */
  75994. get: function () {
  75995. return this._blurX.kernel / this.bloomScale;
  75996. },
  75997. set: function (value) {
  75998. this._blurX.kernel = value * this.bloomScale;
  75999. this._blurY.kernel = value * this.bloomScale;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. /**
  76005. * Disposes each of the internal effects for a given camera.
  76006. * @param camera The camera to dispose the effect on.
  76007. */
  76008. BloomEffect.prototype.disposeEffects = function (camera) {
  76009. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76010. this._effects[effectIndex].dispose(camera);
  76011. }
  76012. };
  76013. /**
  76014. * Internal
  76015. */
  76016. BloomEffect.prototype._updateEffects = function () {
  76017. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76018. this._effects[effectIndex].updateEffect();
  76019. }
  76020. };
  76021. /**
  76022. * Internal
  76023. * @returns if all the contained post processes are ready.
  76024. */
  76025. BloomEffect.prototype._isReady = function () {
  76026. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76027. if (!this._effects[effectIndex].isReady()) {
  76028. return false;
  76029. }
  76030. }
  76031. return true;
  76032. };
  76033. return BloomEffect;
  76034. }(BABYLON.PostProcessRenderEffect));
  76035. BABYLON.BloomEffect = BloomEffect;
  76036. })(BABYLON || (BABYLON = {}));
  76037. //# sourceMappingURL=babylon.bloomEffect.js.map
  76038. var BABYLON;
  76039. (function (BABYLON) {
  76040. /**
  76041. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76042. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76043. */
  76044. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76045. __extends(DefaultRenderingPipeline, _super);
  76046. /**
  76047. * @constructor
  76048. * @param {string} name - The rendering pipeline name (default: "")
  76049. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76050. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76051. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76052. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76053. */
  76054. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76055. if (name === void 0) { name = ""; }
  76056. if (hdr === void 0) { hdr = true; }
  76057. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76058. if (automaticBuild === void 0) { automaticBuild = true; }
  76059. var _this = _super.call(this, scene.getEngine(), name) || this;
  76060. _this._originalCameras = [];
  76061. /**
  76062. * ID of the sharpen post process,
  76063. */
  76064. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76065. /**
  76066. * ID of the image processing post process;
  76067. */
  76068. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76069. /**
  76070. * ID of the Fast Approximate Anti-Aliasing post process;
  76071. */
  76072. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76073. /**
  76074. * ID of the chromatic aberration post process,
  76075. */
  76076. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76077. /**
  76078. * ID of the grain post process
  76079. */
  76080. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76081. /**
  76082. * Glow post process which adds a glow to emmisive areas of the image
  76083. */
  76084. _this._glowLayer = null;
  76085. /**
  76086. * Animations which can be used to tweak settings over a period of time
  76087. */
  76088. _this.animations = [];
  76089. _this._imageProcessingConfigurationObserver = null;
  76090. // Values
  76091. _this._sharpenEnabled = false;
  76092. _this._bloomEnabled = false;
  76093. _this._depthOfFieldEnabled = false;
  76094. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76095. _this._fxaaEnabled = false;
  76096. _this._imageProcessingEnabled = true;
  76097. _this._bloomScale = 0.5;
  76098. _this._chromaticAberrationEnabled = false;
  76099. _this._grainEnabled = false;
  76100. _this._buildAllowed = true;
  76101. _this._resizeObserver = null;
  76102. _this._hardwareScaleLevel = 1.0;
  76103. _this._bloomKernel = 64;
  76104. /**
  76105. * Specifies the weight of the bloom in the final rendering
  76106. */
  76107. _this._bloomWeight = 0.15;
  76108. /**
  76109. * Specifies the luma threshold for the area that will be blurred by the bloom
  76110. */
  76111. _this._bloomThreshold = 0.9;
  76112. _this._samples = 1;
  76113. _this._hasCleared = false;
  76114. _this._prevPostProcess = null;
  76115. _this._prevPrevPostProcess = null;
  76116. _this._cameras = cameras || scene.cameras;
  76117. _this._originalCameras = _this._cameras.slice();
  76118. _this._buildAllowed = automaticBuild;
  76119. // Initialize
  76120. _this._scene = scene;
  76121. var caps = _this._scene.getEngine().getCaps();
  76122. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76123. // Misc
  76124. if (_this._hdr) {
  76125. if (caps.textureHalfFloatRender) {
  76126. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76127. }
  76128. else if (caps.textureFloatRender) {
  76129. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76130. }
  76131. }
  76132. else {
  76133. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76134. }
  76135. // Attach
  76136. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76137. var engine = _this._scene.getEngine();
  76138. // Create post processes before hand so they can be modified before enabled.
  76139. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76140. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76141. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76142. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76143. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76144. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76145. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76146. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76147. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76148. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76149. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76150. _this.bloomKernel = _this.bloomKernel;
  76151. });
  76152. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76153. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76154. });
  76155. _this._buildPipeline();
  76156. return _this;
  76157. }
  76158. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76159. get: function () {
  76160. return this._sharpenEnabled;
  76161. },
  76162. /**
  76163. * Enable or disable the sharpen process from the pipeline
  76164. */
  76165. set: function (enabled) {
  76166. if (this._sharpenEnabled === enabled) {
  76167. return;
  76168. }
  76169. this._sharpenEnabled = enabled;
  76170. this._buildPipeline();
  76171. },
  76172. enumerable: true,
  76173. configurable: true
  76174. });
  76175. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76176. /**
  76177. * Specifies the size of the bloom blur kernel, relative to the final output size
  76178. */
  76179. get: function () {
  76180. return this._bloomKernel;
  76181. },
  76182. set: function (value) {
  76183. this._bloomKernel = value;
  76184. this.bloom.kernel = value / this._hardwareScaleLevel;
  76185. },
  76186. enumerable: true,
  76187. configurable: true
  76188. });
  76189. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76190. get: function () {
  76191. return this._bloomWeight;
  76192. },
  76193. /**
  76194. * The strength of the bloom.
  76195. */
  76196. set: function (value) {
  76197. if (this._bloomWeight === value) {
  76198. return;
  76199. }
  76200. this.bloom.weight = value;
  76201. this._bloomWeight = value;
  76202. },
  76203. enumerable: true,
  76204. configurable: true
  76205. });
  76206. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76207. get: function () {
  76208. return this._bloomThreshold;
  76209. },
  76210. /**
  76211. * The strength of the bloom.
  76212. */
  76213. set: function (value) {
  76214. if (this._bloomThreshold === value) {
  76215. return;
  76216. }
  76217. this.bloom.threshold = value;
  76218. this._bloomThreshold = value;
  76219. },
  76220. enumerable: true,
  76221. configurable: true
  76222. });
  76223. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76224. get: function () {
  76225. return this._bloomScale;
  76226. },
  76227. /**
  76228. * The scale of the bloom, lower value will provide better performance.
  76229. */
  76230. set: function (value) {
  76231. if (this._bloomScale === value) {
  76232. return;
  76233. }
  76234. this._bloomScale = value;
  76235. // recreate bloom and dispose old as this setting is not dynamic
  76236. this._rebuildBloom();
  76237. this._buildPipeline();
  76238. },
  76239. enumerable: true,
  76240. configurable: true
  76241. });
  76242. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76243. get: function () {
  76244. return this._bloomEnabled;
  76245. },
  76246. /**
  76247. * Enable or disable the bloom from the pipeline
  76248. */
  76249. set: function (enabled) {
  76250. if (this._bloomEnabled === enabled) {
  76251. return;
  76252. }
  76253. this._bloomEnabled = enabled;
  76254. this._buildPipeline();
  76255. },
  76256. enumerable: true,
  76257. configurable: true
  76258. });
  76259. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76260. // recreate bloom and dispose old as this setting is not dynamic
  76261. var oldBloom = this.bloom;
  76262. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76263. this.bloom.threshold = oldBloom.threshold;
  76264. for (var i = 0; i < this._cameras.length; i++) {
  76265. oldBloom.disposeEffects(this._cameras[i]);
  76266. }
  76267. };
  76268. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76269. /**
  76270. * If the depth of field is enabled.
  76271. */
  76272. get: function () {
  76273. return this._depthOfFieldEnabled;
  76274. },
  76275. set: function (enabled) {
  76276. if (this._depthOfFieldEnabled === enabled) {
  76277. return;
  76278. }
  76279. this._depthOfFieldEnabled = enabled;
  76280. this._buildPipeline();
  76281. },
  76282. enumerable: true,
  76283. configurable: true
  76284. });
  76285. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76286. /**
  76287. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76288. */
  76289. get: function () {
  76290. return this._depthOfFieldBlurLevel;
  76291. },
  76292. set: function (value) {
  76293. if (this._depthOfFieldBlurLevel === value) {
  76294. return;
  76295. }
  76296. this._depthOfFieldBlurLevel = value;
  76297. // recreate dof and dispose old as this setting is not dynamic
  76298. var oldDof = this.depthOfField;
  76299. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76300. this.depthOfField.focalLength = oldDof.focalLength;
  76301. this.depthOfField.focusDistance = oldDof.focusDistance;
  76302. this.depthOfField.fStop = oldDof.fStop;
  76303. this.depthOfField.lensSize = oldDof.lensSize;
  76304. for (var i = 0; i < this._cameras.length; i++) {
  76305. oldDof.disposeEffects(this._cameras[i]);
  76306. }
  76307. this._buildPipeline();
  76308. },
  76309. enumerable: true,
  76310. configurable: true
  76311. });
  76312. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76313. get: function () {
  76314. return this._fxaaEnabled;
  76315. },
  76316. /**
  76317. * If the anti aliasing is enabled.
  76318. */
  76319. set: function (enabled) {
  76320. if (this._fxaaEnabled === enabled) {
  76321. return;
  76322. }
  76323. this._fxaaEnabled = enabled;
  76324. this._buildPipeline();
  76325. },
  76326. enumerable: true,
  76327. configurable: true
  76328. });
  76329. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76330. get: function () {
  76331. return this._samples;
  76332. },
  76333. /**
  76334. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76335. */
  76336. set: function (sampleCount) {
  76337. if (this._samples === sampleCount) {
  76338. return;
  76339. }
  76340. this._samples = sampleCount;
  76341. this._buildPipeline();
  76342. },
  76343. enumerable: true,
  76344. configurable: true
  76345. });
  76346. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76347. get: function () {
  76348. return this._imageProcessingEnabled;
  76349. },
  76350. /**
  76351. * If image processing is enabled.
  76352. */
  76353. set: function (enabled) {
  76354. if (this._imageProcessingEnabled === enabled) {
  76355. return;
  76356. }
  76357. this._imageProcessingEnabled = enabled;
  76358. this._buildPipeline();
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76364. get: function () {
  76365. return this._glowLayer == null;
  76366. },
  76367. /**
  76368. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76369. */
  76370. set: function (enabled) {
  76371. if (enabled && !this._glowLayer) {
  76372. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76373. }
  76374. else if (!enabled && this._glowLayer) {
  76375. this._glowLayer.dispose();
  76376. this._glowLayer = null;
  76377. }
  76378. },
  76379. enumerable: true,
  76380. configurable: true
  76381. });
  76382. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76383. get: function () {
  76384. return this._chromaticAberrationEnabled;
  76385. },
  76386. /**
  76387. * Enable or disable the chromaticAberration process from the pipeline
  76388. */
  76389. set: function (enabled) {
  76390. if (this._chromaticAberrationEnabled === enabled) {
  76391. return;
  76392. }
  76393. this._chromaticAberrationEnabled = enabled;
  76394. this._buildPipeline();
  76395. },
  76396. enumerable: true,
  76397. configurable: true
  76398. });
  76399. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76400. get: function () {
  76401. return this._grainEnabled;
  76402. },
  76403. /**
  76404. * Enable or disable the grain process from the pipeline
  76405. */
  76406. set: function (enabled) {
  76407. if (this._grainEnabled === enabled) {
  76408. return;
  76409. }
  76410. this._grainEnabled = enabled;
  76411. this._buildPipeline();
  76412. },
  76413. enumerable: true,
  76414. configurable: true
  76415. });
  76416. /**
  76417. * Force the compilation of the entire pipeline.
  76418. */
  76419. DefaultRenderingPipeline.prototype.prepare = function () {
  76420. var previousState = this._buildAllowed;
  76421. this._buildAllowed = true;
  76422. this._buildPipeline();
  76423. this._buildAllowed = previousState;
  76424. };
  76425. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76426. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76427. if (this._hasCleared) {
  76428. postProcess.autoClear = false;
  76429. }
  76430. else {
  76431. postProcess.autoClear = true;
  76432. this._scene.autoClear = false;
  76433. this._hasCleared = true;
  76434. }
  76435. if (!skipTextureSharing) {
  76436. if (this._prevPrevPostProcess) {
  76437. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76438. }
  76439. else {
  76440. postProcess.useOwnOutput();
  76441. }
  76442. if (this._prevPostProcess) {
  76443. this._prevPrevPostProcess = this._prevPostProcess;
  76444. }
  76445. this._prevPostProcess = postProcess;
  76446. }
  76447. };
  76448. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76449. var _this = this;
  76450. if (!this._buildAllowed) {
  76451. return;
  76452. }
  76453. this._scene.autoClear = true;
  76454. var engine = this._scene.getEngine();
  76455. this._disposePostProcesses();
  76456. if (this._cameras !== null) {
  76457. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76458. // get back cameras to be used to reattach pipeline
  76459. this._cameras = this._originalCameras.slice();
  76460. }
  76461. this._reset();
  76462. this._prevPostProcess = null;
  76463. this._prevPrevPostProcess = null;
  76464. this._hasCleared = false;
  76465. if (this.depthOfFieldEnabled) {
  76466. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76467. this.depthOfField.depthTexture = depthTexture;
  76468. if (!this.depthOfField._isReady()) {
  76469. this.depthOfField._updateEffects();
  76470. }
  76471. this.addEffect(this.depthOfField);
  76472. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76473. }
  76474. if (this.bloomEnabled) {
  76475. if (!this.bloom._isReady()) {
  76476. this.bloom._updateEffects();
  76477. }
  76478. this.addEffect(this.bloom);
  76479. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76480. }
  76481. if (this._imageProcessingEnabled) {
  76482. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76483. if (this._hdr) {
  76484. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76485. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76486. }
  76487. else {
  76488. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76489. }
  76490. }
  76491. if (this.sharpenEnabled) {
  76492. if (!this.sharpen.isReady()) {
  76493. this.sharpen.updateEffect();
  76494. }
  76495. this.addEffect(this._sharpenEffect);
  76496. this._setAutoClearAndTextureSharing(this.sharpen);
  76497. }
  76498. if (this.grainEnabled) {
  76499. if (!this.grain.isReady()) {
  76500. this.grain.updateEffect();
  76501. }
  76502. this.addEffect(this._grainEffect);
  76503. this._setAutoClearAndTextureSharing(this.grain);
  76504. }
  76505. if (this.chromaticAberrationEnabled) {
  76506. if (!this.chromaticAberration.isReady()) {
  76507. this.chromaticAberration.updateEffect();
  76508. }
  76509. this.addEffect(this._chromaticAberrationEffect);
  76510. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76511. }
  76512. if (this.fxaaEnabled) {
  76513. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76514. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76515. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76516. }
  76517. if (this._cameras !== null) {
  76518. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76519. }
  76520. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76521. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76522. }
  76523. };
  76524. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76525. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76526. for (var i = 0; i < this._cameras.length; i++) {
  76527. var camera = this._cameras[i];
  76528. if (this.imageProcessing) {
  76529. this.imageProcessing.dispose(camera);
  76530. }
  76531. if (this.fxaa) {
  76532. this.fxaa.dispose(camera);
  76533. }
  76534. // These are created in the constructor and should not be disposed on every pipeline change
  76535. if (disposeNonRecreated) {
  76536. if (this.sharpen) {
  76537. this.sharpen.dispose(camera);
  76538. }
  76539. if (this.depthOfField) {
  76540. this.depthOfField.disposeEffects(camera);
  76541. }
  76542. if (this.bloom) {
  76543. this.bloom.disposeEffects(camera);
  76544. }
  76545. if (this.chromaticAberration) {
  76546. this.chromaticAberration.dispose(camera);
  76547. }
  76548. if (this.grain) {
  76549. this.grain.dispose(camera);
  76550. }
  76551. if (this._glowLayer) {
  76552. this._glowLayer.dispose();
  76553. }
  76554. }
  76555. }
  76556. this.imageProcessing = null;
  76557. this.fxaa = null;
  76558. if (disposeNonRecreated) {
  76559. this.sharpen = null;
  76560. this._sharpenEffect = null;
  76561. this.depthOfField = null;
  76562. this.bloom = null;
  76563. this.chromaticAberration = null;
  76564. this._chromaticAberrationEffect = null;
  76565. this.grain = null;
  76566. this._grainEffect = null;
  76567. this._glowLayer = null;
  76568. }
  76569. };
  76570. /**
  76571. * Dispose of the pipeline and stop all post processes
  76572. */
  76573. DefaultRenderingPipeline.prototype.dispose = function () {
  76574. this._disposePostProcesses(true);
  76575. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76576. this._scene.autoClear = true;
  76577. if (this._resizeObserver) {
  76578. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76579. this._resizeObserver = null;
  76580. }
  76581. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76582. _super.prototype.dispose.call(this);
  76583. };
  76584. /**
  76585. * Serialize the rendering pipeline (Used when exporting)
  76586. * @returns the serialized object
  76587. */
  76588. DefaultRenderingPipeline.prototype.serialize = function () {
  76589. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76590. serializationObject.customType = "DefaultRenderingPipeline";
  76591. return serializationObject;
  76592. };
  76593. /**
  76594. * Parse the serialized pipeline
  76595. * @param source Source pipeline.
  76596. * @param scene The scene to load the pipeline to.
  76597. * @param rootUrl The URL of the serialized pipeline.
  76598. * @returns An instantiated pipeline from the serialized object.
  76599. */
  76600. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76601. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76602. };
  76603. __decorate([
  76604. BABYLON.serialize()
  76605. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76606. __decorate([
  76607. BABYLON.serialize()
  76608. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76609. __decorate([
  76610. BABYLON.serialize()
  76611. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76612. __decorate([
  76613. BABYLON.serialize()
  76614. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76615. __decorate([
  76616. BABYLON.serialize()
  76617. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76618. __decorate([
  76619. BABYLON.serialize()
  76620. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76621. __decorate([
  76622. BABYLON.serialize()
  76623. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76624. __decorate([
  76625. BABYLON.serialize()
  76626. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76627. __decorate([
  76628. BABYLON.serialize()
  76629. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76630. __decorate([
  76631. BABYLON.serialize()
  76632. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76633. __decorate([
  76634. BABYLON.serialize()
  76635. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76636. __decorate([
  76637. BABYLON.serialize()
  76638. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76639. __decorate([
  76640. BABYLON.serialize()
  76641. ], DefaultRenderingPipeline.prototype, "samples", null);
  76642. __decorate([
  76643. BABYLON.serialize()
  76644. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76645. __decorate([
  76646. BABYLON.serialize()
  76647. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76648. __decorate([
  76649. BABYLON.serialize()
  76650. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76651. __decorate([
  76652. BABYLON.serialize()
  76653. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76654. return DefaultRenderingPipeline;
  76655. }(BABYLON.PostProcessRenderPipeline));
  76656. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76657. })(BABYLON || (BABYLON = {}));
  76658. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76659. var BABYLON;
  76660. (function (BABYLON) {
  76661. /**
  76662. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76663. */
  76664. var GeometryBufferRenderer = /** @class */ (function () {
  76665. /**
  76666. * Creates a new G Buffer for the scene
  76667. * @param scene The scene the buffer belongs to
  76668. * @param ratio How big is the buffer related to the main canvas.
  76669. */
  76670. function GeometryBufferRenderer(scene, ratio) {
  76671. if (ratio === void 0) { ratio = 1; }
  76672. this._enablePosition = false;
  76673. this._scene = scene;
  76674. this._ratio = ratio;
  76675. // Render target
  76676. this._createRenderTargets();
  76677. }
  76678. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76679. /**
  76680. * Set the render list (meshes to be rendered) used in the G buffer.
  76681. */
  76682. set: function (meshes) {
  76683. this._multiRenderTarget.renderList = meshes;
  76684. },
  76685. enumerable: true,
  76686. configurable: true
  76687. });
  76688. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76689. /**
  76690. * Gets wether or not G buffer are supported by the running hardware.
  76691. * This requires draw buffer supports
  76692. */
  76693. get: function () {
  76694. return this._multiRenderTarget.isSupported;
  76695. },
  76696. enumerable: true,
  76697. configurable: true
  76698. });
  76699. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76700. /**
  76701. * Gets wether or not position are enabled for the G buffer.
  76702. */
  76703. get: function () {
  76704. return this._enablePosition;
  76705. },
  76706. /**
  76707. * Sets wether or not position are enabled for the G buffer.
  76708. */
  76709. set: function (enable) {
  76710. this._enablePosition = enable;
  76711. this.dispose();
  76712. this._createRenderTargets();
  76713. },
  76714. enumerable: true,
  76715. configurable: true
  76716. });
  76717. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76718. /**
  76719. * Gets the scene associated with the buffer.
  76720. */
  76721. get: function () {
  76722. return this._scene;
  76723. },
  76724. enumerable: true,
  76725. configurable: true
  76726. });
  76727. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76728. /**
  76729. * Gets the ratio used by the buffer during its creation.
  76730. * How big is the buffer related to the main canvas.
  76731. */
  76732. get: function () {
  76733. return this._ratio;
  76734. },
  76735. enumerable: true,
  76736. configurable: true
  76737. });
  76738. /**
  76739. * Checks wether everything is ready to render a submesh to the G buffer.
  76740. * @param subMesh the submesh to check readiness for
  76741. * @param useInstances is the mesh drawn using instance or not
  76742. * @returns true if ready otherwise false
  76743. */
  76744. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76745. var material = subMesh.getMaterial();
  76746. if (material && material.disableDepthWrite) {
  76747. return false;
  76748. }
  76749. var defines = [];
  76750. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76751. var mesh = subMesh.getMesh();
  76752. // Alpha test
  76753. if (material && material.needAlphaTesting()) {
  76754. defines.push("#define ALPHATEST");
  76755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76756. attribs.push(BABYLON.VertexBuffer.UVKind);
  76757. defines.push("#define UV1");
  76758. }
  76759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76760. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76761. defines.push("#define UV2");
  76762. }
  76763. }
  76764. // Buffers
  76765. if (this._enablePosition) {
  76766. defines.push("#define POSITION");
  76767. }
  76768. // Bones
  76769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76772. if (mesh.numBoneInfluencers > 4) {
  76773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76775. }
  76776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76778. }
  76779. else {
  76780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76781. }
  76782. // Instances
  76783. if (useInstances) {
  76784. defines.push("#define INSTANCES");
  76785. attribs.push("world0");
  76786. attribs.push("world1");
  76787. attribs.push("world2");
  76788. attribs.push("world3");
  76789. }
  76790. // Get correct effect
  76791. var join = defines.join("\n");
  76792. if (this._cachedDefines !== join) {
  76793. this._cachedDefines = join;
  76794. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76795. }
  76796. return this._effect.isReady();
  76797. };
  76798. /**
  76799. * Gets the current underlying G Buffer.
  76800. * @returns the buffer
  76801. */
  76802. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76803. return this._multiRenderTarget;
  76804. };
  76805. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76806. /**
  76807. * Gets the number of samples used to render the buffer (anti aliasing).
  76808. */
  76809. get: function () {
  76810. return this._multiRenderTarget.samples;
  76811. },
  76812. /**
  76813. * Sets the number of samples used to render the buffer (anti aliasing).
  76814. */
  76815. set: function (value) {
  76816. this._multiRenderTarget.samples = value;
  76817. },
  76818. enumerable: true,
  76819. configurable: true
  76820. });
  76821. /**
  76822. * Disposes the renderer and frees up associated resources.
  76823. */
  76824. GeometryBufferRenderer.prototype.dispose = function () {
  76825. this.getGBuffer().dispose();
  76826. };
  76827. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76828. var _this = this;
  76829. var engine = this._scene.getEngine();
  76830. var count = this._enablePosition ? 3 : 2;
  76831. 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 });
  76832. if (!this.isSupported) {
  76833. return;
  76834. }
  76835. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76836. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76837. this._multiRenderTarget.refreshRate = 1;
  76838. this._multiRenderTarget.renderParticles = false;
  76839. this._multiRenderTarget.renderList = null;
  76840. // set default depth value to 1.0 (far away)
  76841. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76842. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76843. });
  76844. // Custom render function
  76845. var renderSubMesh = function (subMesh) {
  76846. var mesh = subMesh.getRenderingMesh();
  76847. var scene = _this._scene;
  76848. var engine = scene.getEngine();
  76849. var material = subMesh.getMaterial();
  76850. if (!material) {
  76851. return;
  76852. }
  76853. // Culling
  76854. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76855. // Managing instances
  76856. var batch = mesh._getInstancesRenderList(subMesh._id);
  76857. if (batch.mustReturn) {
  76858. return;
  76859. }
  76860. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76861. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76862. engine.enableEffect(_this._effect);
  76863. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76864. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76865. _this._effect.setMatrix("view", scene.getViewMatrix());
  76866. // Alpha test
  76867. if (material && material.needAlphaTesting()) {
  76868. var alphaTexture = material.getAlphaTestTexture();
  76869. if (alphaTexture) {
  76870. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76871. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76872. }
  76873. }
  76874. // Bones
  76875. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76876. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76877. }
  76878. // Draw
  76879. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76880. }
  76881. };
  76882. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76883. var index;
  76884. if (depthOnlySubMeshes.length) {
  76885. engine.setColorWrite(false);
  76886. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76887. renderSubMesh(depthOnlySubMeshes.data[index]);
  76888. }
  76889. engine.setColorWrite(true);
  76890. }
  76891. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76892. renderSubMesh(opaqueSubMeshes.data[index]);
  76893. }
  76894. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76895. renderSubMesh(alphaTestSubMeshes.data[index]);
  76896. }
  76897. };
  76898. };
  76899. return GeometryBufferRenderer;
  76900. }());
  76901. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76902. })(BABYLON || (BABYLON = {}));
  76903. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76904. var BABYLON;
  76905. (function (BABYLON) {
  76906. var RefractionPostProcess = /** @class */ (function (_super) {
  76907. __extends(RefractionPostProcess, _super);
  76908. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76909. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76910. _this.color = color;
  76911. _this.depth = depth;
  76912. _this.colorLevel = colorLevel;
  76913. _this._ownRefractionTexture = true;
  76914. _this.onActivateObservable.add(function (cam) {
  76915. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76916. });
  76917. _this.onApplyObservable.add(function (effect) {
  76918. effect.setColor3("baseColor", _this.color);
  76919. effect.setFloat("depth", _this.depth);
  76920. effect.setFloat("colorLevel", _this.colorLevel);
  76921. effect.setTexture("refractionSampler", _this._refTexture);
  76922. });
  76923. return _this;
  76924. }
  76925. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76926. /**
  76927. * Gets or sets the refraction texture
  76928. * Please note that you are responsible for disposing the texture if you set it manually
  76929. */
  76930. get: function () {
  76931. return this._refTexture;
  76932. },
  76933. set: function (value) {
  76934. if (this._refTexture && this._ownRefractionTexture) {
  76935. this._refTexture.dispose();
  76936. }
  76937. this._refTexture = value;
  76938. this._ownRefractionTexture = false;
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. // Methods
  76944. RefractionPostProcess.prototype.dispose = function (camera) {
  76945. if (this._refTexture && this._ownRefractionTexture) {
  76946. this._refTexture.dispose();
  76947. this._refTexture = null;
  76948. }
  76949. _super.prototype.dispose.call(this, camera);
  76950. };
  76951. return RefractionPostProcess;
  76952. }(BABYLON.PostProcess));
  76953. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76954. })(BABYLON || (BABYLON = {}));
  76955. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76956. var BABYLON;
  76957. (function (BABYLON) {
  76958. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76959. __extends(BlackAndWhitePostProcess, _super);
  76960. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76961. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76962. _this.degree = 1;
  76963. _this.onApplyObservable.add(function (effect) {
  76964. effect.setFloat("degree", _this.degree);
  76965. });
  76966. return _this;
  76967. }
  76968. return BlackAndWhitePostProcess;
  76969. }(BABYLON.PostProcess));
  76970. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76971. })(BABYLON || (BABYLON = {}));
  76972. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76973. var BABYLON;
  76974. (function (BABYLON) {
  76975. /**
  76976. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76977. * input texture to perform effects such as edge detection or sharpening
  76978. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76979. */
  76980. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76981. __extends(ConvolutionPostProcess, _super);
  76982. /**
  76983. * Creates a new instance ConvolutionPostProcess
  76984. * @param name The name of the effect.
  76985. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76986. * @param options The required width/height ratio to downsize to before computing the render pass.
  76987. * @param camera The camera to apply the render pass to.
  76988. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76989. * @param engine The engine which the post process will be applied. (default: current engine)
  76990. * @param reusable If the post process can be reused on the same frame. (default: false)
  76991. * @param textureType Type of textures used when performing the post process. (default: 0)
  76992. */
  76993. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76994. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76995. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76996. _this.kernel = kernel;
  76997. _this.onApply = function (effect) {
  76998. effect.setFloat2("screenSize", _this.width, _this.height);
  76999. effect.setArray("kernel", _this.kernel);
  77000. };
  77001. return _this;
  77002. }
  77003. // Statics
  77004. /**
  77005. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77006. */
  77007. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77008. /**
  77009. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77010. */
  77011. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77012. /**
  77013. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77014. */
  77015. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77016. /**
  77017. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77018. */
  77019. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77020. /**
  77021. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77022. */
  77023. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77024. /**
  77025. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77026. */
  77027. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77028. return ConvolutionPostProcess;
  77029. }(BABYLON.PostProcess));
  77030. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77031. })(BABYLON || (BABYLON = {}));
  77032. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77033. var BABYLON;
  77034. (function (BABYLON) {
  77035. var FilterPostProcess = /** @class */ (function (_super) {
  77036. __extends(FilterPostProcess, _super);
  77037. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77038. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77039. _this.kernelMatrix = kernelMatrix;
  77040. _this.onApply = function (effect) {
  77041. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77042. };
  77043. return _this;
  77044. }
  77045. return FilterPostProcess;
  77046. }(BABYLON.PostProcess));
  77047. BABYLON.FilterPostProcess = FilterPostProcess;
  77048. })(BABYLON || (BABYLON = {}));
  77049. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77050. var BABYLON;
  77051. (function (BABYLON) {
  77052. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77053. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77054. __extends(VolumetricLightScatteringPostProcess, _super);
  77055. /**
  77056. * @constructor
  77057. * @param {string} name - The post-process name
  77058. * @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)
  77059. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77060. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77061. * @param {number} samples - The post-process quality, default 100
  77062. * @param {number} samplingMode - The post-process filtering mode
  77063. * @param {BABYLON.Engine} engine - The babylon engine
  77064. * @param {boolean} reusable - If the post-process is reusable
  77065. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77066. */
  77067. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77068. if (samples === void 0) { samples = 100; }
  77069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77070. 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;
  77071. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77072. /**
  77073. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77074. */
  77075. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77076. /**
  77077. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77078. */
  77079. _this.useCustomMeshPosition = false;
  77080. /**
  77081. * If the post-process should inverse the light scattering direction
  77082. */
  77083. _this.invert = true;
  77084. /**
  77085. * Array containing the excluded meshes not rendered in the internal pass
  77086. */
  77087. _this.excludedMeshes = new Array();
  77088. /**
  77089. * Controls the overall intensity of the post-process
  77090. */
  77091. _this.exposure = 0.3;
  77092. /**
  77093. * Dissipates each sample's contribution in range [0, 1]
  77094. */
  77095. _this.decay = 0.96815;
  77096. /**
  77097. * Controls the overall intensity of each sample
  77098. */
  77099. _this.weight = 0.58767;
  77100. /**
  77101. * Controls the density of each sample
  77102. */
  77103. _this.density = 0.926;
  77104. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77105. engine = scene.getEngine();
  77106. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77107. // Configure mesh
  77108. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77109. // Configure
  77110. _this._createPass(scene, ratio.passRatio || ratio);
  77111. _this.onActivate = function (camera) {
  77112. if (!_this.isSupported) {
  77113. _this.dispose(camera);
  77114. }
  77115. _this.onActivate = null;
  77116. };
  77117. _this.onApplyObservable.add(function (effect) {
  77118. _this._updateMeshScreenCoordinates(scene);
  77119. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77120. effect.setFloat("exposure", _this.exposure);
  77121. effect.setFloat("decay", _this.decay);
  77122. effect.setFloat("weight", _this.weight);
  77123. effect.setFloat("density", _this.density);
  77124. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77125. });
  77126. return _this;
  77127. }
  77128. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77129. get: function () {
  77130. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77131. return false;
  77132. },
  77133. set: function (useDiffuseColor) {
  77134. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77135. },
  77136. enumerable: true,
  77137. configurable: true
  77138. });
  77139. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77140. return "VolumetricLightScatteringPostProcess";
  77141. };
  77142. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77143. var mesh = subMesh.getMesh();
  77144. // Render this.mesh as default
  77145. if (mesh === this.mesh && mesh.material) {
  77146. return mesh.material.isReady(mesh);
  77147. }
  77148. var defines = [];
  77149. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77150. var material = subMesh.getMaterial();
  77151. // Alpha test
  77152. if (material) {
  77153. if (material.needAlphaTesting()) {
  77154. defines.push("#define ALPHATEST");
  77155. }
  77156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77157. attribs.push(BABYLON.VertexBuffer.UVKind);
  77158. defines.push("#define UV1");
  77159. }
  77160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77161. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77162. defines.push("#define UV2");
  77163. }
  77164. }
  77165. // Bones
  77166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77169. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77170. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77171. }
  77172. else {
  77173. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77174. }
  77175. // Instances
  77176. if (useInstances) {
  77177. defines.push("#define INSTANCES");
  77178. attribs.push("world0");
  77179. attribs.push("world1");
  77180. attribs.push("world2");
  77181. attribs.push("world3");
  77182. }
  77183. // Get correct effect
  77184. var join = defines.join("\n");
  77185. if (this._cachedDefines !== join) {
  77186. this._cachedDefines = join;
  77187. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77188. }
  77189. return this._volumetricLightScatteringPass.isReady();
  77190. };
  77191. /**
  77192. * Sets the new light position for light scattering effect
  77193. * @param {BABYLON.Vector3} The new custom light position
  77194. */
  77195. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77196. this.customMeshPosition = position;
  77197. };
  77198. /**
  77199. * Returns the light position for light scattering effect
  77200. * @return {BABYLON.Vector3} The custom light position
  77201. */
  77202. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77203. return this.customMeshPosition;
  77204. };
  77205. /**
  77206. * Disposes the internal assets and detaches the post-process from the camera
  77207. */
  77208. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77209. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77210. if (rttIndex !== -1) {
  77211. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77212. }
  77213. this._volumetricLightScatteringRTT.dispose();
  77214. _super.prototype.dispose.call(this, camera);
  77215. };
  77216. /**
  77217. * Returns the render target texture used by the post-process
  77218. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77219. */
  77220. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77221. return this._volumetricLightScatteringRTT;
  77222. };
  77223. // Private methods
  77224. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77225. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77226. return true;
  77227. }
  77228. return false;
  77229. };
  77230. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77231. var _this = this;
  77232. var engine = scene.getEngine();
  77233. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77234. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77235. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77236. this._volumetricLightScatteringRTT.renderList = null;
  77237. this._volumetricLightScatteringRTT.renderParticles = false;
  77238. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77239. var camera = this.getCamera();
  77240. if (camera) {
  77241. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77242. }
  77243. else {
  77244. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77245. }
  77246. // Custom render function for submeshes
  77247. var renderSubMesh = function (subMesh) {
  77248. var mesh = subMesh.getRenderingMesh();
  77249. if (_this._meshExcluded(mesh)) {
  77250. return;
  77251. }
  77252. var material = subMesh.getMaterial();
  77253. if (!material) {
  77254. return;
  77255. }
  77256. var scene = mesh.getScene();
  77257. var engine = scene.getEngine();
  77258. // Culling
  77259. engine.setState(material.backFaceCulling);
  77260. // Managing instances
  77261. var batch = mesh._getInstancesRenderList(subMesh._id);
  77262. if (batch.mustReturn) {
  77263. return;
  77264. }
  77265. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77266. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77267. var effect = _this._volumetricLightScatteringPass;
  77268. if (mesh === _this.mesh) {
  77269. if (subMesh.effect) {
  77270. effect = subMesh.effect;
  77271. }
  77272. else {
  77273. effect = material.getEffect();
  77274. }
  77275. }
  77276. engine.enableEffect(effect);
  77277. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77278. if (mesh === _this.mesh) {
  77279. material.bind(mesh.getWorldMatrix(), mesh);
  77280. }
  77281. else {
  77282. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77283. // Alpha test
  77284. if (material && material.needAlphaTesting()) {
  77285. var alphaTexture = material.getAlphaTestTexture();
  77286. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77287. if (alphaTexture) {
  77288. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77289. }
  77290. }
  77291. // Bones
  77292. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77293. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77294. }
  77295. }
  77296. // Draw
  77297. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77298. }
  77299. };
  77300. // Render target texture callbacks
  77301. var savedSceneClearColor;
  77302. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77303. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77304. savedSceneClearColor = scene.clearColor;
  77305. scene.clearColor = sceneClearColor;
  77306. });
  77307. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77308. scene.clearColor = savedSceneClearColor;
  77309. });
  77310. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77311. var engine = scene.getEngine();
  77312. var index;
  77313. if (depthOnlySubMeshes.length) {
  77314. engine.setColorWrite(false);
  77315. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77316. renderSubMesh(depthOnlySubMeshes.data[index]);
  77317. }
  77318. engine.setColorWrite(true);
  77319. }
  77320. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77321. renderSubMesh(opaqueSubMeshes.data[index]);
  77322. }
  77323. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77324. renderSubMesh(alphaTestSubMeshes.data[index]);
  77325. }
  77326. if (transparentSubMeshes.length) {
  77327. // Sort sub meshes
  77328. for (index = 0; index < transparentSubMeshes.length; index++) {
  77329. var submesh = transparentSubMeshes.data[index];
  77330. var boundingInfo = submesh.getBoundingInfo();
  77331. if (boundingInfo && scene.activeCamera) {
  77332. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77333. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77334. }
  77335. }
  77336. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77337. sortedArray.sort(function (a, b) {
  77338. // Alpha index first
  77339. if (a._alphaIndex > b._alphaIndex) {
  77340. return 1;
  77341. }
  77342. if (a._alphaIndex < b._alphaIndex) {
  77343. return -1;
  77344. }
  77345. // Then distance to camera
  77346. if (a._distanceToCamera < b._distanceToCamera) {
  77347. return 1;
  77348. }
  77349. if (a._distanceToCamera > b._distanceToCamera) {
  77350. return -1;
  77351. }
  77352. return 0;
  77353. });
  77354. // Render sub meshes
  77355. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77356. for (index = 0; index < sortedArray.length; index++) {
  77357. renderSubMesh(sortedArray[index]);
  77358. }
  77359. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77360. }
  77361. };
  77362. };
  77363. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77364. var transform = scene.getTransformMatrix();
  77365. var meshPosition;
  77366. if (this.useCustomMeshPosition) {
  77367. meshPosition = this.customMeshPosition;
  77368. }
  77369. else if (this.attachedNode) {
  77370. meshPosition = this.attachedNode.position;
  77371. }
  77372. else {
  77373. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77374. }
  77375. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77376. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77377. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77378. if (this.invert)
  77379. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77380. };
  77381. // Static methods
  77382. /**
  77383. * Creates a default mesh for the Volumeric Light Scattering post-process
  77384. * @param {string} The mesh name
  77385. * @param {BABYLON.Scene} The scene where to create the mesh
  77386. * @return {BABYLON.Mesh} the default mesh
  77387. */
  77388. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77389. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77390. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77391. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77392. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77393. mesh.material = material;
  77394. return mesh;
  77395. };
  77396. __decorate([
  77397. BABYLON.serializeAsVector3()
  77398. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77399. __decorate([
  77400. BABYLON.serialize()
  77401. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77402. __decorate([
  77403. BABYLON.serialize()
  77404. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77405. __decorate([
  77406. BABYLON.serializeAsMeshReference()
  77407. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77408. __decorate([
  77409. BABYLON.serialize()
  77410. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77411. __decorate([
  77412. BABYLON.serialize()
  77413. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77414. __decorate([
  77415. BABYLON.serialize()
  77416. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77417. __decorate([
  77418. BABYLON.serialize()
  77419. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77420. __decorate([
  77421. BABYLON.serialize()
  77422. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77423. return VolumetricLightScatteringPostProcess;
  77424. }(BABYLON.PostProcess));
  77425. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77426. })(BABYLON || (BABYLON = {}));
  77427. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77428. //
  77429. // This post-process allows the modification of rendered colors by using
  77430. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77431. //
  77432. // The object needs to be provided an url to a texture containing the color
  77433. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77434. // Use an image editing software to tweak the LUT to match your needs.
  77435. //
  77436. // For an example of a color LUT, see here:
  77437. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77438. // For explanations on color grading, see here:
  77439. // http://udn.epicgames.com/Three/ColorGrading.html
  77440. //
  77441. var BABYLON;
  77442. (function (BABYLON) {
  77443. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77444. __extends(ColorCorrectionPostProcess, _super);
  77445. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77446. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77447. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77448. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77449. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77450. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77451. _this.onApply = function (effect) {
  77452. effect.setTexture("colorTable", _this._colorTableTexture);
  77453. };
  77454. return _this;
  77455. }
  77456. return ColorCorrectionPostProcess;
  77457. }(BABYLON.PostProcess));
  77458. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77459. })(BABYLON || (BABYLON = {}));
  77460. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77461. var BABYLON;
  77462. (function (BABYLON) {
  77463. /** Defines operator used for tonemapping */
  77464. var TonemappingOperator;
  77465. (function (TonemappingOperator) {
  77466. /** Hable */
  77467. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77468. /** Reinhard */
  77469. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77470. /** HejiDawson */
  77471. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77472. /** Photographic */
  77473. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77474. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77475. ;
  77476. /**
  77477. * Defines a post process to apply tone mapping
  77478. */
  77479. var TonemapPostProcess = /** @class */ (function (_super) {
  77480. __extends(TonemapPostProcess, _super);
  77481. /**
  77482. * Creates a new TonemapPostProcess
  77483. * @param name defines the name of the postprocess
  77484. * @param _operator defines the operator to use
  77485. * @param exposureAdjustment defines the required exposure adjustement
  77486. * @param camera defines the camera to use (can be null)
  77487. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77488. * @param engine defines the hosting engine (can be ignore if camera is set)
  77489. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77490. */
  77491. function TonemapPostProcess(name, _operator,
  77492. /** Defines the required exposure adjustement */
  77493. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77495. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77496. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77497. _this._operator = _operator;
  77498. _this.exposureAdjustment = exposureAdjustment;
  77499. var defines = "#define ";
  77500. if (_this._operator === TonemappingOperator.Hable)
  77501. defines += "HABLE_TONEMAPPING";
  77502. else if (_this._operator === TonemappingOperator.Reinhard)
  77503. defines += "REINHARD_TONEMAPPING";
  77504. else if (_this._operator === TonemappingOperator.HejiDawson)
  77505. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77506. else if (_this._operator === TonemappingOperator.Photographic)
  77507. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77508. //sadly a second call to create the effect.
  77509. _this.updateEffect(defines);
  77510. _this.onApply = function (effect) {
  77511. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77512. };
  77513. return _this;
  77514. }
  77515. return TonemapPostProcess;
  77516. }(BABYLON.PostProcess));
  77517. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77518. })(BABYLON || (BABYLON = {}));
  77519. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77520. var BABYLON;
  77521. (function (BABYLON) {
  77522. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77523. __extends(DisplayPassPostProcess, _super);
  77524. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77525. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77526. }
  77527. return DisplayPassPostProcess;
  77528. }(BABYLON.PostProcess));
  77529. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77530. })(BABYLON || (BABYLON = {}));
  77531. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77532. var BABYLON;
  77533. (function (BABYLON) {
  77534. var HighlightsPostProcess = /** @class */ (function (_super) {
  77535. __extends(HighlightsPostProcess, _super);
  77536. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77537. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77538. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77539. }
  77540. return HighlightsPostProcess;
  77541. }(BABYLON.PostProcess));
  77542. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77543. })(BABYLON || (BABYLON = {}));
  77544. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77545. var BABYLON;
  77546. (function (BABYLON) {
  77547. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77548. __extends(ImageProcessingPostProcess, _super);
  77549. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77550. if (camera === void 0) { camera = null; }
  77551. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77552. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77553. _this._fromLinearSpace = true;
  77554. /**
  77555. * Defines cache preventing GC.
  77556. */
  77557. _this._defines = {
  77558. IMAGEPROCESSING: false,
  77559. VIGNETTE: false,
  77560. VIGNETTEBLENDMODEMULTIPLY: false,
  77561. VIGNETTEBLENDMODEOPAQUE: false,
  77562. TONEMAPPING: false,
  77563. CONTRAST: false,
  77564. COLORCURVES: false,
  77565. COLORGRADING: false,
  77566. COLORGRADING3D: false,
  77567. FROMLINEARSPACE: false,
  77568. SAMPLER3DGREENDEPTH: false,
  77569. SAMPLER3DBGRMAP: false,
  77570. IMAGEPROCESSINGPOSTPROCESS: false,
  77571. EXPOSURE: false,
  77572. };
  77573. // Setup the configuration as forced by the constructor. This would then not force the
  77574. // scene materials output in linear space and let untouched the default forward pass.
  77575. if (imageProcessingConfiguration) {
  77576. imageProcessingConfiguration.applyByPostProcess = true;
  77577. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77578. // This will cause the shader to be compiled
  77579. _this.fromLinearSpace = false;
  77580. }
  77581. // Setup the default processing configuration to the scene.
  77582. else {
  77583. _this._attachImageProcessingConfiguration(null, true);
  77584. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77585. }
  77586. _this.onApply = function (effect) {
  77587. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77588. };
  77589. return _this;
  77590. }
  77591. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77592. /**
  77593. * Gets the image processing configuration used either in this material.
  77594. */
  77595. get: function () {
  77596. return this._imageProcessingConfiguration;
  77597. },
  77598. /**
  77599. * Sets the Default image processing configuration used either in the this material.
  77600. *
  77601. * If sets to null, the scene one is in use.
  77602. */
  77603. set: function (value) {
  77604. this._attachImageProcessingConfiguration(value);
  77605. },
  77606. enumerable: true,
  77607. configurable: true
  77608. });
  77609. /**
  77610. * Attaches a new image processing configuration to the PBR Material.
  77611. * @param configuration
  77612. */
  77613. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77614. var _this = this;
  77615. if (doNotBuild === void 0) { doNotBuild = false; }
  77616. if (configuration === this._imageProcessingConfiguration) {
  77617. return;
  77618. }
  77619. // Detaches observer.
  77620. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77621. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77622. }
  77623. // Pick the scene configuration if needed.
  77624. if (!configuration) {
  77625. var scene = null;
  77626. var engine = this.getEngine();
  77627. var camera = this.getCamera();
  77628. if (camera) {
  77629. scene = camera.getScene();
  77630. }
  77631. else if (engine && engine.scenes) {
  77632. var scenes = engine.scenes;
  77633. scene = scenes[scenes.length - 1];
  77634. }
  77635. else {
  77636. scene = BABYLON.Engine.LastCreatedScene;
  77637. }
  77638. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77639. }
  77640. else {
  77641. this._imageProcessingConfiguration = configuration;
  77642. }
  77643. // Attaches observer.
  77644. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77645. _this._updateParameters();
  77646. });
  77647. // Ensure the effect will be rebuilt.
  77648. if (!doNotBuild) {
  77649. this._updateParameters();
  77650. }
  77651. };
  77652. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77653. /**
  77654. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77655. */
  77656. get: function () {
  77657. return this.imageProcessingConfiguration.colorCurves;
  77658. },
  77659. /**
  77660. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77661. */
  77662. set: function (value) {
  77663. this.imageProcessingConfiguration.colorCurves = value;
  77664. },
  77665. enumerable: true,
  77666. configurable: true
  77667. });
  77668. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77669. /**
  77670. * Gets wether the color curves effect is enabled.
  77671. */
  77672. get: function () {
  77673. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77674. },
  77675. /**
  77676. * Sets wether the color curves effect is enabled.
  77677. */
  77678. set: function (value) {
  77679. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77680. },
  77681. enumerable: true,
  77682. configurable: true
  77683. });
  77684. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77685. /**
  77686. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77687. */
  77688. get: function () {
  77689. return this.imageProcessingConfiguration.colorGradingTexture;
  77690. },
  77691. /**
  77692. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77693. */
  77694. set: function (value) {
  77695. this.imageProcessingConfiguration.colorGradingTexture = value;
  77696. },
  77697. enumerable: true,
  77698. configurable: true
  77699. });
  77700. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77701. /**
  77702. * Gets wether the color grading effect is enabled.
  77703. */
  77704. get: function () {
  77705. return this.imageProcessingConfiguration.colorGradingEnabled;
  77706. },
  77707. /**
  77708. * Gets wether the color grading effect is enabled.
  77709. */
  77710. set: function (value) {
  77711. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77712. },
  77713. enumerable: true,
  77714. configurable: true
  77715. });
  77716. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77717. /**
  77718. * Gets exposure used in the effect.
  77719. */
  77720. get: function () {
  77721. return this.imageProcessingConfiguration.exposure;
  77722. },
  77723. /**
  77724. * Sets exposure used in the effect.
  77725. */
  77726. set: function (value) {
  77727. this.imageProcessingConfiguration.exposure = value;
  77728. },
  77729. enumerable: true,
  77730. configurable: true
  77731. });
  77732. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77733. /**
  77734. * Gets wether tonemapping is enabled or not.
  77735. */
  77736. get: function () {
  77737. return this._imageProcessingConfiguration.toneMappingEnabled;
  77738. },
  77739. /**
  77740. * Sets wether tonemapping is enabled or not
  77741. */
  77742. set: function (value) {
  77743. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77744. },
  77745. enumerable: true,
  77746. configurable: true
  77747. });
  77748. ;
  77749. ;
  77750. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77751. /**
  77752. * Gets contrast used in the effect.
  77753. */
  77754. get: function () {
  77755. return this.imageProcessingConfiguration.contrast;
  77756. },
  77757. /**
  77758. * Sets contrast used in the effect.
  77759. */
  77760. set: function (value) {
  77761. this.imageProcessingConfiguration.contrast = value;
  77762. },
  77763. enumerable: true,
  77764. configurable: true
  77765. });
  77766. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77767. /**
  77768. * Gets Vignette stretch size.
  77769. */
  77770. get: function () {
  77771. return this.imageProcessingConfiguration.vignetteStretch;
  77772. },
  77773. /**
  77774. * Sets Vignette stretch size.
  77775. */
  77776. set: function (value) {
  77777. this.imageProcessingConfiguration.vignetteStretch = value;
  77778. },
  77779. enumerable: true,
  77780. configurable: true
  77781. });
  77782. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77783. /**
  77784. * Gets Vignette centre X Offset.
  77785. */
  77786. get: function () {
  77787. return this.imageProcessingConfiguration.vignetteCentreX;
  77788. },
  77789. /**
  77790. * Sets Vignette centre X Offset.
  77791. */
  77792. set: function (value) {
  77793. this.imageProcessingConfiguration.vignetteCentreX = value;
  77794. },
  77795. enumerable: true,
  77796. configurable: true
  77797. });
  77798. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77799. /**
  77800. * Gets Vignette centre Y Offset.
  77801. */
  77802. get: function () {
  77803. return this.imageProcessingConfiguration.vignetteCentreY;
  77804. },
  77805. /**
  77806. * Sets Vignette centre Y Offset.
  77807. */
  77808. set: function (value) {
  77809. this.imageProcessingConfiguration.vignetteCentreY = value;
  77810. },
  77811. enumerable: true,
  77812. configurable: true
  77813. });
  77814. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77815. /**
  77816. * Gets Vignette weight or intensity of the vignette effect.
  77817. */
  77818. get: function () {
  77819. return this.imageProcessingConfiguration.vignetteWeight;
  77820. },
  77821. /**
  77822. * Sets Vignette weight or intensity of the vignette effect.
  77823. */
  77824. set: function (value) {
  77825. this.imageProcessingConfiguration.vignetteWeight = value;
  77826. },
  77827. enumerable: true,
  77828. configurable: true
  77829. });
  77830. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77831. /**
  77832. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77833. * if vignetteEnabled is set to true.
  77834. */
  77835. get: function () {
  77836. return this.imageProcessingConfiguration.vignetteColor;
  77837. },
  77838. /**
  77839. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77840. * if vignetteEnabled is set to true.
  77841. */
  77842. set: function (value) {
  77843. this.imageProcessingConfiguration.vignetteColor = value;
  77844. },
  77845. enumerable: true,
  77846. configurable: true
  77847. });
  77848. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77849. /**
  77850. * Gets Camera field of view used by the Vignette effect.
  77851. */
  77852. get: function () {
  77853. return this.imageProcessingConfiguration.vignetteCameraFov;
  77854. },
  77855. /**
  77856. * Sets Camera field of view used by the Vignette effect.
  77857. */
  77858. set: function (value) {
  77859. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77860. },
  77861. enumerable: true,
  77862. configurable: true
  77863. });
  77864. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77865. /**
  77866. * Gets the vignette blend mode allowing different kind of effect.
  77867. */
  77868. get: function () {
  77869. return this.imageProcessingConfiguration.vignetteBlendMode;
  77870. },
  77871. /**
  77872. * Sets the vignette blend mode allowing different kind of effect.
  77873. */
  77874. set: function (value) {
  77875. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77876. },
  77877. enumerable: true,
  77878. configurable: true
  77879. });
  77880. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77881. /**
  77882. * Gets wether the vignette effect is enabled.
  77883. */
  77884. get: function () {
  77885. return this.imageProcessingConfiguration.vignetteEnabled;
  77886. },
  77887. /**
  77888. * Sets wether the vignette effect is enabled.
  77889. */
  77890. set: function (value) {
  77891. this.imageProcessingConfiguration.vignetteEnabled = value;
  77892. },
  77893. enumerable: true,
  77894. configurable: true
  77895. });
  77896. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77897. /**
  77898. * Gets wether the input of the processing is in Gamma or Linear Space.
  77899. */
  77900. get: function () {
  77901. return this._fromLinearSpace;
  77902. },
  77903. /**
  77904. * Sets wether the input of the processing is in Gamma or Linear Space.
  77905. */
  77906. set: function (value) {
  77907. if (this._fromLinearSpace === value) {
  77908. return;
  77909. }
  77910. this._fromLinearSpace = value;
  77911. this._updateParameters();
  77912. },
  77913. enumerable: true,
  77914. configurable: true
  77915. });
  77916. ImageProcessingPostProcess.prototype.getClassName = function () {
  77917. return "ImageProcessingPostProcess";
  77918. };
  77919. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77920. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77921. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77922. var defines = "";
  77923. for (var define in this._defines) {
  77924. if (this._defines[define]) {
  77925. defines += "#define " + define + ";\r\n";
  77926. }
  77927. }
  77928. var samplers = ["textureSampler"];
  77929. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77930. var uniforms = ["scale"];
  77931. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77932. this.updateEffect(defines, uniforms, samplers);
  77933. };
  77934. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77935. _super.prototype.dispose.call(this, camera);
  77936. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77937. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77938. }
  77939. this.imageProcessingConfiguration.applyByPostProcess = false;
  77940. };
  77941. __decorate([
  77942. BABYLON.serialize()
  77943. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77944. return ImageProcessingPostProcess;
  77945. }(BABYLON.PostProcess));
  77946. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77947. })(BABYLON || (BABYLON = {}));
  77948. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77949. var BABYLON;
  77950. (function (BABYLON) {
  77951. /**
  77952. * Class used to store bone information
  77953. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77954. */
  77955. var Bone = /** @class */ (function (_super) {
  77956. __extends(Bone, _super);
  77957. /**
  77958. * Create a new bone
  77959. * @param name defines the bone name
  77960. * @param skeleton defines the parent skeleton
  77961. * @param parentBone defines the parent (can be null if the bone is the root)
  77962. * @param localMatrix defines the local matrix
  77963. * @param restPose defines the rest pose matrix
  77964. * @param baseMatrix defines the base matrix
  77965. * @param index defines index of the bone in the hiearchy
  77966. */
  77967. function Bone(
  77968. /**
  77969. * defines the bone name
  77970. */
  77971. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77972. if (parentBone === void 0) { parentBone = null; }
  77973. if (localMatrix === void 0) { localMatrix = null; }
  77974. if (restPose === void 0) { restPose = null; }
  77975. if (baseMatrix === void 0) { baseMatrix = null; }
  77976. if (index === void 0) { index = null; }
  77977. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77978. _this.name = name;
  77979. /**
  77980. * Gets the list of child bones
  77981. */
  77982. _this.children = new Array();
  77983. /** Gets the animations associated with this bone */
  77984. _this.animations = new Array();
  77985. /**
  77986. * @hidden Internal only
  77987. * Set this value to map this bone to a different index in the transform matrices
  77988. * Set this value to -1 to exclude the bone from the transform matrices
  77989. */
  77990. _this._index = null;
  77991. _this._absoluteTransform = new BABYLON.Matrix();
  77992. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77993. _this._scalingDeterminant = 1;
  77994. _this._worldTransform = new BABYLON.Matrix();
  77995. _this._needToDecompose = true;
  77996. _this._needToCompose = false;
  77997. _this._skeleton = skeleton;
  77998. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77999. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78000. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78001. _this._index = index;
  78002. skeleton.bones.push(_this);
  78003. _this.setParent(parentBone, false);
  78004. if (baseMatrix || localMatrix) {
  78005. _this._updateDifferenceMatrix();
  78006. }
  78007. return _this;
  78008. }
  78009. Object.defineProperty(Bone.prototype, "_matrix", {
  78010. /** @hidden */
  78011. get: function () {
  78012. this._compose();
  78013. return this._localMatrix;
  78014. },
  78015. /** @hidden */
  78016. set: function (value) {
  78017. this._localMatrix.copyFrom(value);
  78018. this._needToDecompose = true;
  78019. },
  78020. enumerable: true,
  78021. configurable: true
  78022. });
  78023. // Members
  78024. /**
  78025. * Gets the parent skeleton
  78026. * @returns a skeleton
  78027. */
  78028. Bone.prototype.getSkeleton = function () {
  78029. return this._skeleton;
  78030. };
  78031. /**
  78032. * Gets parent bone
  78033. * @returns a bone or null if the bone is the root of the bone hierarchy
  78034. */
  78035. Bone.prototype.getParent = function () {
  78036. return this._parent;
  78037. };
  78038. /**
  78039. * Sets the parent bone
  78040. * @param parent defines the parent (can be null if the bone is the root)
  78041. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78042. */
  78043. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78044. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78045. if (this._parent === parent) {
  78046. return;
  78047. }
  78048. if (this._parent) {
  78049. var index = this._parent.children.indexOf(this);
  78050. if (index !== -1) {
  78051. this._parent.children.splice(index, 1);
  78052. }
  78053. }
  78054. this._parent = parent;
  78055. if (this._parent) {
  78056. this._parent.children.push(this);
  78057. }
  78058. if (updateDifferenceMatrix) {
  78059. this._updateDifferenceMatrix();
  78060. }
  78061. this.markAsDirty();
  78062. };
  78063. /**
  78064. * Gets the local matrix
  78065. * @returns a matrix
  78066. */
  78067. Bone.prototype.getLocalMatrix = function () {
  78068. this._compose();
  78069. return this._localMatrix;
  78070. };
  78071. /**
  78072. * Gets the base matrix (initial matrix which remains unchanged)
  78073. * @returns a matrix
  78074. */
  78075. Bone.prototype.getBaseMatrix = function () {
  78076. return this._baseMatrix;
  78077. };
  78078. /**
  78079. * Gets the rest pose matrix
  78080. * @returns a matrix
  78081. */
  78082. Bone.prototype.getRestPose = function () {
  78083. return this._restPose;
  78084. };
  78085. /**
  78086. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78087. */
  78088. Bone.prototype.getWorldMatrix = function () {
  78089. return this._worldTransform;
  78090. };
  78091. /**
  78092. * Sets the local matrix to rest pose matrix
  78093. */
  78094. Bone.prototype.returnToRest = function () {
  78095. this.updateMatrix(this._restPose.clone());
  78096. };
  78097. /**
  78098. * Gets the inverse of the absolute transform matrix.
  78099. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78100. * @returns a matrix
  78101. */
  78102. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78103. return this._invertedAbsoluteTransform;
  78104. };
  78105. /**
  78106. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78107. * @returns a matrix
  78108. */
  78109. Bone.prototype.getAbsoluteTransform = function () {
  78110. return this._absoluteTransform;
  78111. };
  78112. Object.defineProperty(Bone.prototype, "position", {
  78113. // Properties (matches AbstractMesh properties)
  78114. /** Gets or sets current position (in local space) */
  78115. get: function () {
  78116. this._decompose();
  78117. return this._localPosition;
  78118. },
  78119. set: function (newPosition) {
  78120. this._decompose();
  78121. this._localPosition.copyFrom(newPosition);
  78122. this._markAsDirtyAndCompose();
  78123. },
  78124. enumerable: true,
  78125. configurable: true
  78126. });
  78127. Object.defineProperty(Bone.prototype, "rotation", {
  78128. /** Gets or sets current rotation (in local space) */
  78129. get: function () {
  78130. return this.getRotation();
  78131. },
  78132. set: function (newRotation) {
  78133. this.setRotation(newRotation);
  78134. },
  78135. enumerable: true,
  78136. configurable: true
  78137. });
  78138. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78139. /** Gets or sets current rotation quaternion (in local space) */
  78140. get: function () {
  78141. this._decompose();
  78142. return this._localRotation;
  78143. },
  78144. set: function (newRotation) {
  78145. this.setRotationQuaternion(newRotation);
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. Object.defineProperty(Bone.prototype, "scaling", {
  78151. /** Gets or sets current scaling (in local space) */
  78152. get: function () {
  78153. return this.getScale();
  78154. },
  78155. set: function (newScaling) {
  78156. this.setScale(newScaling);
  78157. },
  78158. enumerable: true,
  78159. configurable: true
  78160. });
  78161. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78162. /**
  78163. * Gets the animation properties override
  78164. */
  78165. get: function () {
  78166. return this._skeleton.animationPropertiesOverride;
  78167. },
  78168. enumerable: true,
  78169. configurable: true
  78170. });
  78171. // Methods
  78172. Bone.prototype._decompose = function () {
  78173. if (!this._needToDecompose) {
  78174. return;
  78175. }
  78176. this._needToDecompose = false;
  78177. if (!this._localScaling) {
  78178. this._localScaling = BABYLON.Vector3.Zero();
  78179. this._localRotation = BABYLON.Quaternion.Zero();
  78180. this._localPosition = BABYLON.Vector3.Zero();
  78181. }
  78182. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78183. };
  78184. Bone.prototype._compose = function () {
  78185. if (!this._needToCompose) {
  78186. return;
  78187. }
  78188. this._needToCompose = false;
  78189. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78190. };
  78191. /**
  78192. * Update the base and local matrices
  78193. * @param matrix defines the new base or local matrix
  78194. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78195. * @param updateLocalMatrix defines if the local matrix should be updated
  78196. */
  78197. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78198. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78199. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78200. this._baseMatrix.copyFrom(matrix);
  78201. if (updateDifferenceMatrix) {
  78202. this._updateDifferenceMatrix();
  78203. }
  78204. if (updateLocalMatrix) {
  78205. this._localMatrix.copyFrom(matrix);
  78206. this._markAsDirtyAndDecompose();
  78207. }
  78208. else {
  78209. this.markAsDirty();
  78210. }
  78211. };
  78212. /** @hidden */
  78213. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78214. if (updateChildren === void 0) { updateChildren = true; }
  78215. if (!rootMatrix) {
  78216. rootMatrix = this._baseMatrix;
  78217. }
  78218. if (this._parent) {
  78219. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78220. }
  78221. else {
  78222. this._absoluteTransform.copyFrom(rootMatrix);
  78223. }
  78224. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78225. if (updateChildren) {
  78226. for (var index = 0; index < this.children.length; index++) {
  78227. this.children[index]._updateDifferenceMatrix();
  78228. }
  78229. }
  78230. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78231. };
  78232. /**
  78233. * Flag the bone as dirty (Forcing it to update everything)
  78234. */
  78235. Bone.prototype.markAsDirty = function () {
  78236. this._currentRenderId++;
  78237. this._childRenderId++;
  78238. this._skeleton._markAsDirty();
  78239. };
  78240. Bone.prototype._markAsDirtyAndCompose = function () {
  78241. this.markAsDirty();
  78242. this._needToCompose = true;
  78243. };
  78244. Bone.prototype._markAsDirtyAndDecompose = function () {
  78245. this.markAsDirty();
  78246. this._needToDecompose = true;
  78247. };
  78248. /**
  78249. * Copy an animation range from another bone
  78250. * @param source defines the source bone
  78251. * @param rangeName defines the range name to copy
  78252. * @param frameOffset defines the frame offset
  78253. * @param rescaleAsRequired defines if rescaling must be applied if required
  78254. * @param skelDimensionsRatio defines the scaling ratio
  78255. * @returns true if operation was successful
  78256. */
  78257. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78258. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78259. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78260. // all animation may be coming from a library skeleton, so may need to create animation
  78261. if (this.animations.length === 0) {
  78262. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78263. this.animations[0].setKeys([]);
  78264. }
  78265. // get animation info / verify there is such a range from the source bone
  78266. var sourceRange = source.animations[0].getRange(rangeName);
  78267. if (!sourceRange) {
  78268. return false;
  78269. }
  78270. var from = sourceRange.from;
  78271. var to = sourceRange.to;
  78272. var sourceKeys = source.animations[0].getKeys();
  78273. // rescaling prep
  78274. var sourceBoneLength = source.length;
  78275. var sourceParent = source.getParent();
  78276. var parent = this.getParent();
  78277. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78278. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78279. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78280. var destKeys = this.animations[0].getKeys();
  78281. // loop vars declaration
  78282. var orig;
  78283. var origTranslation;
  78284. var mat;
  78285. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78286. orig = sourceKeys[key];
  78287. if (orig.frame >= from && orig.frame <= to) {
  78288. if (rescaleAsRequired) {
  78289. mat = orig.value.clone();
  78290. // scale based on parent ratio, when bone has parent
  78291. if (parentScalingReqd) {
  78292. origTranslation = mat.getTranslation();
  78293. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78294. // scale based on skeleton dimension ratio when root bone, and value is passed
  78295. }
  78296. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78297. origTranslation = mat.getTranslation();
  78298. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78299. // use original when root bone, and no data for skelDimensionsRatio
  78300. }
  78301. else {
  78302. mat = orig.value;
  78303. }
  78304. }
  78305. else {
  78306. mat = orig.value;
  78307. }
  78308. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78309. }
  78310. }
  78311. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78312. return true;
  78313. };
  78314. /**
  78315. * Translate the bone in local or world space
  78316. * @param vec The amount to translate the bone
  78317. * @param space The space that the translation is in
  78318. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78319. */
  78320. Bone.prototype.translate = function (vec, space, mesh) {
  78321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78322. var lm = this.getLocalMatrix();
  78323. if (space == BABYLON.Space.LOCAL) {
  78324. lm.m[12] += vec.x;
  78325. lm.m[13] += vec.y;
  78326. lm.m[14] += vec.z;
  78327. }
  78328. else {
  78329. var wm = null;
  78330. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78331. if (mesh) {
  78332. wm = mesh.getWorldMatrix();
  78333. }
  78334. this._skeleton.computeAbsoluteTransforms();
  78335. var tmat = Bone._tmpMats[0];
  78336. var tvec = Bone._tmpVecs[0];
  78337. if (this._parent) {
  78338. if (mesh && wm) {
  78339. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78340. tmat.multiplyToRef(wm, tmat);
  78341. }
  78342. else {
  78343. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78344. }
  78345. }
  78346. tmat.m[12] = 0;
  78347. tmat.m[13] = 0;
  78348. tmat.m[14] = 0;
  78349. tmat.invert();
  78350. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78351. lm.m[12] += tvec.x;
  78352. lm.m[13] += tvec.y;
  78353. lm.m[14] += tvec.z;
  78354. }
  78355. this._markAsDirtyAndDecompose();
  78356. };
  78357. /**
  78358. * Set the postion of the bone in local or world space
  78359. * @param position The position to set the bone
  78360. * @param space The space that the position is in
  78361. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78362. */
  78363. Bone.prototype.setPosition = function (position, space, mesh) {
  78364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78365. var lm = this.getLocalMatrix();
  78366. if (space == BABYLON.Space.LOCAL) {
  78367. lm.m[12] = position.x;
  78368. lm.m[13] = position.y;
  78369. lm.m[14] = position.z;
  78370. }
  78371. else {
  78372. var wm = null;
  78373. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78374. if (mesh) {
  78375. wm = mesh.getWorldMatrix();
  78376. }
  78377. this._skeleton.computeAbsoluteTransforms();
  78378. var tmat = Bone._tmpMats[0];
  78379. var vec = Bone._tmpVecs[0];
  78380. if (this._parent) {
  78381. if (mesh && wm) {
  78382. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78383. tmat.multiplyToRef(wm, tmat);
  78384. }
  78385. else {
  78386. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78387. }
  78388. }
  78389. tmat.invert();
  78390. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78391. lm.m[12] = vec.x;
  78392. lm.m[13] = vec.y;
  78393. lm.m[14] = vec.z;
  78394. }
  78395. this._markAsDirtyAndDecompose();
  78396. };
  78397. /**
  78398. * Set the absolute position of the bone (world space)
  78399. * @param position The position to set the bone
  78400. * @param mesh The mesh that this bone is attached to
  78401. */
  78402. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78403. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78404. };
  78405. /**
  78406. * Scale the bone on the x, y and z axes (in local space)
  78407. * @param x The amount to scale the bone on the x axis
  78408. * @param y The amount to scale the bone on the y axis
  78409. * @param z The amount to scale the bone on the z axis
  78410. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78411. */
  78412. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78413. if (scaleChildren === void 0) { scaleChildren = false; }
  78414. var locMat = this.getLocalMatrix();
  78415. // Apply new scaling on top of current local matrix
  78416. var scaleMat = Bone._tmpMats[0];
  78417. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78418. scaleMat.multiplyToRef(locMat, locMat);
  78419. // Invert scaling matrix and apply the inverse to all children
  78420. scaleMat.invert();
  78421. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78422. var child = _a[_i];
  78423. var cm = child.getLocalMatrix();
  78424. cm.multiplyToRef(scaleMat, cm);
  78425. cm.m[12] *= x;
  78426. cm.m[13] *= y;
  78427. cm.m[14] *= z;
  78428. child._markAsDirtyAndDecompose();
  78429. }
  78430. this._markAsDirtyAndDecompose();
  78431. if (scaleChildren) {
  78432. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78433. var child = _c[_b];
  78434. child.scale(x, y, z, scaleChildren);
  78435. }
  78436. }
  78437. };
  78438. /**
  78439. * Set the bone scaling in local space
  78440. * @param scale defines the scaling vector
  78441. */
  78442. Bone.prototype.setScale = function (scale) {
  78443. this._decompose();
  78444. this._localScaling.copyFrom(scale);
  78445. this._markAsDirtyAndCompose();
  78446. };
  78447. /**
  78448. * Gets the current scaling in local space
  78449. * @returns the current scaling vector
  78450. */
  78451. Bone.prototype.getScale = function () {
  78452. this._decompose();
  78453. return this._localScaling;
  78454. };
  78455. /**
  78456. * Gets the current scaling in local space and stores it in a target vector
  78457. * @param result defines the target vector
  78458. */
  78459. Bone.prototype.getScaleToRef = function (result) {
  78460. this._decompose();
  78461. result.copyFrom(this._localScaling);
  78462. };
  78463. /**
  78464. * Set the yaw, pitch, and roll of the bone in local or world space
  78465. * @param yaw The rotation of the bone on the y axis
  78466. * @param pitch The rotation of the bone on the x axis
  78467. * @param roll The rotation of the bone on the z axis
  78468. * @param space The space that the axes of rotation are in
  78469. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78470. */
  78471. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78472. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78473. if (space === BABYLON.Space.LOCAL) {
  78474. var quat = Bone._tmpQuat;
  78475. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78476. this.setRotationQuaternion(quat, space, mesh);
  78477. return;
  78478. }
  78479. var rotMatInv = Bone._tmpMats[0];
  78480. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78481. return;
  78482. }
  78483. var rotMat = Bone._tmpMats[1];
  78484. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78485. rotMatInv.multiplyToRef(rotMat, rotMat);
  78486. this._rotateWithMatrix(rotMat, space, mesh);
  78487. };
  78488. /**
  78489. * Add a rotation to the bone on an axis in local or world space
  78490. * @param axis The axis to rotate the bone on
  78491. * @param amount The amount to rotate the bone
  78492. * @param space The space that the axis is in
  78493. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78494. */
  78495. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78497. var rmat = Bone._tmpMats[0];
  78498. rmat.m[12] = 0;
  78499. rmat.m[13] = 0;
  78500. rmat.m[14] = 0;
  78501. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78502. this._rotateWithMatrix(rmat, space, mesh);
  78503. };
  78504. /**
  78505. * Set the rotation of the bone to a particular axis angle in local or world space
  78506. * @param axis The axis to rotate the bone on
  78507. * @param angle The angle that the bone should be rotated to
  78508. * @param space The space that the axis is in
  78509. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78510. */
  78511. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78512. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78513. if (space === BABYLON.Space.LOCAL) {
  78514. var quat = Bone._tmpQuat;
  78515. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78516. this.setRotationQuaternion(quat, space, mesh);
  78517. return;
  78518. }
  78519. var rotMatInv = Bone._tmpMats[0];
  78520. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78521. return;
  78522. }
  78523. var rotMat = Bone._tmpMats[1];
  78524. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78525. rotMatInv.multiplyToRef(rotMat, rotMat);
  78526. this._rotateWithMatrix(rotMat, space, mesh);
  78527. };
  78528. /**
  78529. * Set the euler rotation of the bone in local of world space
  78530. * @param rotation The euler rotation that the bone should be set to
  78531. * @param space The space that the rotation is in
  78532. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78533. */
  78534. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78536. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78537. };
  78538. /**
  78539. * Set the quaternion rotation of the bone in local of world space
  78540. * @param quat The quaternion rotation that the bone should be set to
  78541. * @param space The space that the rotation is in
  78542. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78543. */
  78544. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78546. if (space === BABYLON.Space.LOCAL) {
  78547. this._decompose();
  78548. this._localRotation.copyFrom(quat);
  78549. this._markAsDirtyAndCompose();
  78550. return;
  78551. }
  78552. var rotMatInv = Bone._tmpMats[0];
  78553. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78554. return;
  78555. }
  78556. var rotMat = Bone._tmpMats[1];
  78557. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78558. rotMatInv.multiplyToRef(rotMat, rotMat);
  78559. this._rotateWithMatrix(rotMat, space, mesh);
  78560. };
  78561. /**
  78562. * Set the rotation matrix of the bone in local of world space
  78563. * @param rotMat The rotation matrix that the bone should be set to
  78564. * @param space The space that the rotation is in
  78565. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78566. */
  78567. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78568. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78569. if (space === BABYLON.Space.LOCAL) {
  78570. var quat = Bone._tmpQuat;
  78571. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78572. this.setRotationQuaternion(quat, space, mesh);
  78573. return;
  78574. }
  78575. var rotMatInv = Bone._tmpMats[0];
  78576. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78577. return;
  78578. }
  78579. var rotMat2 = Bone._tmpMats[1];
  78580. rotMat2.copyFrom(rotMat);
  78581. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78582. this._rotateWithMatrix(rotMat2, space, mesh);
  78583. };
  78584. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78586. var lmat = this.getLocalMatrix();
  78587. var lx = lmat.m[12];
  78588. var ly = lmat.m[13];
  78589. var lz = lmat.m[14];
  78590. var parent = this.getParent();
  78591. var parentScale = Bone._tmpMats[3];
  78592. var parentScaleInv = Bone._tmpMats[4];
  78593. if (parent && space == BABYLON.Space.WORLD) {
  78594. if (mesh) {
  78595. parentScale.copyFrom(mesh.getWorldMatrix());
  78596. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78597. }
  78598. else {
  78599. parentScale.copyFrom(parent.getAbsoluteTransform());
  78600. }
  78601. parentScaleInv.copyFrom(parentScale);
  78602. parentScaleInv.invert();
  78603. lmat.multiplyToRef(parentScale, lmat);
  78604. lmat.multiplyToRef(rmat, lmat);
  78605. lmat.multiplyToRef(parentScaleInv, lmat);
  78606. }
  78607. else {
  78608. if (space == BABYLON.Space.WORLD && mesh) {
  78609. parentScale.copyFrom(mesh.getWorldMatrix());
  78610. parentScaleInv.copyFrom(parentScale);
  78611. parentScaleInv.invert();
  78612. lmat.multiplyToRef(parentScale, lmat);
  78613. lmat.multiplyToRef(rmat, lmat);
  78614. lmat.multiplyToRef(parentScaleInv, lmat);
  78615. }
  78616. else {
  78617. lmat.multiplyToRef(rmat, lmat);
  78618. }
  78619. }
  78620. lmat.m[12] = lx;
  78621. lmat.m[13] = ly;
  78622. lmat.m[14] = lz;
  78623. this.computeAbsoluteTransforms();
  78624. this._markAsDirtyAndDecompose();
  78625. };
  78626. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78627. var scaleMatrix = Bone._tmpMats[2];
  78628. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78629. if (mesh) {
  78630. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78631. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78632. }
  78633. rotMatInv.invert();
  78634. if (isNaN(rotMatInv.m[0])) {
  78635. // Matrix failed to invert.
  78636. // This can happen if scale is zero for example.
  78637. return false;
  78638. }
  78639. scaleMatrix.m[0] *= this._scalingDeterminant;
  78640. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78641. return true;
  78642. };
  78643. /**
  78644. * Get the position of the bone in local or world space
  78645. * @param space The space that the returned position is in
  78646. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78647. * @returns The position of the bone
  78648. */
  78649. Bone.prototype.getPosition = function (space, mesh) {
  78650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78651. if (mesh === void 0) { mesh = null; }
  78652. var pos = BABYLON.Vector3.Zero();
  78653. this.getPositionToRef(space, mesh, pos);
  78654. return pos;
  78655. };
  78656. /**
  78657. * Copy the position of the bone to a vector3 in local or world space
  78658. * @param space The space that the returned position is in
  78659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78660. * @param result The vector3 to copy the position to
  78661. */
  78662. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78664. if (space == BABYLON.Space.LOCAL) {
  78665. var lm = this.getLocalMatrix();
  78666. result.x = lm.m[12];
  78667. result.y = lm.m[13];
  78668. result.z = lm.m[14];
  78669. }
  78670. else {
  78671. var wm = null;
  78672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78673. if (mesh) {
  78674. wm = mesh.getWorldMatrix();
  78675. }
  78676. this._skeleton.computeAbsoluteTransforms();
  78677. var tmat = Bone._tmpMats[0];
  78678. if (mesh && wm) {
  78679. tmat.copyFrom(this.getAbsoluteTransform());
  78680. tmat.multiplyToRef(wm, tmat);
  78681. }
  78682. else {
  78683. tmat = this.getAbsoluteTransform();
  78684. }
  78685. result.x = tmat.m[12];
  78686. result.y = tmat.m[13];
  78687. result.z = tmat.m[14];
  78688. }
  78689. };
  78690. /**
  78691. * Get the absolute position of the bone (world space)
  78692. * @param mesh The mesh that this bone is attached to
  78693. * @returns The absolute position of the bone
  78694. */
  78695. Bone.prototype.getAbsolutePosition = function (mesh) {
  78696. if (mesh === void 0) { mesh = null; }
  78697. var pos = BABYLON.Vector3.Zero();
  78698. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78699. return pos;
  78700. };
  78701. /**
  78702. * Copy the absolute position of the bone (world space) to the result param
  78703. * @param mesh The mesh that this bone is attached to
  78704. * @param result The vector3 to copy the absolute position to
  78705. */
  78706. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78707. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78708. };
  78709. /**
  78710. * Compute the absolute transforms of this bone and its children
  78711. */
  78712. Bone.prototype.computeAbsoluteTransforms = function () {
  78713. this._compose();
  78714. if (this._parent) {
  78715. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78716. }
  78717. else {
  78718. this._absoluteTransform.copyFrom(this._localMatrix);
  78719. var poseMatrix = this._skeleton.getPoseMatrix();
  78720. if (poseMatrix) {
  78721. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78722. }
  78723. }
  78724. var children = this.children;
  78725. var len = children.length;
  78726. for (var i = 0; i < len; i++) {
  78727. children[i].computeAbsoluteTransforms();
  78728. }
  78729. };
  78730. /**
  78731. * Get the world direction from an axis that is in the local space of the bone
  78732. * @param localAxis The local direction that is used to compute the world direction
  78733. * @param mesh The mesh that this bone is attached to
  78734. * @returns The world direction
  78735. */
  78736. Bone.prototype.getDirection = function (localAxis, mesh) {
  78737. if (mesh === void 0) { mesh = null; }
  78738. var result = BABYLON.Vector3.Zero();
  78739. this.getDirectionToRef(localAxis, mesh, result);
  78740. return result;
  78741. };
  78742. /**
  78743. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78744. * @param localAxis The local direction that is used to compute the world direction
  78745. * @param mesh The mesh that this bone is attached to
  78746. * @param result The vector3 that the world direction will be copied to
  78747. */
  78748. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78749. if (mesh === void 0) { mesh = null; }
  78750. var wm = null;
  78751. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78752. if (mesh) {
  78753. wm = mesh.getWorldMatrix();
  78754. }
  78755. this._skeleton.computeAbsoluteTransforms();
  78756. var mat = Bone._tmpMats[0];
  78757. mat.copyFrom(this.getAbsoluteTransform());
  78758. if (mesh && wm) {
  78759. mat.multiplyToRef(wm, mat);
  78760. }
  78761. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78762. result.normalize();
  78763. };
  78764. /**
  78765. * Get the euler rotation of the bone in local or world space
  78766. * @param space The space that the rotation should be in
  78767. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78768. * @returns The euler rotation
  78769. */
  78770. Bone.prototype.getRotation = function (space, mesh) {
  78771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78772. if (mesh === void 0) { mesh = null; }
  78773. var result = BABYLON.Vector3.Zero();
  78774. this.getRotationToRef(space, mesh, result);
  78775. return result;
  78776. };
  78777. /**
  78778. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78779. * @param space The space that the rotation should be in
  78780. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78781. * @param result The vector3 that the rotation should be copied to
  78782. */
  78783. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78785. if (mesh === void 0) { mesh = null; }
  78786. var quat = Bone._tmpQuat;
  78787. this.getRotationQuaternionToRef(space, mesh, quat);
  78788. quat.toEulerAnglesToRef(result);
  78789. };
  78790. /**
  78791. * Get the quaternion rotation of the bone in either local or world space
  78792. * @param space The space that the rotation should be in
  78793. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78794. * @returns The quaternion rotation
  78795. */
  78796. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78797. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78798. if (mesh === void 0) { mesh = null; }
  78799. var result = BABYLON.Quaternion.Identity();
  78800. this.getRotationQuaternionToRef(space, mesh, result);
  78801. return result;
  78802. };
  78803. /**
  78804. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78805. * @param space The space that the rotation should be in
  78806. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78807. * @param result The quaternion that the rotation should be copied to
  78808. */
  78809. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78811. if (mesh === void 0) { mesh = null; }
  78812. if (space == BABYLON.Space.LOCAL) {
  78813. this._decompose();
  78814. result.copyFrom(this._localRotation);
  78815. }
  78816. else {
  78817. var mat = Bone._tmpMats[0];
  78818. var amat = this.getAbsoluteTransform();
  78819. if (mesh) {
  78820. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78821. }
  78822. else {
  78823. mat.copyFrom(amat);
  78824. }
  78825. mat.m[0] *= this._scalingDeterminant;
  78826. mat.m[1] *= this._scalingDeterminant;
  78827. mat.m[2] *= this._scalingDeterminant;
  78828. mat.decompose(undefined, result, undefined);
  78829. }
  78830. };
  78831. /**
  78832. * Get the rotation matrix of the bone in local or world space
  78833. * @param space The space that the rotation should be in
  78834. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78835. * @returns The rotation matrix
  78836. */
  78837. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78839. var result = BABYLON.Matrix.Identity();
  78840. this.getRotationMatrixToRef(space, mesh, result);
  78841. return result;
  78842. };
  78843. /**
  78844. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78845. * @param space The space that the rotation should be in
  78846. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78847. * @param result The quaternion that the rotation should be copied to
  78848. */
  78849. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78850. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78851. if (space == BABYLON.Space.LOCAL) {
  78852. this.getLocalMatrix().getRotationMatrixToRef(result);
  78853. }
  78854. else {
  78855. var mat = Bone._tmpMats[0];
  78856. var amat = this.getAbsoluteTransform();
  78857. if (mesh) {
  78858. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78859. }
  78860. else {
  78861. mat.copyFrom(amat);
  78862. }
  78863. mat.m[0] *= this._scalingDeterminant;
  78864. mat.m[1] *= this._scalingDeterminant;
  78865. mat.m[2] *= this._scalingDeterminant;
  78866. mat.getRotationMatrixToRef(result);
  78867. }
  78868. };
  78869. /**
  78870. * Get the world position of a point that is in the local space of the bone
  78871. * @param position The local position
  78872. * @param mesh The mesh that this bone is attached to
  78873. * @returns The world position
  78874. */
  78875. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78876. if (mesh === void 0) { mesh = null; }
  78877. var result = BABYLON.Vector3.Zero();
  78878. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78879. return result;
  78880. };
  78881. /**
  78882. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78883. * @param position The local position
  78884. * @param mesh The mesh that this bone is attached to
  78885. * @param result The vector3 that the world position should be copied to
  78886. */
  78887. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78888. if (mesh === void 0) { mesh = null; }
  78889. var wm = null;
  78890. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78891. if (mesh) {
  78892. wm = mesh.getWorldMatrix();
  78893. }
  78894. this._skeleton.computeAbsoluteTransforms();
  78895. var tmat = Bone._tmpMats[0];
  78896. if (mesh && wm) {
  78897. tmat.copyFrom(this.getAbsoluteTransform());
  78898. tmat.multiplyToRef(wm, tmat);
  78899. }
  78900. else {
  78901. tmat = this.getAbsoluteTransform();
  78902. }
  78903. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78904. };
  78905. /**
  78906. * Get the local position of a point that is in world space
  78907. * @param position The world position
  78908. * @param mesh The mesh that this bone is attached to
  78909. * @returns The local position
  78910. */
  78911. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78912. if (mesh === void 0) { mesh = null; }
  78913. var result = BABYLON.Vector3.Zero();
  78914. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78915. return result;
  78916. };
  78917. /**
  78918. * Get the local position of a point that is in world space and copy it to the result param
  78919. * @param position The world position
  78920. * @param mesh The mesh that this bone is attached to
  78921. * @param result The vector3 that the local position should be copied to
  78922. */
  78923. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78924. if (mesh === void 0) { mesh = null; }
  78925. var wm = null;
  78926. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78927. if (mesh) {
  78928. wm = mesh.getWorldMatrix();
  78929. }
  78930. this._skeleton.computeAbsoluteTransforms();
  78931. var tmat = Bone._tmpMats[0];
  78932. tmat.copyFrom(this.getAbsoluteTransform());
  78933. if (mesh && wm) {
  78934. tmat.multiplyToRef(wm, tmat);
  78935. }
  78936. tmat.invert();
  78937. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78938. };
  78939. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78940. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78941. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78942. return Bone;
  78943. }(BABYLON.Node));
  78944. BABYLON.Bone = Bone;
  78945. })(BABYLON || (BABYLON = {}));
  78946. //# sourceMappingURL=babylon.bone.js.map
  78947. var BABYLON;
  78948. (function (BABYLON) {
  78949. /**
  78950. * Class used to apply inverse kinematics to bones
  78951. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78952. */
  78953. var BoneIKController = /** @class */ (function () {
  78954. /**
  78955. * Creates a new BoneIKController
  78956. * @param mesh defines the mesh to control
  78957. * @param bone defines the bone to control
  78958. * @param options defines options to set up the controller
  78959. */
  78960. function BoneIKController(mesh, bone, options) {
  78961. /**
  78962. * Gets or sets the target position
  78963. */
  78964. this.targetPosition = BABYLON.Vector3.Zero();
  78965. /**
  78966. * Gets or sets the pole target position
  78967. */
  78968. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78969. /**
  78970. * Gets or sets the pole target local offset
  78971. */
  78972. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78973. /**
  78974. * Gets or sets the pole angle
  78975. */
  78976. this.poleAngle = 0;
  78977. /**
  78978. * 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)
  78979. */
  78980. this.slerpAmount = 1;
  78981. this._bone1Quat = BABYLON.Quaternion.Identity();
  78982. this._bone1Mat = BABYLON.Matrix.Identity();
  78983. this._bone2Ang = Math.PI;
  78984. this._maxAngle = Math.PI;
  78985. this._rightHandedSystem = false;
  78986. this._bendAxis = BABYLON.Vector3.Right();
  78987. this._slerping = false;
  78988. this._adjustRoll = 0;
  78989. this._bone2 = bone;
  78990. this._bone1 = bone.getParent();
  78991. if (!this._bone1) {
  78992. return;
  78993. }
  78994. this.mesh = mesh;
  78995. var bonePos = bone.getPosition();
  78996. if (bone.getAbsoluteTransform().determinant() > 0) {
  78997. this._rightHandedSystem = true;
  78998. this._bendAxis.x = 0;
  78999. this._bendAxis.y = 0;
  79000. this._bendAxis.z = -1;
  79001. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79002. this._adjustRoll = Math.PI * .5;
  79003. this._bendAxis.z = 1;
  79004. }
  79005. }
  79006. if (this._bone1.length) {
  79007. var boneScale1 = this._bone1.getScale();
  79008. var boneScale2 = this._bone2.getScale();
  79009. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79010. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79011. }
  79012. else if (this._bone1.children[0]) {
  79013. mesh.computeWorldMatrix(true);
  79014. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79015. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79016. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79017. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79018. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79019. }
  79020. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79021. this.maxAngle = Math.PI;
  79022. if (options) {
  79023. if (options.targetMesh) {
  79024. this.targetMesh = options.targetMesh;
  79025. this.targetMesh.computeWorldMatrix(true);
  79026. }
  79027. if (options.poleTargetMesh) {
  79028. this.poleTargetMesh = options.poleTargetMesh;
  79029. this.poleTargetMesh.computeWorldMatrix(true);
  79030. }
  79031. else if (options.poleTargetBone) {
  79032. this.poleTargetBone = options.poleTargetBone;
  79033. }
  79034. else if (this._bone1.getParent()) {
  79035. this.poleTargetBone = this._bone1.getParent();
  79036. }
  79037. if (options.poleTargetLocalOffset) {
  79038. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79039. }
  79040. if (options.poleAngle) {
  79041. this.poleAngle = options.poleAngle;
  79042. }
  79043. if (options.bendAxis) {
  79044. this._bendAxis.copyFrom(options.bendAxis);
  79045. }
  79046. if (options.maxAngle) {
  79047. this.maxAngle = options.maxAngle;
  79048. }
  79049. if (options.slerpAmount) {
  79050. this.slerpAmount = options.slerpAmount;
  79051. }
  79052. }
  79053. }
  79054. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79055. /**
  79056. * Gets or sets maximum allowed angle
  79057. */
  79058. get: function () {
  79059. return this._maxAngle;
  79060. },
  79061. set: function (value) {
  79062. this._setMaxAngle(value);
  79063. },
  79064. enumerable: true,
  79065. configurable: true
  79066. });
  79067. BoneIKController.prototype._setMaxAngle = function (ang) {
  79068. if (ang < 0) {
  79069. ang = 0;
  79070. }
  79071. if (ang > Math.PI || ang == undefined) {
  79072. ang = Math.PI;
  79073. }
  79074. this._maxAngle = ang;
  79075. var a = this._bone1Length;
  79076. var b = this._bone2Length;
  79077. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79078. };
  79079. /**
  79080. * Force the controller to update the bones
  79081. */
  79082. BoneIKController.prototype.update = function () {
  79083. var bone1 = this._bone1;
  79084. if (!bone1) {
  79085. return;
  79086. }
  79087. var target = this.targetPosition;
  79088. var poleTarget = this.poleTargetPosition;
  79089. var mat1 = BoneIKController._tmpMats[0];
  79090. var mat2 = BoneIKController._tmpMats[1];
  79091. if (this.targetMesh) {
  79092. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79093. }
  79094. if (this.poleTargetBone) {
  79095. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79096. }
  79097. else if (this.poleTargetMesh) {
  79098. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79099. }
  79100. var bonePos = BoneIKController._tmpVecs[0];
  79101. var zaxis = BoneIKController._tmpVecs[1];
  79102. var xaxis = BoneIKController._tmpVecs[2];
  79103. var yaxis = BoneIKController._tmpVecs[3];
  79104. var upAxis = BoneIKController._tmpVecs[4];
  79105. var _tmpQuat = BoneIKController._tmpQuat;
  79106. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79107. poleTarget.subtractToRef(bonePos, upAxis);
  79108. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79109. upAxis.y = 1;
  79110. }
  79111. else {
  79112. upAxis.normalize();
  79113. }
  79114. target.subtractToRef(bonePos, yaxis);
  79115. yaxis.normalize();
  79116. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79117. zaxis.normalize();
  79118. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79119. xaxis.normalize();
  79120. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79121. var a = this._bone1Length;
  79122. var b = this._bone2Length;
  79123. var c = BABYLON.Vector3.Distance(bonePos, target);
  79124. if (this._maxReach > 0) {
  79125. c = Math.min(this._maxReach, c);
  79126. }
  79127. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79128. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79129. if (acosa > 1) {
  79130. acosa = 1;
  79131. }
  79132. if (acosb > 1) {
  79133. acosb = 1;
  79134. }
  79135. if (acosa < -1) {
  79136. acosa = -1;
  79137. }
  79138. if (acosb < -1) {
  79139. acosb = -1;
  79140. }
  79141. var angA = Math.acos(acosa);
  79142. var angB = Math.acos(acosb);
  79143. var angC = -angA - angB;
  79144. if (this._rightHandedSystem) {
  79145. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79146. mat2.multiplyToRef(mat1, mat1);
  79147. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79148. mat2.multiplyToRef(mat1, mat1);
  79149. }
  79150. else {
  79151. var _tmpVec = BoneIKController._tmpVecs[5];
  79152. _tmpVec.copyFrom(this._bendAxis);
  79153. _tmpVec.x *= -1;
  79154. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79155. mat2.multiplyToRef(mat1, mat1);
  79156. }
  79157. if (this.poleAngle) {
  79158. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79159. mat1.multiplyToRef(mat2, mat1);
  79160. }
  79161. if (this._bone1) {
  79162. if (this.slerpAmount < 1) {
  79163. if (!this._slerping) {
  79164. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79165. }
  79166. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79167. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79168. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79169. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79170. this._slerping = true;
  79171. }
  79172. else {
  79173. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79174. this._bone1Mat.copyFrom(mat1);
  79175. this._slerping = false;
  79176. }
  79177. }
  79178. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79179. this._bone2Ang = angC;
  79180. };
  79181. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79182. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79183. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79184. return BoneIKController;
  79185. }());
  79186. BABYLON.BoneIKController = BoneIKController;
  79187. })(BABYLON || (BABYLON = {}));
  79188. //# sourceMappingURL=babylon.boneIKController.js.map
  79189. var BABYLON;
  79190. (function (BABYLON) {
  79191. /**
  79192. * Class used to make a bone look toward a point in space
  79193. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79194. */
  79195. var BoneLookController = /** @class */ (function () {
  79196. /**
  79197. * Create a BoneLookController
  79198. * @param mesh the mesh that the bone belongs to
  79199. * @param bone the bone that will be looking to the target
  79200. * @param target the target Vector3 to look at
  79201. * @param settings optional settings:
  79202. * * maxYaw: the maximum angle the bone will yaw to
  79203. * * minYaw: the minimum angle the bone will yaw to
  79204. * * maxPitch: the maximum angle the bone will pitch to
  79205. * * minPitch: the minimum angle the bone will yaw to
  79206. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79207. * * upAxis: the up axis of the coordinate system
  79208. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79209. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79210. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79211. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79212. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79213. * * adjustRoll: used to make an adjustment to the roll of the bone
  79214. **/
  79215. function BoneLookController(mesh, bone, target, options) {
  79216. /**
  79217. * The up axis of the coordinate system that is used when the bone is rotated
  79218. */
  79219. this.upAxis = BABYLON.Vector3.Up();
  79220. /**
  79221. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79222. */
  79223. this.upAxisSpace = BABYLON.Space.LOCAL;
  79224. /**
  79225. * Used to make an adjustment to the yaw of the bone
  79226. */
  79227. this.adjustYaw = 0;
  79228. /**
  79229. * Used to make an adjustment to the pitch of the bone
  79230. */
  79231. this.adjustPitch = 0;
  79232. /**
  79233. * Used to make an adjustment to the roll of the bone
  79234. */
  79235. this.adjustRoll = 0;
  79236. /**
  79237. * 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)
  79238. */
  79239. this.slerpAmount = 1;
  79240. this._boneQuat = BABYLON.Quaternion.Identity();
  79241. this._slerping = false;
  79242. this._firstFrameSkipped = false;
  79243. this._fowardAxis = BABYLON.Vector3.Forward();
  79244. this.mesh = mesh;
  79245. this.bone = bone;
  79246. this.target = target;
  79247. if (options) {
  79248. if (options.adjustYaw) {
  79249. this.adjustYaw = options.adjustYaw;
  79250. }
  79251. if (options.adjustPitch) {
  79252. this.adjustPitch = options.adjustPitch;
  79253. }
  79254. if (options.adjustRoll) {
  79255. this.adjustRoll = options.adjustRoll;
  79256. }
  79257. if (options.maxYaw != null) {
  79258. this.maxYaw = options.maxYaw;
  79259. }
  79260. else {
  79261. this.maxYaw = Math.PI;
  79262. }
  79263. if (options.minYaw != null) {
  79264. this.minYaw = options.minYaw;
  79265. }
  79266. else {
  79267. this.minYaw = -Math.PI;
  79268. }
  79269. if (options.maxPitch != null) {
  79270. this.maxPitch = options.maxPitch;
  79271. }
  79272. else {
  79273. this.maxPitch = Math.PI;
  79274. }
  79275. if (options.minPitch != null) {
  79276. this.minPitch = options.minPitch;
  79277. }
  79278. else {
  79279. this.minPitch = -Math.PI;
  79280. }
  79281. if (options.slerpAmount != null) {
  79282. this.slerpAmount = options.slerpAmount;
  79283. }
  79284. if (options.upAxis != null) {
  79285. this.upAxis = options.upAxis;
  79286. }
  79287. if (options.upAxisSpace != null) {
  79288. this.upAxisSpace = options.upAxisSpace;
  79289. }
  79290. if (options.yawAxis != null || options.pitchAxis != null) {
  79291. var newYawAxis = BABYLON.Axis.Y;
  79292. var newPitchAxis = BABYLON.Axis.X;
  79293. if (options.yawAxis != null) {
  79294. newYawAxis = options.yawAxis.clone();
  79295. newYawAxis.normalize();
  79296. }
  79297. if (options.pitchAxis != null) {
  79298. newPitchAxis = options.pitchAxis.clone();
  79299. newPitchAxis.normalize();
  79300. }
  79301. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79302. this._transformYawPitch = BABYLON.Matrix.Identity();
  79303. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79304. this._transformYawPitchInv = this._transformYawPitch.clone();
  79305. this._transformYawPitch.invert();
  79306. }
  79307. }
  79308. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79309. this.upAxisSpace = BABYLON.Space.LOCAL;
  79310. }
  79311. }
  79312. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79313. /**
  79314. * Gets or sets the minimum yaw angle that the bone can look to
  79315. */
  79316. get: function () {
  79317. return this._minYaw;
  79318. },
  79319. set: function (value) {
  79320. this._minYaw = value;
  79321. this._minYawSin = Math.sin(value);
  79322. this._minYawCos = Math.cos(value);
  79323. if (this._maxYaw != null) {
  79324. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79325. this._yawRange = this._maxYaw - this._minYaw;
  79326. }
  79327. },
  79328. enumerable: true,
  79329. configurable: true
  79330. });
  79331. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79332. /**
  79333. * Gets or sets the maximum yaw angle that the bone can look to
  79334. */
  79335. get: function () {
  79336. return this._maxYaw;
  79337. },
  79338. set: function (value) {
  79339. this._maxYaw = value;
  79340. this._maxYawSin = Math.sin(value);
  79341. this._maxYawCos = Math.cos(value);
  79342. if (this._minYaw != null) {
  79343. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79344. this._yawRange = this._maxYaw - this._minYaw;
  79345. }
  79346. },
  79347. enumerable: true,
  79348. configurable: true
  79349. });
  79350. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79351. /**
  79352. * Gets or sets the minimum pitch angle that the bone can look to
  79353. */
  79354. get: function () {
  79355. return this._minPitch;
  79356. },
  79357. set: function (value) {
  79358. this._minPitch = value;
  79359. this._minPitchTan = Math.tan(value);
  79360. },
  79361. enumerable: true,
  79362. configurable: true
  79363. });
  79364. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79365. /**
  79366. * Gets or sets the maximum pitch angle that the bone can look to
  79367. */
  79368. get: function () {
  79369. return this._maxPitch;
  79370. },
  79371. set: function (value) {
  79372. this._maxPitch = value;
  79373. this._maxPitchTan = Math.tan(value);
  79374. },
  79375. enumerable: true,
  79376. configurable: true
  79377. });
  79378. /**
  79379. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79380. */
  79381. BoneLookController.prototype.update = function () {
  79382. //skip the first frame when slerping so that the mesh rotation is correct
  79383. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79384. this._firstFrameSkipped = true;
  79385. return;
  79386. }
  79387. var bone = this.bone;
  79388. var bonePos = BoneLookController._tmpVecs[0];
  79389. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79390. var target = this.target;
  79391. var _tmpMat1 = BoneLookController._tmpMats[0];
  79392. var _tmpMat2 = BoneLookController._tmpMats[1];
  79393. var mesh = this.mesh;
  79394. var parentBone = bone.getParent();
  79395. var upAxis = BoneLookController._tmpVecs[1];
  79396. upAxis.copyFrom(this.upAxis);
  79397. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79398. if (this._transformYawPitch) {
  79399. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79400. }
  79401. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79402. }
  79403. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79404. mesh.getDirectionToRef(upAxis, upAxis);
  79405. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79406. upAxis.normalize();
  79407. }
  79408. }
  79409. var checkYaw = false;
  79410. var checkPitch = false;
  79411. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79412. checkYaw = true;
  79413. }
  79414. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79415. checkPitch = true;
  79416. }
  79417. if (checkYaw || checkPitch) {
  79418. var spaceMat = BoneLookController._tmpMats[2];
  79419. var spaceMatInv = BoneLookController._tmpMats[3];
  79420. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79421. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79422. }
  79423. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79424. spaceMat.copyFrom(mesh.getWorldMatrix());
  79425. }
  79426. else {
  79427. var forwardAxis = BoneLookController._tmpVecs[2];
  79428. forwardAxis.copyFrom(this._fowardAxis);
  79429. if (this._transformYawPitch) {
  79430. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79431. }
  79432. if (parentBone) {
  79433. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79434. }
  79435. else {
  79436. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79437. }
  79438. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79439. rightAxis.normalize();
  79440. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79441. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79442. }
  79443. spaceMat.invertToRef(spaceMatInv);
  79444. var xzlen = null;
  79445. if (checkPitch) {
  79446. var localTarget = BoneLookController._tmpVecs[3];
  79447. target.subtractToRef(bonePos, localTarget);
  79448. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79449. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79450. var pitch = Math.atan2(localTarget.y, xzlen);
  79451. var newPitch = pitch;
  79452. if (pitch > this._maxPitch) {
  79453. localTarget.y = this._maxPitchTan * xzlen;
  79454. newPitch = this._maxPitch;
  79455. }
  79456. else if (pitch < this._minPitch) {
  79457. localTarget.y = this._minPitchTan * xzlen;
  79458. newPitch = this._minPitch;
  79459. }
  79460. if (pitch != newPitch) {
  79461. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79462. localTarget.addInPlace(bonePos);
  79463. target = localTarget;
  79464. }
  79465. }
  79466. if (checkYaw) {
  79467. var localTarget = BoneLookController._tmpVecs[4];
  79468. target.subtractToRef(bonePos, localTarget);
  79469. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79470. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79471. var newYaw = yaw;
  79472. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79473. if (xzlen == null) {
  79474. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79475. }
  79476. if (this._yawRange > Math.PI) {
  79477. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79478. localTarget.z = this._maxYawCos * xzlen;
  79479. localTarget.x = this._maxYawSin * xzlen;
  79480. newYaw = this._maxYaw;
  79481. }
  79482. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79483. localTarget.z = this._minYawCos * xzlen;
  79484. localTarget.x = this._minYawSin * xzlen;
  79485. newYaw = this._minYaw;
  79486. }
  79487. }
  79488. else {
  79489. if (yaw > this._maxYaw) {
  79490. localTarget.z = this._maxYawCos * xzlen;
  79491. localTarget.x = this._maxYawSin * xzlen;
  79492. newYaw = this._maxYaw;
  79493. }
  79494. else if (yaw < this._minYaw) {
  79495. localTarget.z = this._minYawCos * xzlen;
  79496. localTarget.x = this._minYawSin * xzlen;
  79497. newYaw = this._minYaw;
  79498. }
  79499. }
  79500. }
  79501. if (this._slerping && this._yawRange > Math.PI) {
  79502. //are we going to be crossing into the min/max region?
  79503. var boneFwd = BoneLookController._tmpVecs[8];
  79504. boneFwd.copyFrom(BABYLON.Axis.Z);
  79505. if (this._transformYawPitch) {
  79506. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79507. }
  79508. var boneRotMat = BoneLookController._tmpMats[4];
  79509. this._boneQuat.toRotationMatrix(boneRotMat);
  79510. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79511. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79512. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79513. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79514. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79515. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79516. if (angBtwTar > angBtwMidYaw) {
  79517. if (xzlen == null) {
  79518. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79519. }
  79520. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79521. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79522. if (angBtwMin < angBtwMax) {
  79523. newYaw = boneYaw + Math.PI * .75;
  79524. localTarget.z = Math.cos(newYaw) * xzlen;
  79525. localTarget.x = Math.sin(newYaw) * xzlen;
  79526. }
  79527. else {
  79528. newYaw = boneYaw - Math.PI * .75;
  79529. localTarget.z = Math.cos(newYaw) * xzlen;
  79530. localTarget.x = Math.sin(newYaw) * xzlen;
  79531. }
  79532. }
  79533. }
  79534. if (yaw != newYaw) {
  79535. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79536. localTarget.addInPlace(bonePos);
  79537. target = localTarget;
  79538. }
  79539. }
  79540. }
  79541. var zaxis = BoneLookController._tmpVecs[5];
  79542. var xaxis = BoneLookController._tmpVecs[6];
  79543. var yaxis = BoneLookController._tmpVecs[7];
  79544. var _tmpQuat = BoneLookController._tmpQuat;
  79545. target.subtractToRef(bonePos, zaxis);
  79546. zaxis.normalize();
  79547. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79548. xaxis.normalize();
  79549. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79550. yaxis.normalize();
  79551. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79552. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79553. return;
  79554. }
  79555. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79556. return;
  79557. }
  79558. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79559. return;
  79560. }
  79561. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79562. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79563. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79564. }
  79565. if (this.slerpAmount < 1) {
  79566. if (!this._slerping) {
  79567. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79568. }
  79569. if (this._transformYawPitch) {
  79570. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79571. }
  79572. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79573. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79574. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79575. this._slerping = true;
  79576. }
  79577. else {
  79578. if (this._transformYawPitch) {
  79579. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79580. }
  79581. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79582. this._slerping = false;
  79583. }
  79584. };
  79585. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79586. var angDiff = ang2 - ang1;
  79587. angDiff %= Math.PI * 2;
  79588. if (angDiff > Math.PI) {
  79589. angDiff -= Math.PI * 2;
  79590. }
  79591. else if (angDiff < -Math.PI) {
  79592. angDiff += Math.PI * 2;
  79593. }
  79594. return angDiff;
  79595. };
  79596. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79597. ang1 %= (2 * Math.PI);
  79598. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79599. ang2 %= (2 * Math.PI);
  79600. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79601. var ab = 0;
  79602. if (ang1 < ang2) {
  79603. ab = ang2 - ang1;
  79604. }
  79605. else {
  79606. ab = ang1 - ang2;
  79607. }
  79608. if (ab > Math.PI) {
  79609. ab = Math.PI * 2 - ab;
  79610. }
  79611. return ab;
  79612. };
  79613. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79614. ang %= (2 * Math.PI);
  79615. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79616. ang1 %= (2 * Math.PI);
  79617. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79618. ang2 %= (2 * Math.PI);
  79619. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79620. if (ang1 < ang2) {
  79621. if (ang > ang1 && ang < ang2) {
  79622. return true;
  79623. }
  79624. }
  79625. else {
  79626. if (ang > ang2 && ang < ang1) {
  79627. return true;
  79628. }
  79629. }
  79630. return false;
  79631. };
  79632. 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()];
  79633. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79634. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79635. return BoneLookController;
  79636. }());
  79637. BABYLON.BoneLookController = BoneLookController;
  79638. })(BABYLON || (BABYLON = {}));
  79639. //# sourceMappingURL=babylon.boneLookController.js.map
  79640. var BABYLON;
  79641. (function (BABYLON) {
  79642. /**
  79643. * Class used to handle skinning animations
  79644. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79645. */
  79646. var Skeleton = /** @class */ (function () {
  79647. /**
  79648. * Creates a new skeleton
  79649. * @param name defines the skeleton name
  79650. * @param id defines the skeleton Id
  79651. * @param scene defines the hosting scene
  79652. */
  79653. function Skeleton(
  79654. /** defines the skeleton name */
  79655. name,
  79656. /** defines the skeleton Id */
  79657. id, scene) {
  79658. this.name = name;
  79659. this.id = id;
  79660. /**
  79661. * Gets the list of child bones
  79662. */
  79663. this.bones = new Array();
  79664. /**
  79665. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79666. */
  79667. this.needInitialSkinMatrix = false;
  79668. this._isDirty = true;
  79669. this._meshesWithPoseMatrix = new Array();
  79670. this._identity = BABYLON.Matrix.Identity();
  79671. this._ranges = {};
  79672. this._lastAbsoluteTransformsUpdateId = -1;
  79673. /**
  79674. * Specifies if the skeleton should be serialized
  79675. */
  79676. this.doNotSerialize = false;
  79677. this._animationPropertiesOverride = null;
  79678. // Events
  79679. /**
  79680. * An observable triggered before computing the skeleton's matrices
  79681. */
  79682. this.onBeforeComputeObservable = new BABYLON.Observable();
  79683. this.bones = [];
  79684. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79685. scene.skeletons.push(this);
  79686. //make sure it will recalculate the matrix next time prepare is called.
  79687. this._isDirty = true;
  79688. }
  79689. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79690. /**
  79691. * Gets or sets the animation properties override
  79692. */
  79693. get: function () {
  79694. if (!this._animationPropertiesOverride) {
  79695. return this._scene.animationPropertiesOverride;
  79696. }
  79697. return this._animationPropertiesOverride;
  79698. },
  79699. set: function (value) {
  79700. this._animationPropertiesOverride = value;
  79701. },
  79702. enumerable: true,
  79703. configurable: true
  79704. });
  79705. // Members
  79706. /**
  79707. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79708. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79709. * @returns a Float32Array containing matrices data
  79710. */
  79711. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79712. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79713. return mesh._bonesTransformMatrices;
  79714. }
  79715. if (!this._transformMatrices) {
  79716. this.prepare();
  79717. }
  79718. return this._transformMatrices;
  79719. };
  79720. /**
  79721. * Gets the current hosting scene
  79722. * @returns a scene object
  79723. */
  79724. Skeleton.prototype.getScene = function () {
  79725. return this._scene;
  79726. };
  79727. // Methods
  79728. /**
  79729. * Gets a string representing the current skeleton data
  79730. * @param fullDetails defines a boolean indicating if we want a verbose version
  79731. * @returns a string representing the current skeleton data
  79732. */
  79733. Skeleton.prototype.toString = function (fullDetails) {
  79734. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79735. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79736. if (fullDetails) {
  79737. ret += ", Ranges: {";
  79738. var first = true;
  79739. for (var name_1 in this._ranges) {
  79740. if (first) {
  79741. ret += ", ";
  79742. first = false;
  79743. }
  79744. ret += name_1;
  79745. }
  79746. ret += "}";
  79747. }
  79748. return ret;
  79749. };
  79750. /**
  79751. * Get bone's index searching by name
  79752. * @param name defines bone's name to search for
  79753. * @return the indice of the bone. Returns -1 if not found
  79754. */
  79755. Skeleton.prototype.getBoneIndexByName = function (name) {
  79756. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79757. if (this.bones[boneIndex].name === name) {
  79758. return boneIndex;
  79759. }
  79760. }
  79761. return -1;
  79762. };
  79763. /**
  79764. * Creater a new animation range
  79765. * @param name defines the name of the range
  79766. * @param from defines the start key
  79767. * @param to defines the end key
  79768. */
  79769. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79770. // check name not already in use
  79771. if (!this._ranges[name]) {
  79772. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79773. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79774. if (this.bones[i].animations[0]) {
  79775. this.bones[i].animations[0].createRange(name, from, to);
  79776. }
  79777. }
  79778. }
  79779. };
  79780. /**
  79781. * Delete a specific animation range
  79782. * @param name defines the name of the range
  79783. * @param deleteFrames defines if frames must be removed as well
  79784. */
  79785. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79786. if (deleteFrames === void 0) { deleteFrames = true; }
  79787. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79788. if (this.bones[i].animations[0]) {
  79789. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79790. }
  79791. }
  79792. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79793. };
  79794. /**
  79795. * Gets a specific animation range
  79796. * @param name defines the name of the range to look for
  79797. * @returns the requested animation range or null if not found
  79798. */
  79799. Skeleton.prototype.getAnimationRange = function (name) {
  79800. return this._ranges[name];
  79801. };
  79802. /**
  79803. * Gets the list of all animation ranges defined on this skeleton
  79804. * @returns an array
  79805. */
  79806. Skeleton.prototype.getAnimationRanges = function () {
  79807. var animationRanges = [];
  79808. var name;
  79809. var i = 0;
  79810. for (name in this._ranges) {
  79811. animationRanges[i] = this._ranges[name];
  79812. i++;
  79813. }
  79814. return animationRanges;
  79815. };
  79816. /**
  79817. * Copy animation range from a source skeleton.
  79818. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79819. * @param source defines the source skeleton
  79820. * @param name defines the name of the range to copy
  79821. * @param rescaleAsRequired defines if rescaling must be applied if required
  79822. * @returns true if operation was successful
  79823. */
  79824. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79825. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79826. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79827. return false;
  79828. }
  79829. var ret = true;
  79830. var frameOffset = this._getHighestAnimationFrame() + 1;
  79831. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79832. var boneDict = {};
  79833. var sourceBones = source.bones;
  79834. var nBones;
  79835. var i;
  79836. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79837. boneDict[sourceBones[i].name] = sourceBones[i];
  79838. }
  79839. if (this.bones.length !== sourceBones.length) {
  79840. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79841. ret = false;
  79842. }
  79843. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79844. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79845. var boneName = this.bones[i].name;
  79846. var sourceBone = boneDict[boneName];
  79847. if (sourceBone) {
  79848. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79849. }
  79850. else {
  79851. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79852. ret = false;
  79853. }
  79854. }
  79855. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79856. var range = source.getAnimationRange(name);
  79857. if (range) {
  79858. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79859. }
  79860. return ret;
  79861. };
  79862. /**
  79863. * Forces the skeleton to go to rest pose
  79864. */
  79865. Skeleton.prototype.returnToRest = function () {
  79866. for (var index = 0; index < this.bones.length; index++) {
  79867. this.bones[index].returnToRest();
  79868. }
  79869. };
  79870. Skeleton.prototype._getHighestAnimationFrame = function () {
  79871. var ret = 0;
  79872. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79873. if (this.bones[i].animations[0]) {
  79874. var highest = this.bones[i].animations[0].getHighestFrame();
  79875. if (ret < highest) {
  79876. ret = highest;
  79877. }
  79878. }
  79879. }
  79880. return ret;
  79881. };
  79882. /**
  79883. * Begin a specific animation range
  79884. * @param name defines the name of the range to start
  79885. * @param loop defines if looping must be turned on (false by default)
  79886. * @param speedRatio defines the speed ratio to apply (1 by default)
  79887. * @param onAnimationEnd defines a callback which will be called when animation will end
  79888. * @returns a new animatable
  79889. */
  79890. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79891. var range = this.getAnimationRange(name);
  79892. if (!range) {
  79893. return null;
  79894. }
  79895. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79896. };
  79897. /** @hidden */
  79898. Skeleton.prototype._markAsDirty = function () {
  79899. this._isDirty = true;
  79900. };
  79901. /** @hidden */
  79902. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79903. this._meshesWithPoseMatrix.push(mesh);
  79904. };
  79905. /** @hidden */
  79906. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79907. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79908. if (index > -1) {
  79909. this._meshesWithPoseMatrix.splice(index, 1);
  79910. }
  79911. };
  79912. /** @hidden */
  79913. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79914. this.onBeforeComputeObservable.notifyObservers(this);
  79915. for (var index = 0; index < this.bones.length; index++) {
  79916. var bone = this.bones[index];
  79917. var parentBone = bone.getParent();
  79918. if (parentBone) {
  79919. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79920. }
  79921. else {
  79922. if (initialSkinMatrix) {
  79923. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79924. }
  79925. else {
  79926. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79927. }
  79928. }
  79929. if (bone._index !== -1) {
  79930. var mappedIndex = bone._index === null ? index : bone._index;
  79931. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79932. }
  79933. }
  79934. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79935. };
  79936. /**
  79937. * Build all resources required to render a skeleton
  79938. */
  79939. Skeleton.prototype.prepare = function () {
  79940. if (!this._isDirty) {
  79941. return;
  79942. }
  79943. if (this.needInitialSkinMatrix) {
  79944. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79945. var mesh = this._meshesWithPoseMatrix[index];
  79946. var poseMatrix = mesh.getPoseMatrix();
  79947. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79948. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79949. }
  79950. if (this._synchronizedWithMesh !== mesh) {
  79951. this._synchronizedWithMesh = mesh;
  79952. // Prepare bones
  79953. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79954. var bone = this.bones[boneIndex];
  79955. if (!bone.getParent()) {
  79956. var matrix = bone.getBaseMatrix();
  79957. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79958. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79959. }
  79960. }
  79961. }
  79962. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79963. }
  79964. }
  79965. else {
  79966. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79967. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79968. }
  79969. this._computeTransformMatrices(this._transformMatrices, null);
  79970. }
  79971. this._isDirty = false;
  79972. this._scene._activeBones.addCount(this.bones.length, false);
  79973. };
  79974. /**
  79975. * Gets the list of animatables currently running for this skeleton
  79976. * @returns an array of animatables
  79977. */
  79978. Skeleton.prototype.getAnimatables = function () {
  79979. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79980. this._animatables = [];
  79981. for (var index = 0; index < this.bones.length; index++) {
  79982. this._animatables.push(this.bones[index]);
  79983. }
  79984. }
  79985. return this._animatables;
  79986. };
  79987. /**
  79988. * Clone the current skeleton
  79989. * @param name defines the name of the new skeleton
  79990. * @param id defines the id of the enw skeleton
  79991. * @returns the new skeleton
  79992. */
  79993. Skeleton.prototype.clone = function (name, id) {
  79994. var result = new Skeleton(name, id || name, this._scene);
  79995. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79996. for (var index = 0; index < this.bones.length; index++) {
  79997. var source = this.bones[index];
  79998. var parentBone = null;
  79999. var parent_1 = source.getParent();
  80000. if (parent_1) {
  80001. var parentIndex = this.bones.indexOf(parent_1);
  80002. parentBone = result.bones[parentIndex];
  80003. }
  80004. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80005. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80006. }
  80007. if (this._ranges) {
  80008. result._ranges = {};
  80009. for (var rangeName in this._ranges) {
  80010. var range = this._ranges[rangeName];
  80011. if (range) {
  80012. result._ranges[rangeName] = range.clone();
  80013. }
  80014. }
  80015. }
  80016. this._isDirty = true;
  80017. return result;
  80018. };
  80019. /**
  80020. * Enable animation blending for this skeleton
  80021. * @param blendingSpeed defines the blending speed to apply
  80022. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80023. */
  80024. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80025. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80026. this.bones.forEach(function (bone) {
  80027. bone.animations.forEach(function (animation) {
  80028. animation.enableBlending = true;
  80029. animation.blendingSpeed = blendingSpeed;
  80030. });
  80031. });
  80032. };
  80033. /**
  80034. * Releases all resources associated with the current skeleton
  80035. */
  80036. Skeleton.prototype.dispose = function () {
  80037. this._meshesWithPoseMatrix = [];
  80038. // Animations
  80039. this.getScene().stopAnimation(this);
  80040. // Remove from scene
  80041. this.getScene().removeSkeleton(this);
  80042. };
  80043. /**
  80044. * Serialize the skeleton in a JSON object
  80045. * @returns a JSON object
  80046. */
  80047. Skeleton.prototype.serialize = function () {
  80048. var serializationObject = {};
  80049. serializationObject.name = this.name;
  80050. serializationObject.id = this.id;
  80051. if (this.dimensionsAtRest) {
  80052. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80053. }
  80054. serializationObject.bones = [];
  80055. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80056. for (var index = 0; index < this.bones.length; index++) {
  80057. var bone = this.bones[index];
  80058. var parent_2 = bone.getParent();
  80059. var serializedBone = {
  80060. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80061. name: bone.name,
  80062. matrix: bone.getBaseMatrix().toArray(),
  80063. rest: bone.getRestPose().toArray()
  80064. };
  80065. serializationObject.bones.push(serializedBone);
  80066. if (bone.length) {
  80067. serializedBone.length = bone.length;
  80068. }
  80069. if (bone.metadata) {
  80070. serializedBone.metadata = bone.metadata;
  80071. }
  80072. if (bone.animations && bone.animations.length > 0) {
  80073. serializedBone.animation = bone.animations[0].serialize();
  80074. }
  80075. serializationObject.ranges = [];
  80076. for (var name in this._ranges) {
  80077. var source = this._ranges[name];
  80078. if (!source) {
  80079. continue;
  80080. }
  80081. var range = {};
  80082. range.name = name;
  80083. range.from = source.from;
  80084. range.to = source.to;
  80085. serializationObject.ranges.push(range);
  80086. }
  80087. }
  80088. return serializationObject;
  80089. };
  80090. /**
  80091. * Creates a new skeleton from serialized data
  80092. * @param parsedSkeleton defines the serialized data
  80093. * @param scene defines the hosting scene
  80094. * @returns a new skeleton
  80095. */
  80096. Skeleton.Parse = function (parsedSkeleton, scene) {
  80097. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80098. if (parsedSkeleton.dimensionsAtRest) {
  80099. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80100. }
  80101. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80102. var index;
  80103. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80104. var parsedBone = parsedSkeleton.bones[index];
  80105. var parentBone = null;
  80106. if (parsedBone.parentBoneIndex > -1) {
  80107. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80108. }
  80109. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80110. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80111. if (parsedBone.length) {
  80112. bone.length = parsedBone.length;
  80113. }
  80114. if (parsedBone.metadata) {
  80115. bone.metadata = parsedBone.metadata;
  80116. }
  80117. if (parsedBone.animation) {
  80118. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80119. }
  80120. }
  80121. // placed after bones, so createAnimationRange can cascade down
  80122. if (parsedSkeleton.ranges) {
  80123. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80124. var data = parsedSkeleton.ranges[index];
  80125. skeleton.createAnimationRange(data.name, data.from, data.to);
  80126. }
  80127. }
  80128. return skeleton;
  80129. };
  80130. /**
  80131. * Compute all node absolute transforms
  80132. * @param forceUpdate defines if computation must be done even if cache is up to date
  80133. */
  80134. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80135. if (forceUpdate === void 0) { forceUpdate = false; }
  80136. var renderId = this._scene.getRenderId();
  80137. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80138. this.bones[0].computeAbsoluteTransforms();
  80139. this._lastAbsoluteTransformsUpdateId = renderId;
  80140. }
  80141. };
  80142. /**
  80143. * Gets the root pose matrix
  80144. * @returns a matrix
  80145. */
  80146. Skeleton.prototype.getPoseMatrix = function () {
  80147. var poseMatrix = null;
  80148. if (this._meshesWithPoseMatrix.length > 0) {
  80149. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80150. }
  80151. return poseMatrix;
  80152. };
  80153. /**
  80154. * Sorts bones per internal index
  80155. */
  80156. Skeleton.prototype.sortBones = function () {
  80157. var bones = new Array();
  80158. var visited = new Array(this.bones.length);
  80159. for (var index = 0; index < this.bones.length; index++) {
  80160. this._sortBones(index, bones, visited);
  80161. }
  80162. this.bones = bones;
  80163. };
  80164. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80165. if (visited[index]) {
  80166. return;
  80167. }
  80168. visited[index] = true;
  80169. var bone = this.bones[index];
  80170. if (bone._index === undefined) {
  80171. bone._index = index;
  80172. }
  80173. var parentBone = bone.getParent();
  80174. if (parentBone) {
  80175. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80176. }
  80177. bones.push(bone);
  80178. };
  80179. return Skeleton;
  80180. }());
  80181. BABYLON.Skeleton = Skeleton;
  80182. })(BABYLON || (BABYLON = {}));
  80183. //# sourceMappingURL=babylon.skeleton.js.map
  80184. var BABYLON;
  80185. (function (BABYLON) {
  80186. var SphericalPolynomial = /** @class */ (function () {
  80187. function SphericalPolynomial() {
  80188. this.x = BABYLON.Vector3.Zero();
  80189. this.y = BABYLON.Vector3.Zero();
  80190. this.z = BABYLON.Vector3.Zero();
  80191. this.xx = BABYLON.Vector3.Zero();
  80192. this.yy = BABYLON.Vector3.Zero();
  80193. this.zz = BABYLON.Vector3.Zero();
  80194. this.xy = BABYLON.Vector3.Zero();
  80195. this.yz = BABYLON.Vector3.Zero();
  80196. this.zx = BABYLON.Vector3.Zero();
  80197. }
  80198. SphericalPolynomial.prototype.addAmbient = function (color) {
  80199. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80200. this.xx = this.xx.add(colorVector);
  80201. this.yy = this.yy.add(colorVector);
  80202. this.zz = this.zz.add(colorVector);
  80203. };
  80204. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80205. var result = new SphericalPolynomial();
  80206. result.x = harmonics.L11.scale(1.02333);
  80207. result.y = harmonics.L1_1.scale(1.02333);
  80208. result.z = harmonics.L10.scale(1.02333);
  80209. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80210. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80211. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80212. result.yz = harmonics.L2_1.scale(0.858086);
  80213. result.zx = harmonics.L21.scale(0.858086);
  80214. result.xy = harmonics.L2_2.scale(0.858086);
  80215. result.scale(1.0 / Math.PI);
  80216. return result;
  80217. };
  80218. SphericalPolynomial.prototype.scale = function (scale) {
  80219. this.x = this.x.scale(scale);
  80220. this.y = this.y.scale(scale);
  80221. this.z = this.z.scale(scale);
  80222. this.xx = this.xx.scale(scale);
  80223. this.yy = this.yy.scale(scale);
  80224. this.zz = this.zz.scale(scale);
  80225. this.yz = this.yz.scale(scale);
  80226. this.zx = this.zx.scale(scale);
  80227. this.xy = this.xy.scale(scale);
  80228. };
  80229. return SphericalPolynomial;
  80230. }());
  80231. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80232. var SphericalHarmonics = /** @class */ (function () {
  80233. function SphericalHarmonics() {
  80234. this.L00 = BABYLON.Vector3.Zero();
  80235. this.L1_1 = BABYLON.Vector3.Zero();
  80236. this.L10 = BABYLON.Vector3.Zero();
  80237. this.L11 = BABYLON.Vector3.Zero();
  80238. this.L2_2 = BABYLON.Vector3.Zero();
  80239. this.L2_1 = BABYLON.Vector3.Zero();
  80240. this.L20 = BABYLON.Vector3.Zero();
  80241. this.L21 = BABYLON.Vector3.Zero();
  80242. this.L22 = BABYLON.Vector3.Zero();
  80243. }
  80244. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80245. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80246. var c = colorVector.scale(deltaSolidAngle);
  80247. this.L00 = this.L00.add(c.scale(0.282095));
  80248. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80249. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80250. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80251. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80252. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80253. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80254. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80255. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80256. };
  80257. SphericalHarmonics.prototype.scale = function (scale) {
  80258. this.L00 = this.L00.scale(scale);
  80259. this.L1_1 = this.L1_1.scale(scale);
  80260. this.L10 = this.L10.scale(scale);
  80261. this.L11 = this.L11.scale(scale);
  80262. this.L2_2 = this.L2_2.scale(scale);
  80263. this.L2_1 = this.L2_1.scale(scale);
  80264. this.L20 = this.L20.scale(scale);
  80265. this.L21 = this.L21.scale(scale);
  80266. this.L22 = this.L22.scale(scale);
  80267. };
  80268. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80269. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80270. //
  80271. // E_lm = A_l * L_lm
  80272. //
  80273. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80274. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80275. // the scaling factors are given in equation 9.
  80276. // Constant (Band 0)
  80277. this.L00 = this.L00.scale(3.141593);
  80278. // Linear (Band 1)
  80279. this.L1_1 = this.L1_1.scale(2.094395);
  80280. this.L10 = this.L10.scale(2.094395);
  80281. this.L11 = this.L11.scale(2.094395);
  80282. // Quadratic (Band 2)
  80283. this.L2_2 = this.L2_2.scale(0.785398);
  80284. this.L2_1 = this.L2_1.scale(0.785398);
  80285. this.L20 = this.L20.scale(0.785398);
  80286. this.L21 = this.L21.scale(0.785398);
  80287. this.L22 = this.L22.scale(0.785398);
  80288. };
  80289. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80290. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80291. // L = (1/pi) * E * rho
  80292. //
  80293. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80294. this.scale(1.0 / Math.PI);
  80295. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80296. // (The pixel shader must apply albedo after texture fetches, etc).
  80297. };
  80298. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80299. var result = new SphericalHarmonics();
  80300. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80301. result.L1_1 = polynomial.y.scale(0.977204);
  80302. result.L10 = polynomial.z.scale(0.977204);
  80303. result.L11 = polynomial.x.scale(0.977204);
  80304. result.L2_2 = polynomial.xy.scale(1.16538);
  80305. result.L2_1 = polynomial.yz.scale(1.16538);
  80306. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80307. result.L21 = polynomial.zx.scale(1.16538);
  80308. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80309. result.scale(Math.PI);
  80310. return result;
  80311. };
  80312. return SphericalHarmonics;
  80313. }());
  80314. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80315. })(BABYLON || (BABYLON = {}));
  80316. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80317. var BABYLON;
  80318. (function (BABYLON) {
  80319. var FileFaceOrientation = /** @class */ (function () {
  80320. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80321. this.name = name;
  80322. this.worldAxisForNormal = worldAxisForNormal;
  80323. this.worldAxisForFileX = worldAxisForFileX;
  80324. this.worldAxisForFileY = worldAxisForFileY;
  80325. }
  80326. return FileFaceOrientation;
  80327. }());
  80328. ;
  80329. /**
  80330. * Helper class dealing with the extraction of spherical polynomial dataArray
  80331. * from a cube map.
  80332. */
  80333. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80334. function CubeMapToSphericalPolynomialTools() {
  80335. }
  80336. /**
  80337. * Converts a texture to the according Spherical Polynomial data.
  80338. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80339. *
  80340. * @param texture The texture to extract the information from.
  80341. * @return The Spherical Polynomial data.
  80342. */
  80343. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80344. if (!texture.isCube) {
  80345. // Only supports cube Textures currently.
  80346. return null;
  80347. }
  80348. var size = texture.getSize().width;
  80349. var right = texture.readPixels(0);
  80350. var left = texture.readPixels(1);
  80351. var up;
  80352. var down;
  80353. if (texture.isRenderTarget) {
  80354. up = texture.readPixels(3);
  80355. down = texture.readPixels(2);
  80356. }
  80357. else {
  80358. up = texture.readPixels(2);
  80359. down = texture.readPixels(3);
  80360. }
  80361. var front = texture.readPixels(4);
  80362. var back = texture.readPixels(5);
  80363. var gammaSpace = texture.gammaSpace;
  80364. // Always read as RGBA.
  80365. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80366. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80367. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80368. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80369. }
  80370. var cubeInfo = {
  80371. size: size,
  80372. right: right,
  80373. left: left,
  80374. up: up,
  80375. down: down,
  80376. front: front,
  80377. back: back,
  80378. format: format,
  80379. type: type,
  80380. gammaSpace: gammaSpace,
  80381. };
  80382. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80383. };
  80384. /**
  80385. * Converts a cubemap to the according Spherical Polynomial data.
  80386. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80387. *
  80388. * @param cubeInfo The Cube map to extract the information from.
  80389. * @return The Spherical Polynomial data.
  80390. */
  80391. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80392. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80393. var totalSolidAngle = 0.0;
  80394. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80395. var du = 2.0 / cubeInfo.size;
  80396. var dv = du;
  80397. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80398. var minUV = du * 0.5 - 1.0;
  80399. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80400. var fileFace = this.FileFaces[faceIndex];
  80401. var dataArray = cubeInfo[fileFace.name];
  80402. var v = minUV;
  80403. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80404. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80405. // Because SP is still linear, so summation is fine in that basis.
  80406. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80407. for (var y = 0; y < cubeInfo.size; y++) {
  80408. var u = minUV;
  80409. for (var x = 0; x < cubeInfo.size; x++) {
  80410. // World direction (not normalised)
  80411. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80412. worldDirection.normalize();
  80413. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80414. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80415. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80416. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80417. // Handle Integer types.
  80418. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80419. r /= 255;
  80420. g /= 255;
  80421. b /= 255;
  80422. }
  80423. // Handle Gamma space textures.
  80424. if (cubeInfo.gammaSpace) {
  80425. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80426. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80427. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80428. }
  80429. var color = new BABYLON.Color3(r, g, b);
  80430. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80431. totalSolidAngle += deltaSolidAngle;
  80432. u += du;
  80433. }
  80434. v += dv;
  80435. }
  80436. }
  80437. // Solid angle for entire sphere is 4*pi
  80438. var sphereSolidAngle = 4.0 * Math.PI;
  80439. // Adjust the solid angle to allow for how many faces we processed.
  80440. var facesProcessed = 6.0;
  80441. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80442. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80443. // This is needed because the numerical integration over the cube uses a
  80444. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80445. // and also to compensate for accumulative error due to float precision in the summation.
  80446. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80447. sphericalHarmonics.scale(correctionFactor);
  80448. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80449. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80450. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80451. };
  80452. CubeMapToSphericalPolynomialTools.FileFaces = [
  80453. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80454. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80455. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80456. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80457. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80458. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80459. ];
  80460. return CubeMapToSphericalPolynomialTools;
  80461. }());
  80462. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80463. })(BABYLON || (BABYLON = {}));
  80464. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80465. var BABYLON;
  80466. (function (BABYLON) {
  80467. /**
  80468. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80469. */
  80470. var PanoramaToCubeMapTools = /** @class */ (function () {
  80471. function PanoramaToCubeMapTools() {
  80472. }
  80473. /**
  80474. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80475. *
  80476. * @param float32Array The source data.
  80477. * @param inputWidth The width of the input panorama.
  80478. * @param inputhHeight The height of the input panorama.
  80479. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80480. * @return The cubemap data
  80481. */
  80482. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80483. if (!float32Array) {
  80484. throw "ConvertPanoramaToCubemap: input cannot be null";
  80485. }
  80486. if (float32Array.length != inputWidth * inputHeight * 3) {
  80487. throw "ConvertPanoramaToCubemap: input size is wrong";
  80488. }
  80489. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80490. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80491. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80492. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80493. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80494. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80495. return {
  80496. front: textureFront,
  80497. back: textureBack,
  80498. left: textureLeft,
  80499. right: textureRight,
  80500. up: textureUp,
  80501. down: textureDown,
  80502. size: size,
  80503. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80504. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80505. gammaSpace: false,
  80506. };
  80507. };
  80508. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80509. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80510. var textureArray = new Float32Array(buffer);
  80511. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80512. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80513. var dy = 1 / texSize;
  80514. var fy = 0;
  80515. for (var y = 0; y < texSize; y++) {
  80516. var xv1 = faceData[0];
  80517. var xv2 = faceData[2];
  80518. for (var x = 0; x < texSize; x++) {
  80519. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80520. v.normalize();
  80521. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80522. // 3 channels per pixels
  80523. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80524. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80525. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80526. xv1 = xv1.add(rotDX1);
  80527. xv2 = xv2.add(rotDX2);
  80528. }
  80529. fy += dy;
  80530. }
  80531. return textureArray;
  80532. };
  80533. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80534. var theta = Math.atan2(vDir.z, vDir.x);
  80535. var phi = Math.acos(vDir.y);
  80536. while (theta < -Math.PI)
  80537. theta += 2 * Math.PI;
  80538. while (theta > Math.PI)
  80539. theta -= 2 * Math.PI;
  80540. var dx = theta / Math.PI;
  80541. var dy = phi / Math.PI;
  80542. // recenter.
  80543. dx = dx * 0.5 + 0.5;
  80544. var px = Math.round(dx * inputWidth);
  80545. if (px < 0)
  80546. px = 0;
  80547. else if (px >= inputWidth)
  80548. px = inputWidth - 1;
  80549. var py = Math.round(dy * inputHeight);
  80550. if (py < 0)
  80551. py = 0;
  80552. else if (py >= inputHeight)
  80553. py = inputHeight - 1;
  80554. var inputY = (inputHeight - py - 1);
  80555. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80556. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80557. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80558. return {
  80559. r: r,
  80560. g: g,
  80561. b: b
  80562. };
  80563. };
  80564. PanoramaToCubeMapTools.FACE_FRONT = [
  80565. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80566. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80567. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80568. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80569. ];
  80570. PanoramaToCubeMapTools.FACE_BACK = [
  80571. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80572. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80573. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80574. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80575. ];
  80576. PanoramaToCubeMapTools.FACE_RIGHT = [
  80577. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80578. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80579. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80580. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80581. ];
  80582. PanoramaToCubeMapTools.FACE_LEFT = [
  80583. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80584. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80585. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80586. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80587. ];
  80588. PanoramaToCubeMapTools.FACE_DOWN = [
  80589. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80590. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80591. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80592. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80593. ];
  80594. PanoramaToCubeMapTools.FACE_UP = [
  80595. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80596. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80597. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80598. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80599. ];
  80600. return PanoramaToCubeMapTools;
  80601. }());
  80602. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80603. })(BABYLON || (BABYLON = {}));
  80604. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80605. var BABYLON;
  80606. (function (BABYLON) {
  80607. ;
  80608. /**
  80609. * This groups tools to convert HDR texture to native colors array.
  80610. */
  80611. var HDRTools = /** @class */ (function () {
  80612. function HDRTools() {
  80613. }
  80614. HDRTools.Ldexp = function (mantissa, exponent) {
  80615. if (exponent > 1023) {
  80616. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80617. }
  80618. if (exponent < -1074) {
  80619. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80620. }
  80621. return mantissa * Math.pow(2, exponent);
  80622. };
  80623. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80624. if (exponent > 0) { /*nonzero pixel*/
  80625. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80626. float32array[index + 0] = red * exponent;
  80627. float32array[index + 1] = green * exponent;
  80628. float32array[index + 2] = blue * exponent;
  80629. }
  80630. else {
  80631. float32array[index + 0] = 0;
  80632. float32array[index + 1] = 0;
  80633. float32array[index + 2] = 0;
  80634. }
  80635. };
  80636. HDRTools.readStringLine = function (uint8array, startIndex) {
  80637. var line = "";
  80638. var character = "";
  80639. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80640. character = String.fromCharCode(uint8array[i]);
  80641. if (character == "\n") {
  80642. break;
  80643. }
  80644. line += character;
  80645. }
  80646. return line;
  80647. };
  80648. /**
  80649. * Reads header information from an RGBE texture stored in a native array.
  80650. * More information on this format are available here:
  80651. * https://en.wikipedia.org/wiki/RGBE_image_format
  80652. *
  80653. * @param uint8array The binary file stored in native array.
  80654. * @return The header information.
  80655. */
  80656. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80657. var height = 0;
  80658. var width = 0;
  80659. var line = this.readStringLine(uint8array, 0);
  80660. if (line[0] != '#' || line[1] != '?') {
  80661. throw "Bad HDR Format.";
  80662. }
  80663. var endOfHeader = false;
  80664. var findFormat = false;
  80665. var lineIndex = 0;
  80666. do {
  80667. lineIndex += (line.length + 1);
  80668. line = this.readStringLine(uint8array, lineIndex);
  80669. if (line == "FORMAT=32-bit_rle_rgbe") {
  80670. findFormat = true;
  80671. }
  80672. else if (line.length == 0) {
  80673. endOfHeader = true;
  80674. }
  80675. } while (!endOfHeader);
  80676. if (!findFormat) {
  80677. throw "HDR Bad header format, unsupported FORMAT";
  80678. }
  80679. lineIndex += (line.length + 1);
  80680. line = this.readStringLine(uint8array, lineIndex);
  80681. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80682. var match = sizeRegexp.exec(line);
  80683. // TODO. Support +Y and -X if needed.
  80684. if (!match || match.length < 3) {
  80685. throw "HDR Bad header format, no size";
  80686. }
  80687. width = parseInt(match[2]);
  80688. height = parseInt(match[1]);
  80689. if (width < 8 || width > 0x7fff) {
  80690. throw "HDR Bad header format, unsupported size";
  80691. }
  80692. lineIndex += (line.length + 1);
  80693. return {
  80694. height: height,
  80695. width: width,
  80696. dataPosition: lineIndex
  80697. };
  80698. };
  80699. /**
  80700. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80701. * This RGBE texture needs to store the information as a panorama.
  80702. *
  80703. * More information on this format are available here:
  80704. * https://en.wikipedia.org/wiki/RGBE_image_format
  80705. *
  80706. * @param buffer The binary file stored in an array buffer.
  80707. * @param size The expected size of the extracted cubemap.
  80708. * @return The Cube Map information.
  80709. */
  80710. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80711. var uint8array = new Uint8Array(buffer);
  80712. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80713. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80714. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80715. return cubeMapData;
  80716. };
  80717. /**
  80718. * Returns the pixels data extracted from an RGBE texture.
  80719. * This pixels will be stored left to right up to down in the R G B order in one array.
  80720. *
  80721. * More information on this format are available here:
  80722. * https://en.wikipedia.org/wiki/RGBE_image_format
  80723. *
  80724. * @param uint8array The binary file stored in an array buffer.
  80725. * @param hdrInfo The header information of the file.
  80726. * @return The pixels data in RGB right to left up to down order.
  80727. */
  80728. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80729. // Keep for multi format supports.
  80730. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80731. };
  80732. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80733. var num_scanlines = hdrInfo.height;
  80734. var scanline_width = hdrInfo.width;
  80735. var a, b, c, d, count;
  80736. var dataIndex = hdrInfo.dataPosition;
  80737. var index = 0, endIndex = 0, i = 0;
  80738. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80739. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80740. // 3 channels of 4 bytes per pixel in float.
  80741. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80742. var resultArray = new Float32Array(resultBuffer);
  80743. // read in each successive scanline
  80744. while (num_scanlines > 0) {
  80745. a = uint8array[dataIndex++];
  80746. b = uint8array[dataIndex++];
  80747. c = uint8array[dataIndex++];
  80748. d = uint8array[dataIndex++];
  80749. if (a != 2 || b != 2 || (c & 0x80)) {
  80750. // this file is not run length encoded
  80751. throw "HDR Bad header format, not RLE";
  80752. }
  80753. if (((c << 8) | d) != scanline_width) {
  80754. throw "HDR Bad header format, wrong scan line width";
  80755. }
  80756. index = 0;
  80757. // read each of the four channels for the scanline into the buffer
  80758. for (i = 0; i < 4; i++) {
  80759. endIndex = (i + 1) * scanline_width;
  80760. while (index < endIndex) {
  80761. a = uint8array[dataIndex++];
  80762. b = uint8array[dataIndex++];
  80763. if (a > 128) {
  80764. // a run of the same value
  80765. count = a - 128;
  80766. if ((count == 0) || (count > endIndex - index)) {
  80767. throw "HDR Bad Format, bad scanline data (run)";
  80768. }
  80769. while (count-- > 0) {
  80770. scanLineArray[index++] = b;
  80771. }
  80772. }
  80773. else {
  80774. // a non-run
  80775. count = a;
  80776. if ((count == 0) || (count > endIndex - index)) {
  80777. throw "HDR Bad Format, bad scanline data (non-run)";
  80778. }
  80779. scanLineArray[index++] = b;
  80780. if (--count > 0) {
  80781. for (var j = 0; j < count; j++) {
  80782. scanLineArray[index++] = uint8array[dataIndex++];
  80783. }
  80784. }
  80785. }
  80786. }
  80787. }
  80788. // now convert data from buffer into floats
  80789. for (i = 0; i < scanline_width; i++) {
  80790. a = scanLineArray[i];
  80791. b = scanLineArray[i + scanline_width];
  80792. c = scanLineArray[i + 2 * scanline_width];
  80793. d = scanLineArray[i + 3 * scanline_width];
  80794. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80795. }
  80796. num_scanlines--;
  80797. }
  80798. return resultArray;
  80799. };
  80800. return HDRTools;
  80801. }());
  80802. BABYLON.HDRTools = HDRTools;
  80803. })(BABYLON || (BABYLON = {}));
  80804. //# sourceMappingURL=babylon.hdr.js.map
  80805. var BABYLON;
  80806. (function (BABYLON) {
  80807. /**
  80808. * This represents a texture coming from an HDR input.
  80809. *
  80810. * The only supported format is currently panorama picture stored in RGBE format.
  80811. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80812. */
  80813. var HDRCubeTexture = /** @class */ (function (_super) {
  80814. __extends(HDRCubeTexture, _super);
  80815. /**
  80816. * Instantiates an HDRTexture from the following parameters.
  80817. *
  80818. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80819. * @param scene The scene the texture will be used in
  80820. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80821. * @param noMipmap Forces to not generate the mipmap if true
  80822. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80823. * @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)
  80824. * @param reserved Reserved flag for internal use.
  80825. */
  80826. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80827. if (noMipmap === void 0) { noMipmap = false; }
  80828. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80829. if (gammaSpace === void 0) { gammaSpace = false; }
  80830. if (reserved === void 0) { reserved = false; }
  80831. if (onLoad === void 0) { onLoad = null; }
  80832. if (onError === void 0) { onError = null; }
  80833. var _this = _super.call(this, scene) || this;
  80834. _this._generateHarmonics = true;
  80835. _this._onLoad = null;
  80836. _this._onError = null;
  80837. /**
  80838. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80839. */
  80840. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80841. _this._isBlocking = true;
  80842. _this._rotationY = 0;
  80843. /**
  80844. * Gets or sets the center of the bounding box associated with the cube texture
  80845. * It must define where the camera used to render the texture was set
  80846. */
  80847. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80848. if (!url) {
  80849. return _this;
  80850. }
  80851. _this.name = url;
  80852. _this.url = url;
  80853. _this.hasAlpha = false;
  80854. _this.isCube = true;
  80855. _this._textureMatrix = BABYLON.Matrix.Identity();
  80856. _this._onLoad = onLoad;
  80857. _this._onError = onError;
  80858. _this.gammaSpace = gammaSpace;
  80859. _this._noMipmap = noMipmap;
  80860. _this._size = size;
  80861. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80862. if (!_this._texture) {
  80863. if (!scene.useDelayedTextureLoading) {
  80864. _this.loadTexture();
  80865. }
  80866. else {
  80867. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80868. }
  80869. }
  80870. return _this;
  80871. }
  80872. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80873. /**
  80874. * Gets wether or not the texture is blocking during loading.
  80875. */
  80876. get: function () {
  80877. return this._isBlocking;
  80878. },
  80879. /**
  80880. * Sets wether or not the texture is blocking during loading.
  80881. */
  80882. set: function (value) {
  80883. this._isBlocking = value;
  80884. },
  80885. enumerable: true,
  80886. configurable: true
  80887. });
  80888. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80889. /**
  80890. * Gets texture matrix rotation angle around Y axis radians.
  80891. */
  80892. get: function () {
  80893. return this._rotationY;
  80894. },
  80895. /**
  80896. * Sets texture matrix rotation angle around Y axis in radians.
  80897. */
  80898. set: function (value) {
  80899. this._rotationY = value;
  80900. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80901. },
  80902. enumerable: true,
  80903. configurable: true
  80904. });
  80905. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80906. get: function () {
  80907. return this._boundingBoxSize;
  80908. },
  80909. /**
  80910. * Gets or sets the size of the bounding box associated with the cube texture
  80911. * When defined, the cubemap will switch to local mode
  80912. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80913. * @example https://www.babylonjs-playground.com/#RNASML
  80914. */
  80915. set: function (value) {
  80916. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80917. return;
  80918. }
  80919. this._boundingBoxSize = value;
  80920. var scene = this.getScene();
  80921. if (scene) {
  80922. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80923. }
  80924. },
  80925. enumerable: true,
  80926. configurable: true
  80927. });
  80928. /**
  80929. * Occurs when the file is raw .hdr file.
  80930. */
  80931. HDRCubeTexture.prototype.loadTexture = function () {
  80932. var _this = this;
  80933. var callback = function (buffer) {
  80934. var scene = _this.getScene();
  80935. if (!scene) {
  80936. return null;
  80937. }
  80938. // Extract the raw linear data.
  80939. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80940. // Generate harmonics if needed.
  80941. if (_this._generateHarmonics) {
  80942. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80943. _this.sphericalPolynomial = sphericalPolynomial;
  80944. }
  80945. var results = [];
  80946. var byteArray = null;
  80947. // Push each faces.
  80948. for (var j = 0; j < 6; j++) {
  80949. // Create uintarray fallback.
  80950. if (!scene.getEngine().getCaps().textureFloat) {
  80951. // 3 channels of 1 bytes per pixel in bytes.
  80952. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80953. byteArray = new Uint8Array(byteBuffer);
  80954. }
  80955. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80956. // If special cases.
  80957. if (_this.gammaSpace || byteArray) {
  80958. for (var i = 0; i < _this._size * _this._size; i++) {
  80959. // Put in gamma space if requested.
  80960. if (_this.gammaSpace) {
  80961. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80962. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80963. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80964. }
  80965. // Convert to int texture for fallback.
  80966. if (byteArray) {
  80967. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80968. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80969. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80970. // May use luminance instead if the result is not accurate.
  80971. var max = Math.max(Math.max(r, g), b);
  80972. if (max > 255) {
  80973. var scale = 255 / max;
  80974. r *= scale;
  80975. g *= scale;
  80976. b *= scale;
  80977. }
  80978. byteArray[(i * 3) + 0] = r;
  80979. byteArray[(i * 3) + 1] = g;
  80980. byteArray[(i * 3) + 2] = b;
  80981. }
  80982. }
  80983. }
  80984. if (byteArray) {
  80985. results.push(byteArray);
  80986. }
  80987. else {
  80988. results.push(dataFace);
  80989. }
  80990. }
  80991. return results;
  80992. };
  80993. var scene = this.getScene();
  80994. if (scene) {
  80995. 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);
  80996. }
  80997. };
  80998. HDRCubeTexture.prototype.clone = function () {
  80999. var scene = this.getScene();
  81000. if (!scene) {
  81001. return this;
  81002. }
  81003. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81004. // Base texture
  81005. newTexture.level = this.level;
  81006. newTexture.wrapU = this.wrapU;
  81007. newTexture.wrapV = this.wrapV;
  81008. newTexture.coordinatesIndex = this.coordinatesIndex;
  81009. newTexture.coordinatesMode = this.coordinatesMode;
  81010. return newTexture;
  81011. };
  81012. // Methods
  81013. HDRCubeTexture.prototype.delayLoad = function () {
  81014. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81015. return;
  81016. }
  81017. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81018. this._texture = this._getFromCache(this.url, this._noMipmap);
  81019. if (!this._texture) {
  81020. this.loadTexture();
  81021. }
  81022. };
  81023. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81024. return this._textureMatrix;
  81025. };
  81026. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81027. this._textureMatrix = value;
  81028. };
  81029. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81030. var texture = null;
  81031. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81032. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81033. texture.name = parsedTexture.name;
  81034. texture.hasAlpha = parsedTexture.hasAlpha;
  81035. texture.level = parsedTexture.level;
  81036. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81037. texture.isBlocking = parsedTexture.isBlocking;
  81038. }
  81039. if (texture) {
  81040. if (parsedTexture.boundingBoxPosition) {
  81041. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81042. }
  81043. if (parsedTexture.boundingBoxSize) {
  81044. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81045. }
  81046. if (parsedTexture.rotationY) {
  81047. texture.rotationY = parsedTexture.rotationY;
  81048. }
  81049. }
  81050. return texture;
  81051. };
  81052. HDRCubeTexture.prototype.serialize = function () {
  81053. if (!this.name) {
  81054. return null;
  81055. }
  81056. var serializationObject = {};
  81057. serializationObject.name = this.name;
  81058. serializationObject.hasAlpha = this.hasAlpha;
  81059. serializationObject.isCube = true;
  81060. serializationObject.level = this.level;
  81061. serializationObject.size = this._size;
  81062. serializationObject.coordinatesMode = this.coordinatesMode;
  81063. serializationObject.useInGammaSpace = this.gammaSpace;
  81064. serializationObject.generateHarmonics = this._generateHarmonics;
  81065. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81066. serializationObject.noMipmap = this._noMipmap;
  81067. serializationObject.isBlocking = this._isBlocking;
  81068. serializationObject.rotationY = this._rotationY;
  81069. return serializationObject;
  81070. };
  81071. HDRCubeTexture._facesMapping = [
  81072. "right",
  81073. "left",
  81074. "up",
  81075. "down",
  81076. "front",
  81077. "back"
  81078. ];
  81079. return HDRCubeTexture;
  81080. }(BABYLON.BaseTexture));
  81081. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81082. })(BABYLON || (BABYLON = {}));
  81083. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81084. var BABYLON;
  81085. (function (BABYLON) {
  81086. var IndexedVector2 = /** @class */ (function (_super) {
  81087. __extends(IndexedVector2, _super);
  81088. function IndexedVector2(original, index) {
  81089. var _this = _super.call(this, original.x, original.y) || this;
  81090. _this.index = index;
  81091. return _this;
  81092. }
  81093. return IndexedVector2;
  81094. }(BABYLON.Vector2));
  81095. var PolygonPoints = /** @class */ (function () {
  81096. function PolygonPoints() {
  81097. this.elements = new Array();
  81098. }
  81099. PolygonPoints.prototype.add = function (originalPoints) {
  81100. var _this = this;
  81101. var result = new Array();
  81102. originalPoints.forEach(function (point) {
  81103. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81104. var newPoint = new IndexedVector2(point, _this.elements.length);
  81105. result.push(newPoint);
  81106. _this.elements.push(newPoint);
  81107. }
  81108. });
  81109. return result;
  81110. };
  81111. PolygonPoints.prototype.computeBounds = function () {
  81112. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81113. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81114. this.elements.forEach(function (point) {
  81115. // x
  81116. if (point.x < lmin.x) {
  81117. lmin.x = point.x;
  81118. }
  81119. else if (point.x > lmax.x) {
  81120. lmax.x = point.x;
  81121. }
  81122. // y
  81123. if (point.y < lmin.y) {
  81124. lmin.y = point.y;
  81125. }
  81126. else if (point.y > lmax.y) {
  81127. lmax.y = point.y;
  81128. }
  81129. });
  81130. return {
  81131. min: lmin,
  81132. max: lmax,
  81133. width: lmax.x - lmin.x,
  81134. height: lmax.y - lmin.y
  81135. };
  81136. };
  81137. return PolygonPoints;
  81138. }());
  81139. var Polygon = /** @class */ (function () {
  81140. function Polygon() {
  81141. }
  81142. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81143. return [
  81144. new BABYLON.Vector2(xmin, ymin),
  81145. new BABYLON.Vector2(xmax, ymin),
  81146. new BABYLON.Vector2(xmax, ymax),
  81147. new BABYLON.Vector2(xmin, ymax)
  81148. ];
  81149. };
  81150. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81151. if (cx === void 0) { cx = 0; }
  81152. if (cy === void 0) { cy = 0; }
  81153. if (numberOfSides === void 0) { numberOfSides = 32; }
  81154. var result = new Array();
  81155. var angle = 0;
  81156. var increment = (Math.PI * 2) / numberOfSides;
  81157. for (var i = 0; i < numberOfSides; i++) {
  81158. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81159. angle -= increment;
  81160. }
  81161. return result;
  81162. };
  81163. Polygon.Parse = function (input) {
  81164. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81165. var i, result = [];
  81166. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81167. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81168. }
  81169. return result;
  81170. };
  81171. Polygon.StartingAt = function (x, y) {
  81172. return BABYLON.Path2.StartingAt(x, y);
  81173. };
  81174. return Polygon;
  81175. }());
  81176. BABYLON.Polygon = Polygon;
  81177. var PolygonMeshBuilder = /** @class */ (function () {
  81178. function PolygonMeshBuilder(name, contours, scene) {
  81179. this._points = new PolygonPoints();
  81180. this._outlinepoints = new PolygonPoints();
  81181. this._holes = new Array();
  81182. this._epoints = new Array();
  81183. this._eholes = new Array();
  81184. this._name = name;
  81185. this._scene = scene;
  81186. var points;
  81187. if (contours instanceof BABYLON.Path2) {
  81188. points = contours.getPoints();
  81189. }
  81190. else {
  81191. points = contours;
  81192. }
  81193. this._addToepoint(points);
  81194. this._points.add(points);
  81195. this._outlinepoints.add(points);
  81196. if (typeof earcut === 'undefined') {
  81197. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81198. }
  81199. }
  81200. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81201. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81202. var p = points_1[_i];
  81203. this._epoints.push(p.x, p.y);
  81204. }
  81205. };
  81206. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81207. this._points.add(hole);
  81208. var holepoints = new PolygonPoints();
  81209. holepoints.add(hole);
  81210. this._holes.push(holepoints);
  81211. this._eholes.push(this._epoints.length / 2);
  81212. this._addToepoint(hole);
  81213. return this;
  81214. };
  81215. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81216. var _this = this;
  81217. if (updatable === void 0) { updatable = false; }
  81218. if (depth === void 0) { depth = 0; }
  81219. var result = new BABYLON.Mesh(this._name, this._scene);
  81220. var normals = new Array();
  81221. var positions = new Array();
  81222. var uvs = new Array();
  81223. var bounds = this._points.computeBounds();
  81224. this._points.elements.forEach(function (p) {
  81225. normals.push(0, 1.0, 0);
  81226. positions.push(p.x, 0, p.y);
  81227. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81228. });
  81229. var indices = new Array();
  81230. var res = earcut(this._epoints, this._eholes, 2);
  81231. for (var i = 0; i < res.length; i++) {
  81232. indices.push(res[i]);
  81233. }
  81234. if (depth > 0) {
  81235. var positionscount = (positions.length / 3); //get the current pointcount
  81236. this._points.elements.forEach(function (p) {
  81237. normals.push(0, -1.0, 0);
  81238. positions.push(p.x, -depth, p.y);
  81239. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81240. });
  81241. var totalCount = indices.length;
  81242. for (var i = 0; i < totalCount; i += 3) {
  81243. var i0 = indices[i + 0];
  81244. var i1 = indices[i + 1];
  81245. var i2 = indices[i + 2];
  81246. indices.push(i2 + positionscount);
  81247. indices.push(i1 + positionscount);
  81248. indices.push(i0 + positionscount);
  81249. }
  81250. //Add the sides
  81251. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81252. this._holes.forEach(function (hole) {
  81253. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81254. });
  81255. }
  81256. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81257. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81258. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81259. result.setIndices(indices);
  81260. return result;
  81261. };
  81262. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81263. var StartIndex = positions.length / 3;
  81264. var ulength = 0;
  81265. for (var i = 0; i < points.elements.length; i++) {
  81266. var p = points.elements[i];
  81267. var p1;
  81268. if ((i + 1) > points.elements.length - 1) {
  81269. p1 = points.elements[0];
  81270. }
  81271. else {
  81272. p1 = points.elements[i + 1];
  81273. }
  81274. positions.push(p.x, 0, p.y);
  81275. positions.push(p.x, -depth, p.y);
  81276. positions.push(p1.x, 0, p1.y);
  81277. positions.push(p1.x, -depth, p1.y);
  81278. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81279. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81280. var v3 = v2.subtract(v1);
  81281. var v4 = new BABYLON.Vector3(0, 1, 0);
  81282. var vn = BABYLON.Vector3.Cross(v3, v4);
  81283. vn = vn.normalize();
  81284. uvs.push(ulength / bounds.width, 0);
  81285. uvs.push(ulength / bounds.width, 1);
  81286. ulength += v3.length();
  81287. uvs.push((ulength / bounds.width), 0);
  81288. uvs.push((ulength / bounds.width), 1);
  81289. if (!flip) {
  81290. normals.push(-vn.x, -vn.y, -vn.z);
  81291. normals.push(-vn.x, -vn.y, -vn.z);
  81292. normals.push(-vn.x, -vn.y, -vn.z);
  81293. normals.push(-vn.x, -vn.y, -vn.z);
  81294. indices.push(StartIndex);
  81295. indices.push(StartIndex + 1);
  81296. indices.push(StartIndex + 2);
  81297. indices.push(StartIndex + 1);
  81298. indices.push(StartIndex + 3);
  81299. indices.push(StartIndex + 2);
  81300. }
  81301. else {
  81302. normals.push(vn.x, vn.y, vn.z);
  81303. normals.push(vn.x, vn.y, vn.z);
  81304. normals.push(vn.x, vn.y, vn.z);
  81305. normals.push(vn.x, vn.y, vn.z);
  81306. indices.push(StartIndex);
  81307. indices.push(StartIndex + 2);
  81308. indices.push(StartIndex + 1);
  81309. indices.push(StartIndex + 1);
  81310. indices.push(StartIndex + 2);
  81311. indices.push(StartIndex + 3);
  81312. }
  81313. StartIndex += 4;
  81314. }
  81315. ;
  81316. };
  81317. return PolygonMeshBuilder;
  81318. }());
  81319. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81320. })(BABYLON || (BABYLON = {}));
  81321. //# sourceMappingURL=babylon.polygonMesh.js.map
  81322. var BABYLON;
  81323. (function (BABYLON) {
  81324. // Unique ID when we import meshes from Babylon to CSG
  81325. var currentCSGMeshId = 0;
  81326. // # class Vertex
  81327. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81328. // one to provide additional features like texture coordinates and vertex
  81329. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81330. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81331. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81332. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81333. // is not used anywhere else.
  81334. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81335. var Vertex = /** @class */ (function () {
  81336. function Vertex(pos, normal, uv) {
  81337. this.pos = pos;
  81338. this.normal = normal;
  81339. this.uv = uv;
  81340. }
  81341. Vertex.prototype.clone = function () {
  81342. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81343. };
  81344. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81345. // orientation of a polygon is flipped.
  81346. Vertex.prototype.flip = function () {
  81347. this.normal = this.normal.scale(-1);
  81348. };
  81349. // Create a new vertex between this vertex and `other` by linearly
  81350. // interpolating all properties using a parameter of `t`. Subclasses should
  81351. // override this to interpolate additional properties.
  81352. Vertex.prototype.interpolate = function (other, t) {
  81353. 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));
  81354. };
  81355. return Vertex;
  81356. }());
  81357. // # class Plane
  81358. // Represents a plane in 3D space.
  81359. var Plane = /** @class */ (function () {
  81360. function Plane(normal, w) {
  81361. this.normal = normal;
  81362. this.w = w;
  81363. }
  81364. Plane.FromPoints = function (a, b, c) {
  81365. var v0 = c.subtract(a);
  81366. var v1 = b.subtract(a);
  81367. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81368. return null;
  81369. }
  81370. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81371. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81372. };
  81373. Plane.prototype.clone = function () {
  81374. return new Plane(this.normal.clone(), this.w);
  81375. };
  81376. Plane.prototype.flip = function () {
  81377. this.normal.scaleInPlace(-1);
  81378. this.w = -this.w;
  81379. };
  81380. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81381. // fragments in the appropriate lists. Coplanar polygons go into either
  81382. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81383. // respect to this plane. Polygons in front or in back of this plane go into
  81384. // either `front` or `back`.
  81385. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81386. var COPLANAR = 0;
  81387. var FRONT = 1;
  81388. var BACK = 2;
  81389. var SPANNING = 3;
  81390. // Classify each point as well as the entire polygon into one of the above
  81391. // four classes.
  81392. var polygonType = 0;
  81393. var types = [];
  81394. var i;
  81395. var t;
  81396. for (i = 0; i < polygon.vertices.length; i++) {
  81397. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81398. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81399. polygonType |= type;
  81400. types.push(type);
  81401. }
  81402. // Put the polygon in the correct list, splitting it when necessary.
  81403. switch (polygonType) {
  81404. case COPLANAR:
  81405. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81406. break;
  81407. case FRONT:
  81408. front.push(polygon);
  81409. break;
  81410. case BACK:
  81411. back.push(polygon);
  81412. break;
  81413. case SPANNING:
  81414. var f = [], b = [];
  81415. for (i = 0; i < polygon.vertices.length; i++) {
  81416. var j = (i + 1) % polygon.vertices.length;
  81417. var ti = types[i], tj = types[j];
  81418. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81419. if (ti !== BACK)
  81420. f.push(vi);
  81421. if (ti !== FRONT)
  81422. b.push(ti !== BACK ? vi.clone() : vi);
  81423. if ((ti | tj) === SPANNING) {
  81424. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81425. var v = vi.interpolate(vj, t);
  81426. f.push(v);
  81427. b.push(v.clone());
  81428. }
  81429. }
  81430. var poly;
  81431. if (f.length >= 3) {
  81432. poly = new Polygon(f, polygon.shared);
  81433. if (poly.plane)
  81434. front.push(poly);
  81435. }
  81436. if (b.length >= 3) {
  81437. poly = new Polygon(b, polygon.shared);
  81438. if (poly.plane)
  81439. back.push(poly);
  81440. }
  81441. break;
  81442. }
  81443. };
  81444. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81445. // point is on the plane.
  81446. Plane.EPSILON = 1e-5;
  81447. return Plane;
  81448. }());
  81449. // # class Polygon
  81450. // Represents a convex polygon. The vertices used to initialize a polygon must
  81451. // be coplanar and form a convex loop.
  81452. //
  81453. // Each convex polygon has a `shared` property, which is shared between all
  81454. // polygons that are clones of each other or were split from the same polygon.
  81455. // This can be used to define per-polygon properties (such as surface color).
  81456. var Polygon = /** @class */ (function () {
  81457. function Polygon(vertices, shared) {
  81458. this.vertices = vertices;
  81459. this.shared = shared;
  81460. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81461. }
  81462. Polygon.prototype.clone = function () {
  81463. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81464. return new Polygon(vertices, this.shared);
  81465. };
  81466. Polygon.prototype.flip = function () {
  81467. this.vertices.reverse().map(function (v) { v.flip(); });
  81468. this.plane.flip();
  81469. };
  81470. return Polygon;
  81471. }());
  81472. // # class Node
  81473. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81474. // by picking a polygon to split along. That polygon (and all other coplanar
  81475. // polygons) are added directly to that node and the other polygons are added to
  81476. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81477. // no distinction between internal and leaf nodes.
  81478. var Node = /** @class */ (function () {
  81479. function Node(polygons) {
  81480. this.plane = null;
  81481. this.front = null;
  81482. this.back = null;
  81483. this.polygons = new Array();
  81484. if (polygons) {
  81485. this.build(polygons);
  81486. }
  81487. }
  81488. Node.prototype.clone = function () {
  81489. var node = new Node();
  81490. node.plane = this.plane && this.plane.clone();
  81491. node.front = this.front && this.front.clone();
  81492. node.back = this.back && this.back.clone();
  81493. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81494. return node;
  81495. };
  81496. // Convert solid space to empty space and empty space to solid space.
  81497. Node.prototype.invert = function () {
  81498. for (var i = 0; i < this.polygons.length; i++) {
  81499. this.polygons[i].flip();
  81500. }
  81501. if (this.plane) {
  81502. this.plane.flip();
  81503. }
  81504. if (this.front) {
  81505. this.front.invert();
  81506. }
  81507. if (this.back) {
  81508. this.back.invert();
  81509. }
  81510. var temp = this.front;
  81511. this.front = this.back;
  81512. this.back = temp;
  81513. };
  81514. // Recursively remove all polygons in `polygons` that are inside this BSP
  81515. // tree.
  81516. Node.prototype.clipPolygons = function (polygons) {
  81517. if (!this.plane)
  81518. return polygons.slice();
  81519. var front = new Array(), back = new Array();
  81520. for (var i = 0; i < polygons.length; i++) {
  81521. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81522. }
  81523. if (this.front) {
  81524. front = this.front.clipPolygons(front);
  81525. }
  81526. if (this.back) {
  81527. back = this.back.clipPolygons(back);
  81528. }
  81529. else {
  81530. back = [];
  81531. }
  81532. return front.concat(back);
  81533. };
  81534. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81535. // `bsp`.
  81536. Node.prototype.clipTo = function (bsp) {
  81537. this.polygons = bsp.clipPolygons(this.polygons);
  81538. if (this.front)
  81539. this.front.clipTo(bsp);
  81540. if (this.back)
  81541. this.back.clipTo(bsp);
  81542. };
  81543. // Return a list of all polygons in this BSP tree.
  81544. Node.prototype.allPolygons = function () {
  81545. var polygons = this.polygons.slice();
  81546. if (this.front)
  81547. polygons = polygons.concat(this.front.allPolygons());
  81548. if (this.back)
  81549. polygons = polygons.concat(this.back.allPolygons());
  81550. return polygons;
  81551. };
  81552. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81553. // new polygons are filtered down to the bottom of the tree and become new
  81554. // nodes there. Each set of polygons is partitioned using the first polygon
  81555. // (no heuristic is used to pick a good split).
  81556. Node.prototype.build = function (polygons) {
  81557. if (!polygons.length)
  81558. return;
  81559. if (!this.plane)
  81560. this.plane = polygons[0].plane.clone();
  81561. var front = new Array(), back = new Array();
  81562. for (var i = 0; i < polygons.length; i++) {
  81563. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81564. }
  81565. if (front.length) {
  81566. if (!this.front)
  81567. this.front = new Node();
  81568. this.front.build(front);
  81569. }
  81570. if (back.length) {
  81571. if (!this.back)
  81572. this.back = new Node();
  81573. this.back.build(back);
  81574. }
  81575. };
  81576. return Node;
  81577. }());
  81578. var CSG = /** @class */ (function () {
  81579. function CSG() {
  81580. this.polygons = new Array();
  81581. }
  81582. // Convert BABYLON.Mesh to BABYLON.CSG
  81583. CSG.FromMesh = function (mesh) {
  81584. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81585. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81586. if (mesh instanceof BABYLON.Mesh) {
  81587. mesh.computeWorldMatrix(true);
  81588. matrix = mesh.getWorldMatrix();
  81589. meshPosition = mesh.position.clone();
  81590. meshRotation = mesh.rotation.clone();
  81591. if (mesh.rotationQuaternion) {
  81592. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81593. }
  81594. meshScaling = mesh.scaling.clone();
  81595. }
  81596. else {
  81597. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81598. }
  81599. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81600. var subMeshes = mesh.subMeshes;
  81601. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81602. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81603. vertices = [];
  81604. for (var j = 0; j < 3; j++) {
  81605. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81606. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81607. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81608. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81609. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81610. vertex = new Vertex(position, normal, uv);
  81611. vertices.push(vertex);
  81612. }
  81613. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81614. // To handle the case of degenerated triangle
  81615. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81616. if (polygon.plane)
  81617. polygons.push(polygon);
  81618. }
  81619. }
  81620. var csg = CSG.FromPolygons(polygons);
  81621. csg.matrix = matrix;
  81622. csg.position = meshPosition;
  81623. csg.rotation = meshRotation;
  81624. csg.scaling = meshScaling;
  81625. csg.rotationQuaternion = meshRotationQuaternion;
  81626. currentCSGMeshId++;
  81627. return csg;
  81628. };
  81629. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81630. CSG.FromPolygons = function (polygons) {
  81631. var csg = new CSG();
  81632. csg.polygons = polygons;
  81633. return csg;
  81634. };
  81635. CSG.prototype.clone = function () {
  81636. var csg = new CSG();
  81637. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81638. csg.copyTransformAttributes(this);
  81639. return csg;
  81640. };
  81641. CSG.prototype.union = function (csg) {
  81642. var a = new Node(this.clone().polygons);
  81643. var b = new Node(csg.clone().polygons);
  81644. a.clipTo(b);
  81645. b.clipTo(a);
  81646. b.invert();
  81647. b.clipTo(a);
  81648. b.invert();
  81649. a.build(b.allPolygons());
  81650. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81651. };
  81652. CSG.prototype.unionInPlace = function (csg) {
  81653. var a = new Node(this.polygons);
  81654. var b = new Node(csg.polygons);
  81655. a.clipTo(b);
  81656. b.clipTo(a);
  81657. b.invert();
  81658. b.clipTo(a);
  81659. b.invert();
  81660. a.build(b.allPolygons());
  81661. this.polygons = a.allPolygons();
  81662. };
  81663. CSG.prototype.subtract = function (csg) {
  81664. var a = new Node(this.clone().polygons);
  81665. var b = new Node(csg.clone().polygons);
  81666. a.invert();
  81667. a.clipTo(b);
  81668. b.clipTo(a);
  81669. b.invert();
  81670. b.clipTo(a);
  81671. b.invert();
  81672. a.build(b.allPolygons());
  81673. a.invert();
  81674. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81675. };
  81676. CSG.prototype.subtractInPlace = function (csg) {
  81677. var a = new Node(this.polygons);
  81678. var b = new Node(csg.polygons);
  81679. a.invert();
  81680. a.clipTo(b);
  81681. b.clipTo(a);
  81682. b.invert();
  81683. b.clipTo(a);
  81684. b.invert();
  81685. a.build(b.allPolygons());
  81686. a.invert();
  81687. this.polygons = a.allPolygons();
  81688. };
  81689. CSG.prototype.intersect = function (csg) {
  81690. var a = new Node(this.clone().polygons);
  81691. var b = new Node(csg.clone().polygons);
  81692. a.invert();
  81693. b.clipTo(a);
  81694. b.invert();
  81695. a.clipTo(b);
  81696. b.clipTo(a);
  81697. a.build(b.allPolygons());
  81698. a.invert();
  81699. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81700. };
  81701. CSG.prototype.intersectInPlace = function (csg) {
  81702. var a = new Node(this.polygons);
  81703. var b = new Node(csg.polygons);
  81704. a.invert();
  81705. b.clipTo(a);
  81706. b.invert();
  81707. a.clipTo(b);
  81708. b.clipTo(a);
  81709. a.build(b.allPolygons());
  81710. a.invert();
  81711. this.polygons = a.allPolygons();
  81712. };
  81713. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81714. // not modified.
  81715. CSG.prototype.inverse = function () {
  81716. var csg = this.clone();
  81717. csg.inverseInPlace();
  81718. return csg;
  81719. };
  81720. CSG.prototype.inverseInPlace = function () {
  81721. this.polygons.map(function (p) { p.flip(); });
  81722. };
  81723. // This is used to keep meshes transformations so they can be restored
  81724. // when we build back a Babylon Mesh
  81725. // NB : All CSG operations are performed in world coordinates
  81726. CSG.prototype.copyTransformAttributes = function (csg) {
  81727. this.matrix = csg.matrix;
  81728. this.position = csg.position;
  81729. this.rotation = csg.rotation;
  81730. this.scaling = csg.scaling;
  81731. this.rotationQuaternion = csg.rotationQuaternion;
  81732. return this;
  81733. };
  81734. // Build Raw mesh from CSG
  81735. // Coordinates here are in world space
  81736. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81737. var matrix = this.matrix.clone();
  81738. matrix.invert();
  81739. 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;
  81740. if (keepSubMeshes) {
  81741. // Sort Polygons, since subMeshes are indices range
  81742. polygons.sort(function (a, b) {
  81743. if (a.shared.meshId === b.shared.meshId) {
  81744. return a.shared.subMeshId - b.shared.subMeshId;
  81745. }
  81746. else {
  81747. return a.shared.meshId - b.shared.meshId;
  81748. }
  81749. });
  81750. }
  81751. for (var i = 0, il = polygons.length; i < il; i++) {
  81752. polygon = polygons[i];
  81753. // Building SubMeshes
  81754. if (!subMesh_dict[polygon.shared.meshId]) {
  81755. subMesh_dict[polygon.shared.meshId] = {};
  81756. }
  81757. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81758. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81759. indexStart: +Infinity,
  81760. indexEnd: -Infinity,
  81761. materialIndex: polygon.shared.materialIndex
  81762. };
  81763. }
  81764. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81765. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81766. polygonIndices[0] = 0;
  81767. polygonIndices[1] = j - 1;
  81768. polygonIndices[2] = j;
  81769. for (var k = 0; k < 3; k++) {
  81770. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81771. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81772. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81773. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81774. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81775. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81776. // Check if 2 points can be merged
  81777. if (!(typeof vertex_idx !== 'undefined' &&
  81778. normals[vertex_idx * 3] === localNormal.x &&
  81779. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81780. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81781. uvs[vertex_idx * 2] === uv.x &&
  81782. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81783. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81784. uvs.push(uv.x, uv.y);
  81785. normals.push(normal.x, normal.y, normal.z);
  81786. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81787. }
  81788. indices.push(vertex_idx);
  81789. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81790. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81791. currentIndex++;
  81792. }
  81793. }
  81794. }
  81795. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81796. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81797. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81798. mesh.setIndices(indices, null);
  81799. if (keepSubMeshes) {
  81800. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81801. var materialIndexOffset = 0, materialMaxIndex;
  81802. mesh.subMeshes = new Array();
  81803. for (var m in subMesh_dict) {
  81804. materialMaxIndex = -1;
  81805. for (var sm in subMesh_dict[m]) {
  81806. subMesh_obj = subMesh_dict[m][sm];
  81807. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81808. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81809. }
  81810. materialIndexOffset += ++materialMaxIndex;
  81811. }
  81812. }
  81813. return mesh;
  81814. };
  81815. // Build Mesh from CSG taking material and transforms into account
  81816. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81817. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81818. mesh.material = material;
  81819. mesh.position.copyFrom(this.position);
  81820. mesh.rotation.copyFrom(this.rotation);
  81821. if (this.rotationQuaternion) {
  81822. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81823. }
  81824. mesh.scaling.copyFrom(this.scaling);
  81825. mesh.computeWorldMatrix(true);
  81826. return mesh;
  81827. };
  81828. return CSG;
  81829. }());
  81830. BABYLON.CSG = CSG;
  81831. })(BABYLON || (BABYLON = {}));
  81832. //# sourceMappingURL=babylon.csg.js.map
  81833. var BABYLON;
  81834. (function (BABYLON) {
  81835. var LensFlare = /** @class */ (function () {
  81836. function LensFlare(size, position, color, imgUrl, system) {
  81837. this.size = size;
  81838. this.position = position;
  81839. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81840. this.color = color || new BABYLON.Color3(1, 1, 1);
  81841. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81842. this._system = system;
  81843. system.lensFlares.push(this);
  81844. }
  81845. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81846. return new LensFlare(size, position, color, imgUrl, system);
  81847. };
  81848. LensFlare.prototype.dispose = function () {
  81849. if (this.texture) {
  81850. this.texture.dispose();
  81851. }
  81852. // Remove from scene
  81853. var index = this._system.lensFlares.indexOf(this);
  81854. this._system.lensFlares.splice(index, 1);
  81855. };
  81856. ;
  81857. return LensFlare;
  81858. }());
  81859. BABYLON.LensFlare = LensFlare;
  81860. })(BABYLON || (BABYLON = {}));
  81861. //# sourceMappingURL=babylon.lensFlare.js.map
  81862. var BABYLON;
  81863. (function (BABYLON) {
  81864. var LensFlareSystem = /** @class */ (function () {
  81865. function LensFlareSystem(name, emitter, scene) {
  81866. this.name = name;
  81867. this.lensFlares = new Array();
  81868. this.borderLimit = 300;
  81869. this.viewportBorder = 0;
  81870. this.layerMask = 0x0FFFFFFF;
  81871. this._vertexBuffers = {};
  81872. this._isEnabled = true;
  81873. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81874. this._emitter = emitter;
  81875. this.id = name;
  81876. scene.lensFlareSystems.push(this);
  81877. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81878. var engine = scene.getEngine();
  81879. // VBO
  81880. var vertices = [];
  81881. vertices.push(1, 1);
  81882. vertices.push(-1, 1);
  81883. vertices.push(-1, -1);
  81884. vertices.push(1, -1);
  81885. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81886. // Indices
  81887. var indices = [];
  81888. indices.push(0);
  81889. indices.push(1);
  81890. indices.push(2);
  81891. indices.push(0);
  81892. indices.push(2);
  81893. indices.push(3);
  81894. this._indexBuffer = engine.createIndexBuffer(indices);
  81895. // Effects
  81896. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81897. }
  81898. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81899. get: function () {
  81900. return this._isEnabled;
  81901. },
  81902. set: function (value) {
  81903. this._isEnabled = value;
  81904. },
  81905. enumerable: true,
  81906. configurable: true
  81907. });
  81908. LensFlareSystem.prototype.getScene = function () {
  81909. return this._scene;
  81910. };
  81911. LensFlareSystem.prototype.getEmitter = function () {
  81912. return this._emitter;
  81913. };
  81914. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81915. this._emitter = newEmitter;
  81916. };
  81917. LensFlareSystem.prototype.getEmitterPosition = function () {
  81918. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81919. };
  81920. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81921. var position = this.getEmitterPosition();
  81922. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81923. this._positionX = position.x;
  81924. this._positionY = position.y;
  81925. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81926. if (this.viewportBorder > 0) {
  81927. globalViewport.x -= this.viewportBorder;
  81928. globalViewport.y -= this.viewportBorder;
  81929. globalViewport.width += this.viewportBorder * 2;
  81930. globalViewport.height += this.viewportBorder * 2;
  81931. position.x += this.viewportBorder;
  81932. position.y += this.viewportBorder;
  81933. this._positionX += this.viewportBorder;
  81934. this._positionY += this.viewportBorder;
  81935. }
  81936. if (position.z > 0) {
  81937. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81938. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81939. return true;
  81940. }
  81941. return true;
  81942. }
  81943. return false;
  81944. };
  81945. LensFlareSystem.prototype._isVisible = function () {
  81946. if (!this._isEnabled || !this._scene.activeCamera) {
  81947. return false;
  81948. }
  81949. var emitterPosition = this.getEmitterPosition();
  81950. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81951. var distance = direction.length();
  81952. direction.normalize();
  81953. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81954. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81955. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81956. };
  81957. LensFlareSystem.prototype.render = function () {
  81958. if (!this._effect.isReady() || !this._scene.activeCamera)
  81959. return false;
  81960. var engine = this._scene.getEngine();
  81961. var viewport = this._scene.activeCamera.viewport;
  81962. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81963. // Position
  81964. if (!this.computeEffectivePosition(globalViewport)) {
  81965. return false;
  81966. }
  81967. // Visibility
  81968. if (!this._isVisible()) {
  81969. return false;
  81970. }
  81971. // Intensity
  81972. var awayX;
  81973. var awayY;
  81974. if (this._positionX < this.borderLimit + globalViewport.x) {
  81975. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81976. }
  81977. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81978. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81979. }
  81980. else {
  81981. awayX = 0;
  81982. }
  81983. if (this._positionY < this.borderLimit + globalViewport.y) {
  81984. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81985. }
  81986. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81987. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81988. }
  81989. else {
  81990. awayY = 0;
  81991. }
  81992. var away = (awayX > awayY) ? awayX : awayY;
  81993. away -= this.viewportBorder;
  81994. if (away > this.borderLimit) {
  81995. away = this.borderLimit;
  81996. }
  81997. var intensity = 1.0 - (away / this.borderLimit);
  81998. if (intensity < 0) {
  81999. return false;
  82000. }
  82001. if (intensity > 1.0) {
  82002. intensity = 1.0;
  82003. }
  82004. if (this.viewportBorder > 0) {
  82005. globalViewport.x += this.viewportBorder;
  82006. globalViewport.y += this.viewportBorder;
  82007. globalViewport.width -= this.viewportBorder * 2;
  82008. globalViewport.height -= this.viewportBorder * 2;
  82009. this._positionX -= this.viewportBorder;
  82010. this._positionY -= this.viewportBorder;
  82011. }
  82012. // Position
  82013. var centerX = globalViewport.x + globalViewport.width / 2;
  82014. var centerY = globalViewport.y + globalViewport.height / 2;
  82015. var distX = centerX - this._positionX;
  82016. var distY = centerY - this._positionY;
  82017. // Effects
  82018. engine.enableEffect(this._effect);
  82019. engine.setState(false);
  82020. engine.setDepthBuffer(false);
  82021. // VBOs
  82022. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82023. // Flares
  82024. for (var index = 0; index < this.lensFlares.length; index++) {
  82025. var flare = this.lensFlares[index];
  82026. engine.setAlphaMode(flare.alphaMode);
  82027. var x = centerX - (distX * flare.position);
  82028. var y = centerY - (distY * flare.position);
  82029. var cw = flare.size;
  82030. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82031. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82032. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82033. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82034. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82035. // Texture
  82036. this._effect.setTexture("textureSampler", flare.texture);
  82037. // Color
  82038. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82039. // Draw order
  82040. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82041. }
  82042. engine.setDepthBuffer(true);
  82043. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82044. return true;
  82045. };
  82046. LensFlareSystem.prototype.dispose = function () {
  82047. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82048. if (vertexBuffer) {
  82049. vertexBuffer.dispose();
  82050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82051. }
  82052. if (this._indexBuffer) {
  82053. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82054. this._indexBuffer = null;
  82055. }
  82056. while (this.lensFlares.length) {
  82057. this.lensFlares[0].dispose();
  82058. }
  82059. // Remove from scene
  82060. var index = this._scene.lensFlareSystems.indexOf(this);
  82061. this._scene.lensFlareSystems.splice(index, 1);
  82062. };
  82063. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82064. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82065. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82066. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82067. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82068. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82069. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82070. var parsedFlare = parsedLensFlareSystem.flares[index];
  82071. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82072. }
  82073. return lensFlareSystem;
  82074. };
  82075. LensFlareSystem.prototype.serialize = function () {
  82076. var serializationObject = {};
  82077. serializationObject.id = this.id;
  82078. serializationObject.name = this.name;
  82079. serializationObject.emitterId = this.getEmitter().id;
  82080. serializationObject.borderLimit = this.borderLimit;
  82081. serializationObject.flares = [];
  82082. for (var index = 0; index < this.lensFlares.length; index++) {
  82083. var flare = this.lensFlares[index];
  82084. serializationObject.flares.push({
  82085. size: flare.size,
  82086. position: flare.position,
  82087. color: flare.color.asArray(),
  82088. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82089. });
  82090. }
  82091. return serializationObject;
  82092. };
  82093. return LensFlareSystem;
  82094. }());
  82095. BABYLON.LensFlareSystem = LensFlareSystem;
  82096. })(BABYLON || (BABYLON = {}));
  82097. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82098. var BABYLON;
  82099. (function (BABYLON) {
  82100. /**
  82101. * This is a holder class for the physics joint created by the physics plugin.
  82102. * It holds a set of functions to control the underlying joint.
  82103. */
  82104. var PhysicsJoint = /** @class */ (function () {
  82105. function PhysicsJoint(type, jointData) {
  82106. this.type = type;
  82107. this.jointData = jointData;
  82108. jointData.nativeParams = jointData.nativeParams || {};
  82109. }
  82110. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82111. get: function () {
  82112. return this._physicsJoint;
  82113. },
  82114. set: function (newJoint) {
  82115. if (this._physicsJoint) {
  82116. //remove from the wolrd
  82117. }
  82118. this._physicsJoint = newJoint;
  82119. },
  82120. enumerable: true,
  82121. configurable: true
  82122. });
  82123. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82124. set: function (physicsPlugin) {
  82125. this._physicsPlugin = physicsPlugin;
  82126. },
  82127. enumerable: true,
  82128. configurable: true
  82129. });
  82130. /**
  82131. * Execute a function that is physics-plugin specific.
  82132. * @param {Function} func the function that will be executed.
  82133. * It accepts two parameters: the physics world and the physics joint.
  82134. */
  82135. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82136. func(this._physicsPlugin.world, this._physicsJoint);
  82137. };
  82138. //TODO check if the native joints are the same
  82139. //Joint Types
  82140. PhysicsJoint.DistanceJoint = 0;
  82141. PhysicsJoint.HingeJoint = 1;
  82142. PhysicsJoint.BallAndSocketJoint = 2;
  82143. PhysicsJoint.WheelJoint = 3;
  82144. PhysicsJoint.SliderJoint = 4;
  82145. //OIMO
  82146. PhysicsJoint.PrismaticJoint = 5;
  82147. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82148. PhysicsJoint.UniversalJoint = 6;
  82149. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82150. //Cannon
  82151. //Similar to a Ball-Joint. Different in params
  82152. PhysicsJoint.PointToPointJoint = 8;
  82153. //Cannon only at the moment
  82154. PhysicsJoint.SpringJoint = 9;
  82155. PhysicsJoint.LockJoint = 10;
  82156. return PhysicsJoint;
  82157. }());
  82158. BABYLON.PhysicsJoint = PhysicsJoint;
  82159. /**
  82160. * A class representing a physics distance joint.
  82161. */
  82162. var DistanceJoint = /** @class */ (function (_super) {
  82163. __extends(DistanceJoint, _super);
  82164. function DistanceJoint(jointData) {
  82165. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82166. }
  82167. /**
  82168. * Update the predefined distance.
  82169. */
  82170. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82171. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82172. };
  82173. return DistanceJoint;
  82174. }(PhysicsJoint));
  82175. BABYLON.DistanceJoint = DistanceJoint;
  82176. var MotorEnabledJoint = /** @class */ (function (_super) {
  82177. __extends(MotorEnabledJoint, _super);
  82178. function MotorEnabledJoint(type, jointData) {
  82179. return _super.call(this, type, jointData) || this;
  82180. }
  82181. /**
  82182. * Set the motor values.
  82183. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82184. * @param {number} force the force to apply
  82185. * @param {number} maxForce max force for this motor.
  82186. */
  82187. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82188. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82189. };
  82190. /**
  82191. * Set the motor's limits.
  82192. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82193. */
  82194. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82195. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82196. };
  82197. return MotorEnabledJoint;
  82198. }(PhysicsJoint));
  82199. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82200. /**
  82201. * This class represents a single hinge physics joint
  82202. */
  82203. var HingeJoint = /** @class */ (function (_super) {
  82204. __extends(HingeJoint, _super);
  82205. function HingeJoint(jointData) {
  82206. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82207. }
  82208. /**
  82209. * Set the motor values.
  82210. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82211. * @param {number} force the force to apply
  82212. * @param {number} maxForce max force for this motor.
  82213. */
  82214. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82215. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82216. };
  82217. /**
  82218. * Set the motor's limits.
  82219. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82220. */
  82221. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82222. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82223. };
  82224. return HingeJoint;
  82225. }(MotorEnabledJoint));
  82226. BABYLON.HingeJoint = HingeJoint;
  82227. /**
  82228. * This class represents a dual hinge physics joint (same as wheel joint)
  82229. */
  82230. var Hinge2Joint = /** @class */ (function (_super) {
  82231. __extends(Hinge2Joint, _super);
  82232. function Hinge2Joint(jointData) {
  82233. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82234. }
  82235. /**
  82236. * Set the motor values.
  82237. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82238. * @param {number} force the force to apply
  82239. * @param {number} maxForce max force for this motor.
  82240. * @param {motorIndex} the motor's index, 0 or 1.
  82241. */
  82242. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82243. if (motorIndex === void 0) { motorIndex = 0; }
  82244. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82245. };
  82246. /**
  82247. * Set the motor limits.
  82248. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82249. * @param {number} upperLimit the upper limit
  82250. * @param {number} lowerLimit lower limit
  82251. * @param {motorIndex} the motor's index, 0 or 1.
  82252. */
  82253. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82254. if (motorIndex === void 0) { motorIndex = 0; }
  82255. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82256. };
  82257. return Hinge2Joint;
  82258. }(MotorEnabledJoint));
  82259. BABYLON.Hinge2Joint = Hinge2Joint;
  82260. })(BABYLON || (BABYLON = {}));
  82261. //# sourceMappingURL=babylon.physicsJoint.js.map
  82262. var BABYLON;
  82263. (function (BABYLON) {
  82264. var PhysicsImpostor = /** @class */ (function () {
  82265. function PhysicsImpostor(object, type, _options, _scene) {
  82266. if (_options === void 0) { _options = { mass: 0 }; }
  82267. var _this = this;
  82268. this.object = object;
  82269. this.type = type;
  82270. this._options = _options;
  82271. this._scene = _scene;
  82272. this._bodyUpdateRequired = false;
  82273. this._onBeforePhysicsStepCallbacks = new Array();
  82274. this._onAfterPhysicsStepCallbacks = new Array();
  82275. this._onPhysicsCollideCallbacks = [];
  82276. this._deltaPosition = BABYLON.Vector3.Zero();
  82277. this._isDisposed = false;
  82278. //temp variables for parent rotation calculations
  82279. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82280. this._tmpQuat = new BABYLON.Quaternion();
  82281. this._tmpQuat2 = new BABYLON.Quaternion();
  82282. /**
  82283. * this function is executed by the physics engine.
  82284. */
  82285. this.beforeStep = function () {
  82286. if (!_this._physicsEngine) {
  82287. return;
  82288. }
  82289. _this.object.translate(_this._deltaPosition, -1);
  82290. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82291. _this.object.computeWorldMatrix(false);
  82292. if (_this.object.parent && _this.object.rotationQuaternion) {
  82293. _this.getParentsRotation();
  82294. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82295. }
  82296. else {
  82297. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82298. }
  82299. if (!_this._options.disableBidirectionalTransformation) {
  82300. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82301. }
  82302. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82303. func(_this);
  82304. });
  82305. };
  82306. /**
  82307. * this function is executed by the physics engine.
  82308. */
  82309. this.afterStep = function () {
  82310. if (!_this._physicsEngine) {
  82311. return;
  82312. }
  82313. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82314. func(_this);
  82315. });
  82316. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82317. // object has now its world rotation. needs to be converted to local.
  82318. if (_this.object.parent && _this.object.rotationQuaternion) {
  82319. _this.getParentsRotation();
  82320. _this._tmpQuat.conjugateInPlace();
  82321. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82322. }
  82323. // take the position set and make it the absolute position of this object.
  82324. _this.object.setAbsolutePosition(_this.object.position);
  82325. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82326. _this.object.translate(_this._deltaPosition, 1);
  82327. };
  82328. /**
  82329. * Legacy collision detection event support
  82330. */
  82331. this.onCollideEvent = null;
  82332. //event and body object due to cannon's event-based architecture.
  82333. this.onCollide = function (e) {
  82334. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82335. return;
  82336. }
  82337. if (!_this._physicsEngine) {
  82338. return;
  82339. }
  82340. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82341. if (otherImpostor) {
  82342. // Legacy collision detection event support
  82343. if (_this.onCollideEvent) {
  82344. _this.onCollideEvent(_this, otherImpostor);
  82345. }
  82346. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82347. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82348. }).forEach(function (obj) {
  82349. obj.callback(_this, otherImpostor);
  82350. });
  82351. }
  82352. };
  82353. //sanity check!
  82354. if (!this.object) {
  82355. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82356. return;
  82357. }
  82358. //legacy support for old syntax.
  82359. if (!this._scene && object.getScene) {
  82360. this._scene = object.getScene();
  82361. }
  82362. if (!this._scene) {
  82363. return;
  82364. }
  82365. this._physicsEngine = this._scene.getPhysicsEngine();
  82366. if (!this._physicsEngine) {
  82367. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82368. }
  82369. else {
  82370. //set the object's quaternion, if not set
  82371. if (!this.object.rotationQuaternion) {
  82372. if (this.object.rotation) {
  82373. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82374. }
  82375. else {
  82376. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82377. }
  82378. }
  82379. //default options params
  82380. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82381. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82382. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82383. this._joints = [];
  82384. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82385. if (!this.object.parent || this._options.ignoreParent) {
  82386. this._init();
  82387. }
  82388. else if (this.object.parent.physicsImpostor) {
  82389. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82390. }
  82391. }
  82392. }
  82393. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82394. get: function () {
  82395. return this._isDisposed;
  82396. },
  82397. enumerable: true,
  82398. configurable: true
  82399. });
  82400. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82401. get: function () {
  82402. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82403. },
  82404. set: function (value) {
  82405. this.setMass(value);
  82406. },
  82407. enumerable: true,
  82408. configurable: true
  82409. });
  82410. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82411. get: function () {
  82412. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82413. },
  82414. set: function (value) {
  82415. if (!this._physicsEngine) {
  82416. return;
  82417. }
  82418. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82419. },
  82420. enumerable: true,
  82421. configurable: true
  82422. });
  82423. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82424. get: function () {
  82425. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82426. },
  82427. set: function (value) {
  82428. if (!this._physicsEngine) {
  82429. return;
  82430. }
  82431. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82432. },
  82433. enumerable: true,
  82434. configurable: true
  82435. });
  82436. /**
  82437. * This function will completly initialize this impostor.
  82438. * It will create a new body - but only if this mesh has no parent.
  82439. * If it has, this impostor will not be used other than to define the impostor
  82440. * of the child mesh.
  82441. */
  82442. PhysicsImpostor.prototype._init = function () {
  82443. if (!this._physicsEngine) {
  82444. return;
  82445. }
  82446. this._physicsEngine.removeImpostor(this);
  82447. this.physicsBody = null;
  82448. this._parent = this._parent || this._getPhysicsParent();
  82449. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82450. this._physicsEngine.addImpostor(this);
  82451. }
  82452. };
  82453. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82454. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82455. var parentMesh = this.object.parent;
  82456. return parentMesh.physicsImpostor;
  82457. }
  82458. return null;
  82459. };
  82460. /**
  82461. * Should a new body be generated.
  82462. */
  82463. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82464. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82465. };
  82466. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82467. this.forceUpdate();
  82468. };
  82469. /**
  82470. * Force a regeneration of this or the parent's impostor's body.
  82471. * Use under cautious - This will remove all joints already implemented.
  82472. */
  82473. PhysicsImpostor.prototype.forceUpdate = function () {
  82474. this._init();
  82475. if (this.parent && !this._options.ignoreParent) {
  82476. this.parent.forceUpdate();
  82477. }
  82478. };
  82479. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82480. /*public get mesh(): AbstractMesh {
  82481. return this._mesh;
  82482. }*/
  82483. /**
  82484. * Gets the body that holds this impostor. Either its own, or its parent.
  82485. */
  82486. get: function () {
  82487. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82488. },
  82489. /**
  82490. * Set the physics body. Used mainly by the physics engine/plugin
  82491. */
  82492. set: function (physicsBody) {
  82493. if (this._physicsBody && this._physicsEngine) {
  82494. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82495. }
  82496. this._physicsBody = physicsBody;
  82497. this.resetUpdateFlags();
  82498. },
  82499. enumerable: true,
  82500. configurable: true
  82501. });
  82502. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82503. get: function () {
  82504. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82505. },
  82506. set: function (value) {
  82507. this._parent = value;
  82508. },
  82509. enumerable: true,
  82510. configurable: true
  82511. });
  82512. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82513. this._bodyUpdateRequired = false;
  82514. };
  82515. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82516. if (this.object.getBoundingInfo) {
  82517. var q = this.object.rotationQuaternion;
  82518. //reset rotation
  82519. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82520. //calculate the world matrix with no rotation
  82521. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82522. var boundingInfo = this.object.getBoundingInfo();
  82523. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82524. //bring back the rotation
  82525. this.object.rotationQuaternion = q;
  82526. //calculate the world matrix with the new rotation
  82527. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82528. return size;
  82529. }
  82530. else {
  82531. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82532. }
  82533. };
  82534. PhysicsImpostor.prototype.getObjectCenter = function () {
  82535. if (this.object.getBoundingInfo) {
  82536. var boundingInfo = this.object.getBoundingInfo();
  82537. return boundingInfo.boundingBox.centerWorld;
  82538. }
  82539. else {
  82540. return this.object.position;
  82541. }
  82542. };
  82543. /**
  82544. * Get a specific parametes from the options parameter.
  82545. */
  82546. PhysicsImpostor.prototype.getParam = function (paramName) {
  82547. return this._options[paramName];
  82548. };
  82549. /**
  82550. * Sets a specific parameter in the options given to the physics plugin
  82551. */
  82552. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82553. this._options[paramName] = value;
  82554. this._bodyUpdateRequired = true;
  82555. };
  82556. /**
  82557. * Specifically change the body's mass option. Won't recreate the physics body object
  82558. */
  82559. PhysicsImpostor.prototype.setMass = function (mass) {
  82560. if (this.getParam("mass") !== mass) {
  82561. this.setParam("mass", mass);
  82562. }
  82563. if (this._physicsEngine) {
  82564. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82565. }
  82566. };
  82567. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82569. };
  82570. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82571. if (this._physicsEngine) {
  82572. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82573. }
  82574. };
  82575. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82576. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82577. };
  82578. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82579. if (this._physicsEngine) {
  82580. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82581. }
  82582. };
  82583. /**
  82584. * Execute a function with the physics plugin native code.
  82585. * Provide a function the will have two variables - the world object and the physics body object.
  82586. */
  82587. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82588. if (this._physicsEngine) {
  82589. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82590. }
  82591. };
  82592. /**
  82593. * Register a function that will be executed before the physics world is stepping forward.
  82594. */
  82595. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82596. this._onBeforePhysicsStepCallbacks.push(func);
  82597. };
  82598. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82599. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82600. if (index > -1) {
  82601. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82602. }
  82603. else {
  82604. BABYLON.Tools.Warn("Function to remove was not found");
  82605. }
  82606. };
  82607. /**
  82608. * Register a function that will be executed after the physics step
  82609. */
  82610. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82611. this._onAfterPhysicsStepCallbacks.push(func);
  82612. };
  82613. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82614. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82615. if (index > -1) {
  82616. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82617. }
  82618. else {
  82619. BABYLON.Tools.Warn("Function to remove was not found");
  82620. }
  82621. };
  82622. /**
  82623. * register a function that will be executed when this impostor collides against a different body.
  82624. */
  82625. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82626. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82627. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82628. };
  82629. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82630. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82631. var index = -1;
  82632. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82633. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82634. // chcek the arrays match
  82635. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82636. return collidedAgainstList.indexOf(impostor) > -1;
  82637. });
  82638. if (sameList) {
  82639. index = idx;
  82640. }
  82641. return sameList;
  82642. }
  82643. return false;
  82644. });
  82645. if (found) {
  82646. this._onPhysicsCollideCallbacks.splice(index, 1);
  82647. }
  82648. else {
  82649. BABYLON.Tools.Warn("Function to remove was not found");
  82650. }
  82651. };
  82652. PhysicsImpostor.prototype.getParentsRotation = function () {
  82653. var parent = this.object.parent;
  82654. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82655. while (parent) {
  82656. if (parent.rotationQuaternion) {
  82657. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82658. }
  82659. else {
  82660. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82661. }
  82662. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82663. parent = parent.parent;
  82664. }
  82665. return this._tmpQuat;
  82666. };
  82667. /**
  82668. * Apply a force
  82669. */
  82670. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82671. if (this._physicsEngine) {
  82672. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82673. }
  82674. return this;
  82675. };
  82676. /**
  82677. * Apply an impulse
  82678. */
  82679. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82680. if (this._physicsEngine) {
  82681. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82682. }
  82683. return this;
  82684. };
  82685. /**
  82686. * A help function to create a joint.
  82687. */
  82688. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82689. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82690. this.addJoint(otherImpostor, joint);
  82691. return this;
  82692. };
  82693. /**
  82694. * Add a joint to this impostor with a different impostor.
  82695. */
  82696. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82697. this._joints.push({
  82698. otherImpostor: otherImpostor,
  82699. joint: joint
  82700. });
  82701. if (this._physicsEngine) {
  82702. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82703. }
  82704. return this;
  82705. };
  82706. /**
  82707. * Will keep this body still, in a sleep mode.
  82708. */
  82709. PhysicsImpostor.prototype.sleep = function () {
  82710. if (this._physicsEngine) {
  82711. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82712. }
  82713. return this;
  82714. };
  82715. /**
  82716. * Wake the body up.
  82717. */
  82718. PhysicsImpostor.prototype.wakeUp = function () {
  82719. if (this._physicsEngine) {
  82720. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82721. }
  82722. return this;
  82723. };
  82724. PhysicsImpostor.prototype.clone = function (newObject) {
  82725. if (!newObject)
  82726. return null;
  82727. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82728. };
  82729. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82730. var _this = this;
  82731. //no dispose if no physics engine is available.
  82732. if (!this._physicsEngine) {
  82733. return;
  82734. }
  82735. this._joints.forEach(function (j) {
  82736. if (_this._physicsEngine) {
  82737. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82738. }
  82739. });
  82740. //dispose the physics body
  82741. this._physicsEngine.removeImpostor(this);
  82742. if (this.parent) {
  82743. this.parent.forceUpdate();
  82744. }
  82745. else {
  82746. /*this._object.getChildMeshes().forEach(function(mesh) {
  82747. if (mesh.physicsImpostor) {
  82748. if (disposeChildren) {
  82749. mesh.physicsImpostor.dispose();
  82750. mesh.physicsImpostor = null;
  82751. }
  82752. }
  82753. })*/
  82754. }
  82755. this._isDisposed = true;
  82756. };
  82757. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82758. this._deltaPosition.copyFrom(position);
  82759. };
  82760. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82761. if (!this._deltaRotation) {
  82762. this._deltaRotation = new BABYLON.Quaternion();
  82763. }
  82764. this._deltaRotation.copyFrom(rotation);
  82765. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82766. };
  82767. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82768. if (this._physicsEngine) {
  82769. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82770. }
  82771. return this;
  82772. };
  82773. PhysicsImpostor.prototype.getRadius = function () {
  82774. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82775. };
  82776. /**
  82777. * Sync a bone with this impostor
  82778. * @param bone The bone to sync to the impostor.
  82779. * @param boneMesh The mesh that the bone is influencing.
  82780. * @param jointPivot The pivot of the joint / bone in local space.
  82781. * @param distToJoint Optional distance from the impostor to the joint.
  82782. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82783. */
  82784. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82785. var tempVec = PhysicsImpostor._tmpVecs[0];
  82786. var mesh = this.object;
  82787. if (mesh.rotationQuaternion) {
  82788. if (adjustRotation) {
  82789. var tempQuat = PhysicsImpostor._tmpQuat;
  82790. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82791. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82792. }
  82793. else {
  82794. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82795. }
  82796. }
  82797. tempVec.x = 0;
  82798. tempVec.y = 0;
  82799. tempVec.z = 0;
  82800. if (jointPivot) {
  82801. tempVec.x = jointPivot.x;
  82802. tempVec.y = jointPivot.y;
  82803. tempVec.z = jointPivot.z;
  82804. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82805. if (distToJoint === undefined || distToJoint === null) {
  82806. distToJoint = jointPivot.length();
  82807. }
  82808. tempVec.x *= distToJoint;
  82809. tempVec.y *= distToJoint;
  82810. tempVec.z *= distToJoint;
  82811. }
  82812. if (bone.getParent()) {
  82813. tempVec.addInPlace(mesh.getAbsolutePosition());
  82814. bone.setAbsolutePosition(tempVec, boneMesh);
  82815. }
  82816. else {
  82817. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82818. boneMesh.position.x -= tempVec.x;
  82819. boneMesh.position.y -= tempVec.y;
  82820. boneMesh.position.z -= tempVec.z;
  82821. }
  82822. };
  82823. /**
  82824. * Sync impostor to a bone
  82825. * @param bone The bone that the impostor will be synced to.
  82826. * @param boneMesh The mesh that the bone is influencing.
  82827. * @param jointPivot The pivot of the joint / bone in local space.
  82828. * @param distToJoint Optional distance from the impostor to the joint.
  82829. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82830. * @param boneAxis Optional vector3 axis the bone is aligned with
  82831. */
  82832. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82833. var mesh = this.object;
  82834. if (mesh.rotationQuaternion) {
  82835. if (adjustRotation) {
  82836. var tempQuat = PhysicsImpostor._tmpQuat;
  82837. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82838. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82839. }
  82840. else {
  82841. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82842. }
  82843. }
  82844. var pos = PhysicsImpostor._tmpVecs[0];
  82845. var boneDir = PhysicsImpostor._tmpVecs[1];
  82846. if (!boneAxis) {
  82847. boneAxis = PhysicsImpostor._tmpVecs[2];
  82848. boneAxis.x = 0;
  82849. boneAxis.y = 1;
  82850. boneAxis.z = 0;
  82851. }
  82852. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82853. bone.getAbsolutePositionToRef(boneMesh, pos);
  82854. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82855. distToJoint = jointPivot.length();
  82856. }
  82857. if (distToJoint !== undefined && distToJoint !== null) {
  82858. pos.x += boneDir.x * distToJoint;
  82859. pos.y += boneDir.y * distToJoint;
  82860. pos.z += boneDir.z * distToJoint;
  82861. }
  82862. mesh.setAbsolutePosition(pos);
  82863. };
  82864. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82865. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82866. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82867. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82868. //Impostor types
  82869. PhysicsImpostor.NoImpostor = 0;
  82870. PhysicsImpostor.SphereImpostor = 1;
  82871. PhysicsImpostor.BoxImpostor = 2;
  82872. PhysicsImpostor.PlaneImpostor = 3;
  82873. PhysicsImpostor.MeshImpostor = 4;
  82874. PhysicsImpostor.CylinderImpostor = 7;
  82875. PhysicsImpostor.ParticleImpostor = 8;
  82876. PhysicsImpostor.HeightmapImpostor = 9;
  82877. return PhysicsImpostor;
  82878. }());
  82879. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82880. })(BABYLON || (BABYLON = {}));
  82881. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82882. var BABYLON;
  82883. (function (BABYLON) {
  82884. var PhysicsEngine = /** @class */ (function () {
  82885. function PhysicsEngine(gravity, _physicsPlugin) {
  82886. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82887. this._physicsPlugin = _physicsPlugin;
  82888. //new methods and parameters
  82889. this._impostors = [];
  82890. this._joints = [];
  82891. if (!this._physicsPlugin.isSupported()) {
  82892. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82893. + "Please make sure it is included.");
  82894. }
  82895. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82896. this.setGravity(gravity);
  82897. this.setTimeStep();
  82898. }
  82899. PhysicsEngine.prototype.setGravity = function (gravity) {
  82900. this.gravity = gravity;
  82901. this._physicsPlugin.setGravity(this.gravity);
  82902. };
  82903. /**
  82904. * Set the time step of the physics engine.
  82905. * default is 1/60.
  82906. * To slow it down, enter 1/600 for example.
  82907. * To speed it up, 1/30
  82908. * @param {number} newTimeStep the new timestep to apply to this world.
  82909. */
  82910. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82911. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82912. this._physicsPlugin.setTimeStep(newTimeStep);
  82913. };
  82914. /**
  82915. * Get the time step of the physics engine.
  82916. */
  82917. PhysicsEngine.prototype.getTimeStep = function () {
  82918. return this._physicsPlugin.getTimeStep();
  82919. };
  82920. PhysicsEngine.prototype.dispose = function () {
  82921. this._impostors.forEach(function (impostor) {
  82922. impostor.dispose();
  82923. });
  82924. this._physicsPlugin.dispose();
  82925. };
  82926. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82927. return this._physicsPlugin.name;
  82928. };
  82929. /**
  82930. * Adding a new impostor for the impostor tracking.
  82931. * This will be done by the impostor itself.
  82932. * @param {PhysicsImpostor} impostor the impostor to add
  82933. */
  82934. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82935. impostor.uniqueId = this._impostors.push(impostor);
  82936. //if no parent, generate the body
  82937. if (!impostor.parent) {
  82938. this._physicsPlugin.generatePhysicsBody(impostor);
  82939. }
  82940. };
  82941. /**
  82942. * Remove an impostor from the engine.
  82943. * This impostor and its mesh will not longer be updated by the physics engine.
  82944. * @param {PhysicsImpostor} impostor the impostor to remove
  82945. */
  82946. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82947. var index = this._impostors.indexOf(impostor);
  82948. if (index > -1) {
  82949. var removed = this._impostors.splice(index, 1);
  82950. //Is it needed?
  82951. if (removed.length) {
  82952. //this will also remove it from the world.
  82953. removed[0].physicsBody = null;
  82954. }
  82955. }
  82956. };
  82957. /**
  82958. * Add a joint to the physics engine
  82959. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82960. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82961. * @param {PhysicsJoint} the joint that will connect both impostors.
  82962. */
  82963. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82964. var impostorJoint = {
  82965. mainImpostor: mainImpostor,
  82966. connectedImpostor: connectedImpostor,
  82967. joint: joint
  82968. };
  82969. joint.physicsPlugin = this._physicsPlugin;
  82970. this._joints.push(impostorJoint);
  82971. this._physicsPlugin.generateJoint(impostorJoint);
  82972. };
  82973. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82974. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82975. return (impostorJoint.connectedImpostor === connectedImpostor
  82976. && impostorJoint.joint === joint
  82977. && impostorJoint.mainImpostor === mainImpostor);
  82978. });
  82979. if (matchingJoints.length) {
  82980. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82981. //TODO remove it from the list as well
  82982. }
  82983. };
  82984. /**
  82985. * Called by the scene. no need to call it.
  82986. */
  82987. PhysicsEngine.prototype._step = function (delta) {
  82988. var _this = this;
  82989. //check if any mesh has no body / requires an update
  82990. this._impostors.forEach(function (impostor) {
  82991. if (impostor.isBodyInitRequired()) {
  82992. _this._physicsPlugin.generatePhysicsBody(impostor);
  82993. }
  82994. });
  82995. if (delta > 0.1) {
  82996. delta = 0.1;
  82997. }
  82998. else if (delta <= 0) {
  82999. delta = 1.0 / 60.0;
  83000. }
  83001. this._physicsPlugin.executeStep(delta, this._impostors);
  83002. };
  83003. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83004. return this._physicsPlugin;
  83005. };
  83006. PhysicsEngine.prototype.getImpostors = function () {
  83007. return this._impostors;
  83008. };
  83009. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83010. for (var i = 0; i < this._impostors.length; ++i) {
  83011. if (this._impostors[i].object === object) {
  83012. return this._impostors[i];
  83013. }
  83014. }
  83015. return null;
  83016. };
  83017. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83018. for (var i = 0; i < this._impostors.length; ++i) {
  83019. if (this._impostors[i].physicsBody === body) {
  83020. return this._impostors[i];
  83021. }
  83022. }
  83023. return null;
  83024. };
  83025. // Statics
  83026. PhysicsEngine.Epsilon = 0.001;
  83027. return PhysicsEngine;
  83028. }());
  83029. BABYLON.PhysicsEngine = PhysicsEngine;
  83030. })(BABYLON || (BABYLON = {}));
  83031. //# sourceMappingURL=babylon.physicsEngine.js.map
  83032. var BABYLON;
  83033. (function (BABYLON) {
  83034. var PhysicsHelper = /** @class */ (function () {
  83035. function PhysicsHelper(scene) {
  83036. this._scene = scene;
  83037. this._physicsEngine = this._scene.getPhysicsEngine();
  83038. if (!this._physicsEngine) {
  83039. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83040. }
  83041. }
  83042. /**
  83043. * @param {Vector3} origin the origin of the explosion
  83044. * @param {number} radius the explosion radius
  83045. * @param {number} strength the explosion strength
  83046. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83047. */
  83048. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83049. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83050. if (!this._physicsEngine) {
  83051. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83052. return null;
  83053. }
  83054. var impostors = this._physicsEngine.getImpostors();
  83055. if (impostors.length === 0) {
  83056. return null;
  83057. }
  83058. var event = new PhysicsRadialExplosionEvent(this._scene);
  83059. impostors.forEach(function (impostor) {
  83060. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83061. if (!impostorForceAndContactPoint) {
  83062. return;
  83063. }
  83064. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83065. });
  83066. event.dispose(false);
  83067. return event;
  83068. };
  83069. /**
  83070. * @param {Vector3} origin the origin of the explosion
  83071. * @param {number} radius the explosion radius
  83072. * @param {number} strength the explosion strength
  83073. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83074. */
  83075. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83076. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83077. if (!this._physicsEngine) {
  83078. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83079. return null;
  83080. }
  83081. var impostors = this._physicsEngine.getImpostors();
  83082. if (impostors.length === 0) {
  83083. return null;
  83084. }
  83085. var event = new PhysicsRadialExplosionEvent(this._scene);
  83086. impostors.forEach(function (impostor) {
  83087. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83088. if (!impostorForceAndContactPoint) {
  83089. return;
  83090. }
  83091. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83092. });
  83093. event.dispose(false);
  83094. return event;
  83095. };
  83096. /**
  83097. * @param {Vector3} origin the origin of the explosion
  83098. * @param {number} radius the explosion radius
  83099. * @param {number} strength the explosion strength
  83100. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83101. */
  83102. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83103. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83104. if (!this._physicsEngine) {
  83105. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83106. return null;
  83107. }
  83108. var impostors = this._physicsEngine.getImpostors();
  83109. if (impostors.length === 0) {
  83110. return null;
  83111. }
  83112. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83113. event.dispose(false);
  83114. return event;
  83115. };
  83116. /**
  83117. * @param {Vector3} origin the origin of the updraft
  83118. * @param {number} radius the radius of the updraft
  83119. * @param {number} strength the strength of the updraft
  83120. * @param {number} height the height of the updraft
  83121. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83122. */
  83123. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83124. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83125. if (!this._physicsEngine) {
  83126. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83127. return null;
  83128. }
  83129. if (this._physicsEngine.getImpostors().length === 0) {
  83130. return null;
  83131. }
  83132. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83133. event.dispose(false);
  83134. return event;
  83135. };
  83136. /**
  83137. * @param {Vector3} origin the of the vortex
  83138. * @param {number} radius the radius of the vortex
  83139. * @param {number} strength the strength of the vortex
  83140. * @param {number} height the height of the vortex
  83141. */
  83142. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83143. if (!this._physicsEngine) {
  83144. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83145. return null;
  83146. }
  83147. if (this._physicsEngine.getImpostors().length === 0) {
  83148. return null;
  83149. }
  83150. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83151. event.dispose(false);
  83152. return event;
  83153. };
  83154. return PhysicsHelper;
  83155. }());
  83156. BABYLON.PhysicsHelper = PhysicsHelper;
  83157. /***** Radial explosion *****/
  83158. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83159. function PhysicsRadialExplosionEvent(scene) {
  83160. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83161. this._rays = [];
  83162. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83163. this._scene = scene;
  83164. }
  83165. /**
  83166. * Returns the data related to the radial explosion event (sphere & rays).
  83167. * @returns {PhysicsRadialExplosionEventData}
  83168. */
  83169. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83170. this._dataFetched = true;
  83171. return {
  83172. sphere: this._sphere,
  83173. rays: this._rays,
  83174. };
  83175. };
  83176. /**
  83177. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83178. * @param impostor
  83179. * @param {Vector3} origin the origin of the explosion
  83180. * @param {number} radius the explosion radius
  83181. * @param {number} strength the explosion strength
  83182. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83183. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83184. */
  83185. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83186. if (impostor.mass === 0) {
  83187. return null;
  83188. }
  83189. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83190. return null;
  83191. }
  83192. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83193. return null;
  83194. }
  83195. var impostorObjectCenter = impostor.getObjectCenter();
  83196. var direction = impostorObjectCenter.subtract(origin);
  83197. var ray = new BABYLON.Ray(origin, direction, radius);
  83198. this._rays.push(ray);
  83199. var hit = ray.intersectsMesh(impostor.object);
  83200. var contactPoint = hit.pickedPoint;
  83201. if (!contactPoint) {
  83202. return null;
  83203. }
  83204. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83205. if (distanceFromOrigin > radius) {
  83206. return null;
  83207. }
  83208. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83209. ? strength
  83210. : strength * (1 - (distanceFromOrigin / radius));
  83211. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83212. return { force: force, contactPoint: contactPoint };
  83213. };
  83214. /**
  83215. * Disposes the sphere.
  83216. * @param {bolean} force
  83217. */
  83218. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83219. var _this = this;
  83220. if (force === void 0) { force = true; }
  83221. if (force) {
  83222. this._sphere.dispose();
  83223. }
  83224. else {
  83225. setTimeout(function () {
  83226. if (!_this._dataFetched) {
  83227. _this._sphere.dispose();
  83228. }
  83229. }, 0);
  83230. }
  83231. };
  83232. /*** Helpers ***/
  83233. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83234. if (!this._sphere) {
  83235. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83236. this._sphere.isVisible = false;
  83237. }
  83238. };
  83239. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83240. var impostorObject = impostor.object;
  83241. this._prepareSphere();
  83242. this._sphere.position = origin;
  83243. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83244. this._sphere._updateBoundingInfo();
  83245. this._sphere.computeWorldMatrix(true);
  83246. return this._sphere.intersectsMesh(impostorObject, true);
  83247. };
  83248. return PhysicsRadialExplosionEvent;
  83249. }());
  83250. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83251. /***** Gravitational Field *****/
  83252. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83253. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83254. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83255. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83256. this._physicsHelper = physicsHelper;
  83257. this._scene = scene;
  83258. this._origin = origin;
  83259. this._radius = radius;
  83260. this._strength = strength;
  83261. this._falloff = falloff;
  83262. this._tickCallback = this._tick.bind(this);
  83263. }
  83264. /**
  83265. * Returns the data related to the gravitational field event (sphere).
  83266. * @returns {PhysicsGravitationalFieldEventData}
  83267. */
  83268. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83269. this._dataFetched = true;
  83270. return {
  83271. sphere: this._sphere,
  83272. };
  83273. };
  83274. /**
  83275. * Enables the gravitational field.
  83276. */
  83277. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83278. this._tickCallback.call(this);
  83279. this._scene.registerBeforeRender(this._tickCallback);
  83280. };
  83281. /**
  83282. * Disables the gravitational field.
  83283. */
  83284. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83285. this._scene.unregisterBeforeRender(this._tickCallback);
  83286. };
  83287. /**
  83288. * Disposes the sphere.
  83289. * @param {bolean} force
  83290. */
  83291. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83292. var _this = this;
  83293. if (force === void 0) { force = true; }
  83294. if (force) {
  83295. this._sphere.dispose();
  83296. }
  83297. else {
  83298. setTimeout(function () {
  83299. if (!_this._dataFetched) {
  83300. _this._sphere.dispose();
  83301. }
  83302. }, 0);
  83303. }
  83304. };
  83305. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83306. // Since the params won't change, we fetch the event only once
  83307. if (this._sphere) {
  83308. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83309. }
  83310. else {
  83311. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83312. if (radialExplosionEvent) {
  83313. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83314. }
  83315. }
  83316. };
  83317. return PhysicsGravitationalFieldEvent;
  83318. }());
  83319. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83320. /***** Updraft *****/
  83321. var PhysicsUpdraftEvent = /** @class */ (function () {
  83322. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83323. this._scene = _scene;
  83324. this._origin = _origin;
  83325. this._radius = _radius;
  83326. this._strength = _strength;
  83327. this._height = _height;
  83328. this._updraftMode = _updraftMode;
  83329. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83330. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83331. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83332. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83333. this._physicsEngine = this._scene.getPhysicsEngine();
  83334. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83335. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83336. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83337. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83338. }
  83339. this._tickCallback = this._tick.bind(this);
  83340. }
  83341. /**
  83342. * Returns the data related to the updraft event (cylinder).
  83343. * @returns {PhysicsUpdraftEventData}
  83344. */
  83345. PhysicsUpdraftEvent.prototype.getData = function () {
  83346. this._dataFetched = true;
  83347. return {
  83348. cylinder: this._cylinder,
  83349. };
  83350. };
  83351. /**
  83352. * Enables the updraft.
  83353. */
  83354. PhysicsUpdraftEvent.prototype.enable = function () {
  83355. this._tickCallback.call(this);
  83356. this._scene.registerBeforeRender(this._tickCallback);
  83357. };
  83358. /**
  83359. * Disables the cortex.
  83360. */
  83361. PhysicsUpdraftEvent.prototype.disable = function () {
  83362. this._scene.unregisterBeforeRender(this._tickCallback);
  83363. };
  83364. /**
  83365. * Disposes the sphere.
  83366. * @param {bolean} force
  83367. */
  83368. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83369. var _this = this;
  83370. if (force === void 0) { force = true; }
  83371. if (force) {
  83372. this._cylinder.dispose();
  83373. }
  83374. else {
  83375. setTimeout(function () {
  83376. if (!_this._dataFetched) {
  83377. _this._cylinder.dispose();
  83378. }
  83379. }, 0);
  83380. }
  83381. };
  83382. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83383. if (impostor.mass === 0) {
  83384. return null;
  83385. }
  83386. if (!this._intersectsWithCylinder(impostor)) {
  83387. return null;
  83388. }
  83389. var impostorObjectCenter = impostor.getObjectCenter();
  83390. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83391. var direction = this._originDirection;
  83392. }
  83393. else {
  83394. var direction = impostorObjectCenter.subtract(this._originTop);
  83395. }
  83396. var multiplier = this._strength * -1;
  83397. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83398. return { force: force, contactPoint: impostorObjectCenter };
  83399. };
  83400. PhysicsUpdraftEvent.prototype._tick = function () {
  83401. var _this = this;
  83402. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83403. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83404. if (!impostorForceAndContactPoint) {
  83405. return;
  83406. }
  83407. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83408. });
  83409. };
  83410. /*** Helpers ***/
  83411. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83412. if (!this._cylinder) {
  83413. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83414. height: this._height,
  83415. diameter: this._radius * 2,
  83416. }, this._scene);
  83417. this._cylinder.isVisible = false;
  83418. }
  83419. };
  83420. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83421. var impostorObject = impostor.object;
  83422. this._prepareCylinder();
  83423. this._cylinder.position = this._cylinderPosition;
  83424. return this._cylinder.intersectsMesh(impostorObject, true);
  83425. };
  83426. return PhysicsUpdraftEvent;
  83427. }());
  83428. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83429. /***** Vortex *****/
  83430. var PhysicsVortexEvent = /** @class */ (function () {
  83431. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83432. this._scene = _scene;
  83433. this._origin = _origin;
  83434. this._radius = _radius;
  83435. this._strength = _strength;
  83436. this._height = _height;
  83437. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83438. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83439. this._updraftMultiplier = 0.02;
  83440. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83441. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83442. this._physicsEngine = this._scene.getPhysicsEngine();
  83443. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83444. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83445. this._tickCallback = this._tick.bind(this);
  83446. }
  83447. /**
  83448. * Returns the data related to the vortex event (cylinder).
  83449. * @returns {PhysicsVortexEventData}
  83450. */
  83451. PhysicsVortexEvent.prototype.getData = function () {
  83452. this._dataFetched = true;
  83453. return {
  83454. cylinder: this._cylinder,
  83455. };
  83456. };
  83457. /**
  83458. * Enables the vortex.
  83459. */
  83460. PhysicsVortexEvent.prototype.enable = function () {
  83461. this._tickCallback.call(this);
  83462. this._scene.registerBeforeRender(this._tickCallback);
  83463. };
  83464. /**
  83465. * Disables the cortex.
  83466. */
  83467. PhysicsVortexEvent.prototype.disable = function () {
  83468. this._scene.unregisterBeforeRender(this._tickCallback);
  83469. };
  83470. /**
  83471. * Disposes the sphere.
  83472. * @param {bolean} force
  83473. */
  83474. PhysicsVortexEvent.prototype.dispose = function (force) {
  83475. var _this = this;
  83476. if (force === void 0) { force = true; }
  83477. if (force) {
  83478. this._cylinder.dispose();
  83479. }
  83480. else {
  83481. setTimeout(function () {
  83482. if (!_this._dataFetched) {
  83483. _this._cylinder.dispose();
  83484. }
  83485. }, 0);
  83486. }
  83487. };
  83488. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83489. if (impostor.mass === 0) {
  83490. return null;
  83491. }
  83492. if (!this._intersectsWithCylinder(impostor)) {
  83493. return null;
  83494. }
  83495. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83496. return null;
  83497. }
  83498. var impostorObjectCenter = impostor.getObjectCenter();
  83499. 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)
  83500. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83501. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83502. var hit = ray.intersectsMesh(impostor.object);
  83503. var contactPoint = hit.pickedPoint;
  83504. if (!contactPoint) {
  83505. return null;
  83506. }
  83507. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83508. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83509. var directionToOrigin = contactPoint.normalize();
  83510. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83511. directionToOrigin = directionToOrigin.negate();
  83512. }
  83513. // TODO: find a more physically based solution
  83514. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83515. var forceX = directionToOrigin.x * this._strength / 8;
  83516. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83517. var forceZ = directionToOrigin.z * this._strength / 8;
  83518. }
  83519. else {
  83520. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83521. var forceY = this._originTop.y * this._updraftMultiplier;
  83522. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83523. }
  83524. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83525. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83526. return { force: force, contactPoint: impostorObjectCenter };
  83527. };
  83528. PhysicsVortexEvent.prototype._tick = function () {
  83529. var _this = this;
  83530. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83531. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83532. if (!impostorForceAndContactPoint) {
  83533. return;
  83534. }
  83535. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83536. });
  83537. };
  83538. /*** Helpers ***/
  83539. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83540. if (!this._cylinder) {
  83541. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83542. height: this._height,
  83543. diameter: this._radius * 2,
  83544. }, this._scene);
  83545. this._cylinder.isVisible = false;
  83546. }
  83547. };
  83548. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83549. var impostorObject = impostor.object;
  83550. this._prepareCylinder();
  83551. this._cylinder.position = this._cylinderPosition;
  83552. return this._cylinder.intersectsMesh(impostorObject, true);
  83553. };
  83554. return PhysicsVortexEvent;
  83555. }());
  83556. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83557. /***** Enums *****/
  83558. /**
  83559. * The strenght of the force in correspondence to the distance of the affected object
  83560. */
  83561. var PhysicsRadialImpulseFalloff;
  83562. (function (PhysicsRadialImpulseFalloff) {
  83563. /** Defines that impulse is constant in strength across it's whole radius */
  83564. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83565. /** DEfines that impulse gets weaker if it's further from the origin */
  83566. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83567. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83568. /**
  83569. * The strenght of the force in correspondence to the distance of the affected object
  83570. */
  83571. var PhysicsUpdraftMode;
  83572. (function (PhysicsUpdraftMode) {
  83573. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83574. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83575. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83576. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83577. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83578. })(BABYLON || (BABYLON = {}));
  83579. //# sourceMappingURL=babylon.physicsHelper.js.map
  83580. var BABYLON;
  83581. (function (BABYLON) {
  83582. var CannonJSPlugin = /** @class */ (function () {
  83583. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83584. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83585. if (iterations === void 0) { iterations = 10; }
  83586. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83587. this.name = "CannonJSPlugin";
  83588. this._physicsMaterials = new Array();
  83589. this._fixedTimeStep = 1 / 60;
  83590. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83591. this.BJSCANNON = CANNON;
  83592. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83593. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83594. this._tmpPosition = BABYLON.Vector3.Zero();
  83595. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83596. this._tmpUnityRotation = new BABYLON.Quaternion();
  83597. if (!this.isSupported()) {
  83598. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83599. return;
  83600. }
  83601. this._extendNamespace();
  83602. this.world = new this.BJSCANNON.World();
  83603. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83604. this.world.solver.iterations = iterations;
  83605. }
  83606. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83607. this.world.gravity.copy(gravity);
  83608. };
  83609. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83610. this._fixedTimeStep = timeStep;
  83611. };
  83612. CannonJSPlugin.prototype.getTimeStep = function () {
  83613. return this._fixedTimeStep;
  83614. };
  83615. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83616. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83617. };
  83618. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83619. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83620. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83621. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83622. };
  83623. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83624. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83625. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83626. impostor.physicsBody.applyForce(impulse, worldPoint);
  83627. };
  83628. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83629. //parent-child relationship. Does this impostor has a parent impostor?
  83630. if (impostor.parent) {
  83631. if (impostor.physicsBody) {
  83632. this.removePhysicsBody(impostor);
  83633. //TODO is that needed?
  83634. impostor.forceUpdate();
  83635. }
  83636. return;
  83637. }
  83638. //should a new body be created for this impostor?
  83639. if (impostor.isBodyInitRequired()) {
  83640. var shape = this._createShape(impostor);
  83641. //unregister events, if body is being changed
  83642. var oldBody = impostor.physicsBody;
  83643. if (oldBody) {
  83644. this.removePhysicsBody(impostor);
  83645. }
  83646. //create the body and material
  83647. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83648. var bodyCreationObject = {
  83649. mass: impostor.getParam("mass"),
  83650. material: material
  83651. };
  83652. // A simple extend, in case native options were used.
  83653. var nativeOptions = impostor.getParam("nativeOptions");
  83654. for (var key in nativeOptions) {
  83655. if (nativeOptions.hasOwnProperty(key)) {
  83656. bodyCreationObject[key] = nativeOptions[key];
  83657. }
  83658. }
  83659. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83660. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83661. this.world.addEventListener("preStep", impostor.beforeStep);
  83662. this.world.addEventListener("postStep", impostor.afterStep);
  83663. impostor.physicsBody.addShape(shape);
  83664. this.world.add(impostor.physicsBody);
  83665. //try to keep the body moving in the right direction by taking old properties.
  83666. //Should be tested!
  83667. if (oldBody) {
  83668. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83669. impostor.physicsBody[param].copy(oldBody[param]);
  83670. });
  83671. }
  83672. this._processChildMeshes(impostor);
  83673. }
  83674. //now update the body's transformation
  83675. this._updatePhysicsBodyTransformation(impostor);
  83676. };
  83677. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83678. var _this = this;
  83679. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83680. var currentRotation = mainImpostor.object.rotationQuaternion;
  83681. if (meshChildren.length) {
  83682. var processMesh = function (localPosition, mesh) {
  83683. if (!currentRotation || !mesh.rotationQuaternion) {
  83684. return;
  83685. }
  83686. var childImpostor = mesh.getPhysicsImpostor();
  83687. if (childImpostor) {
  83688. var parent = childImpostor.parent;
  83689. if (parent !== mainImpostor) {
  83690. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83691. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83692. if (childImpostor.physicsBody) {
  83693. _this.removePhysicsBody(childImpostor);
  83694. childImpostor.physicsBody = null;
  83695. }
  83696. childImpostor.parent = mainImpostor;
  83697. childImpostor.resetUpdateFlags();
  83698. 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));
  83699. //Add the mass of the children.
  83700. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83701. }
  83702. }
  83703. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83704. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83705. };
  83706. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83707. }
  83708. };
  83709. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83710. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83711. this.world.removeEventListener("preStep", impostor.beforeStep);
  83712. this.world.removeEventListener("postStep", impostor.afterStep);
  83713. this.world.remove(impostor.physicsBody);
  83714. };
  83715. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83716. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83717. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83718. if (!mainBody || !connectedBody) {
  83719. return;
  83720. }
  83721. var constraint;
  83722. var jointData = impostorJoint.joint.jointData;
  83723. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83724. var constraintData = {
  83725. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83726. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83727. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83728. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83729. maxForce: jointData.nativeParams.maxForce,
  83730. collideConnected: !!jointData.collision
  83731. };
  83732. switch (impostorJoint.joint.type) {
  83733. case BABYLON.PhysicsJoint.HingeJoint:
  83734. case BABYLON.PhysicsJoint.Hinge2Joint:
  83735. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83736. break;
  83737. case BABYLON.PhysicsJoint.DistanceJoint:
  83738. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83739. break;
  83740. case BABYLON.PhysicsJoint.SpringJoint:
  83741. var springData = jointData;
  83742. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83743. restLength: springData.length,
  83744. stiffness: springData.stiffness,
  83745. damping: springData.damping,
  83746. localAnchorA: constraintData.pivotA,
  83747. localAnchorB: constraintData.pivotB
  83748. });
  83749. break;
  83750. case BABYLON.PhysicsJoint.LockJoint:
  83751. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83752. break;
  83753. case BABYLON.PhysicsJoint.PointToPointJoint:
  83754. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83755. default:
  83756. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83757. break;
  83758. }
  83759. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83760. constraint.collideConnected = !!jointData.collision;
  83761. impostorJoint.joint.physicsJoint = constraint;
  83762. //don't add spring as constraint, as it is not one.
  83763. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83764. this.world.addConstraint(constraint);
  83765. }
  83766. else {
  83767. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83768. constraint.applyForce();
  83769. });
  83770. }
  83771. };
  83772. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83773. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83774. };
  83775. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83776. var index;
  83777. var mat;
  83778. for (index = 0; index < this._physicsMaterials.length; index++) {
  83779. mat = this._physicsMaterials[index];
  83780. if (mat.friction === friction && mat.restitution === restitution) {
  83781. return mat;
  83782. }
  83783. }
  83784. var currentMat = new this.BJSCANNON.Material(name);
  83785. currentMat.friction = friction;
  83786. currentMat.restitution = restitution;
  83787. this._physicsMaterials.push(currentMat);
  83788. return currentMat;
  83789. };
  83790. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83791. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83792. };
  83793. CannonJSPlugin.prototype._createShape = function (impostor) {
  83794. var object = impostor.object;
  83795. var returnValue;
  83796. var extendSize = impostor.getObjectExtendSize();
  83797. switch (impostor.type) {
  83798. case BABYLON.PhysicsImpostor.SphereImpostor:
  83799. var radiusX = extendSize.x;
  83800. var radiusY = extendSize.y;
  83801. var radiusZ = extendSize.z;
  83802. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83803. break;
  83804. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83805. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83806. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83807. break;
  83808. case BABYLON.PhysicsImpostor.BoxImpostor:
  83809. var box = extendSize.scale(0.5);
  83810. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83811. break;
  83812. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83813. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83814. returnValue = new this.BJSCANNON.Plane();
  83815. break;
  83816. case BABYLON.PhysicsImpostor.MeshImpostor:
  83817. // should transform the vertex data to world coordinates!!
  83818. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83819. var rawFaces = object.getIndices ? object.getIndices() : [];
  83820. if (!rawVerts)
  83821. return;
  83822. // get only scale! so the object could transform correctly.
  83823. var oldPosition = object.position.clone();
  83824. var oldRotation = object.rotation && object.rotation.clone();
  83825. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83826. object.position.copyFromFloats(0, 0, 0);
  83827. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83828. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83829. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83830. var transform = object.computeWorldMatrix(true);
  83831. // convert rawVerts to object space
  83832. var temp = new Array();
  83833. var index;
  83834. for (index = 0; index < rawVerts.length; index += 3) {
  83835. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83836. }
  83837. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83838. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83839. //now set back the transformation!
  83840. object.position.copyFrom(oldPosition);
  83841. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83842. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83843. break;
  83844. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83845. var oldPosition2 = object.position.clone();
  83846. var oldRotation2 = object.rotation && object.rotation.clone();
  83847. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83848. object.position.copyFromFloats(0, 0, 0);
  83849. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83850. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83851. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83852. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83853. returnValue = this._createHeightmap(object);
  83854. object.position.copyFrom(oldPosition2);
  83855. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83856. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83857. object.computeWorldMatrix(true);
  83858. break;
  83859. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83860. returnValue = new this.BJSCANNON.Particle();
  83861. break;
  83862. }
  83863. return returnValue;
  83864. };
  83865. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83866. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83867. var transform = object.computeWorldMatrix(true);
  83868. // convert rawVerts to object space
  83869. var temp = new Array();
  83870. var index;
  83871. for (index = 0; index < pos.length; index += 3) {
  83872. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83873. }
  83874. pos = temp;
  83875. var matrix = new Array();
  83876. //For now pointDepth will not be used and will be automatically calculated.
  83877. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83878. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83879. var boundingInfo = object.getBoundingInfo();
  83880. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83881. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83882. var elementSize = dim * 2 / arraySize;
  83883. for (var i = 0; i < pos.length; i = i + 3) {
  83884. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83885. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83886. var y = -pos[i + 2] + minY;
  83887. if (!matrix[x]) {
  83888. matrix[x] = [];
  83889. }
  83890. if (!matrix[x][z]) {
  83891. matrix[x][z] = y;
  83892. }
  83893. matrix[x][z] = Math.max(y, matrix[x][z]);
  83894. }
  83895. for (var x = 0; x <= arraySize; ++x) {
  83896. if (!matrix[x]) {
  83897. var loc = 1;
  83898. while (!matrix[(x + loc) % arraySize]) {
  83899. loc++;
  83900. }
  83901. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83902. //console.log("missing x", x);
  83903. }
  83904. for (var z = 0; z <= arraySize; ++z) {
  83905. if (!matrix[x][z]) {
  83906. var loc = 1;
  83907. var newValue;
  83908. while (newValue === undefined) {
  83909. newValue = matrix[x][(z + loc++) % arraySize];
  83910. }
  83911. matrix[x][z] = newValue;
  83912. }
  83913. }
  83914. }
  83915. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83916. elementSize: elementSize
  83917. });
  83918. //For future reference, needed for body transformation
  83919. shape.minY = minY;
  83920. return shape;
  83921. };
  83922. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83923. var object = impostor.object;
  83924. //make sure it is updated...
  83925. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83926. // The delta between the mesh position and the mesh bounding box center
  83927. var bInfo = object.getBoundingInfo();
  83928. if (!bInfo)
  83929. return;
  83930. var center = impostor.getObjectCenter();
  83931. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83932. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83933. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83934. this._tmpPosition.copyFrom(center);
  83935. var quaternion = object.rotationQuaternion;
  83936. if (!quaternion) {
  83937. return;
  83938. }
  83939. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83940. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83941. //-90 DEG in X, precalculated
  83942. quaternion = quaternion.multiply(this._minus90X);
  83943. //Invert! (Precalculated, 90 deg in X)
  83944. //No need to clone. this will never change.
  83945. impostor.setDeltaRotation(this._plus90X);
  83946. }
  83947. //If it is a heightfield, if should be centered.
  83948. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83949. var mesh = object;
  83950. var boundingInfo = mesh.getBoundingInfo();
  83951. //calculate the correct body position:
  83952. var rotationQuaternion = mesh.rotationQuaternion;
  83953. mesh.rotationQuaternion = this._tmpUnityRotation;
  83954. mesh.computeWorldMatrix(true);
  83955. //get original center with no rotation
  83956. var c = center.clone();
  83957. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83958. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83959. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83960. mesh.setPreTransformMatrix(p);
  83961. mesh.computeWorldMatrix(true);
  83962. //calculate the translation
  83963. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83964. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83965. //add it inverted to the delta
  83966. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83967. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83968. //rotation is back
  83969. mesh.rotationQuaternion = rotationQuaternion;
  83970. mesh.setPreTransformMatrix(oldPivot);
  83971. mesh.computeWorldMatrix(true);
  83972. }
  83973. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83974. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83975. //this._tmpPosition.copyFrom(object.position);
  83976. }
  83977. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83978. //Now update the impostor object
  83979. impostor.physicsBody.position.copy(this._tmpPosition);
  83980. impostor.physicsBody.quaternion.copy(quaternion);
  83981. };
  83982. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83983. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83984. if (impostor.object.rotationQuaternion) {
  83985. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83986. }
  83987. };
  83988. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83989. impostor.physicsBody.position.copy(newPosition);
  83990. impostor.physicsBody.quaternion.copy(newRotation);
  83991. };
  83992. CannonJSPlugin.prototype.isSupported = function () {
  83993. return this.BJSCANNON !== undefined;
  83994. };
  83995. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83996. impostor.physicsBody.velocity.copy(velocity);
  83997. };
  83998. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83999. impostor.physicsBody.angularVelocity.copy(velocity);
  84000. };
  84001. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84002. var v = impostor.physicsBody.velocity;
  84003. if (!v) {
  84004. return null;
  84005. }
  84006. return new BABYLON.Vector3(v.x, v.y, v.z);
  84007. };
  84008. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84009. var v = impostor.physicsBody.angularVelocity;
  84010. if (!v) {
  84011. return null;
  84012. }
  84013. return new BABYLON.Vector3(v.x, v.y, v.z);
  84014. };
  84015. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84016. impostor.physicsBody.mass = mass;
  84017. impostor.physicsBody.updateMassProperties();
  84018. };
  84019. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84020. return impostor.physicsBody.mass;
  84021. };
  84022. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84023. return impostor.physicsBody.material.friction;
  84024. };
  84025. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84026. impostor.physicsBody.material.friction = friction;
  84027. };
  84028. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84029. return impostor.physicsBody.material.restitution;
  84030. };
  84031. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84032. impostor.physicsBody.material.restitution = restitution;
  84033. };
  84034. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84035. impostor.physicsBody.sleep();
  84036. };
  84037. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84038. impostor.physicsBody.wakeUp();
  84039. };
  84040. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84041. joint.physicsJoint.distance = maxDistance;
  84042. };
  84043. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84044. // if (!motorIndex) {
  84045. // joint.physicsJoint.enableMotor();
  84046. // }
  84047. // }
  84048. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84049. // if (!motorIndex) {
  84050. // joint.physicsJoint.disableMotor();
  84051. // }
  84052. // }
  84053. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84054. if (!motorIndex) {
  84055. joint.physicsJoint.enableMotor();
  84056. joint.physicsJoint.setMotorSpeed(speed);
  84057. if (maxForce) {
  84058. this.setLimit(joint, maxForce);
  84059. }
  84060. }
  84061. };
  84062. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84063. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84064. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84065. };
  84066. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84067. var body = impostor.physicsBody;
  84068. mesh.position.x = body.position.x;
  84069. mesh.position.y = body.position.y;
  84070. mesh.position.z = body.position.z;
  84071. if (mesh.rotationQuaternion) {
  84072. mesh.rotationQuaternion.x = body.quaternion.x;
  84073. mesh.rotationQuaternion.y = body.quaternion.y;
  84074. mesh.rotationQuaternion.z = body.quaternion.z;
  84075. mesh.rotationQuaternion.w = body.quaternion.w;
  84076. }
  84077. };
  84078. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84079. var shape = impostor.physicsBody.shapes[0];
  84080. return shape.boundingSphereRadius;
  84081. };
  84082. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84083. var shape = impostor.physicsBody.shapes[0];
  84084. result.x = shape.halfExtents.x * 2;
  84085. result.y = shape.halfExtents.y * 2;
  84086. result.z = shape.halfExtents.z * 2;
  84087. };
  84088. CannonJSPlugin.prototype.dispose = function () {
  84089. };
  84090. CannonJSPlugin.prototype._extendNamespace = function () {
  84091. //this will force cannon to execute at least one step when using interpolation
  84092. var step_tmp1 = new this.BJSCANNON.Vec3();
  84093. var Engine = this.BJSCANNON;
  84094. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84095. maxSubSteps = maxSubSteps || 10;
  84096. timeSinceLastCalled = timeSinceLastCalled || 0;
  84097. if (timeSinceLastCalled === 0) {
  84098. this.internalStep(dt);
  84099. this.time += dt;
  84100. }
  84101. else {
  84102. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84103. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84104. var t0 = performance.now();
  84105. for (var i = 0; i !== internalSteps; i++) {
  84106. this.internalStep(dt);
  84107. if (performance.now() - t0 > dt * 1000) {
  84108. break;
  84109. }
  84110. }
  84111. this.time += timeSinceLastCalled;
  84112. var h = this.time % dt;
  84113. var h_div_dt = h / dt;
  84114. var interpvelo = step_tmp1;
  84115. var bodies = this.bodies;
  84116. for (var j = 0; j !== bodies.length; j++) {
  84117. var b = bodies[j];
  84118. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84119. b.position.vsub(b.previousPosition, interpvelo);
  84120. interpvelo.scale(h_div_dt, interpvelo);
  84121. b.position.vadd(interpvelo, b.interpolatedPosition);
  84122. }
  84123. else {
  84124. b.interpolatedPosition.copy(b.position);
  84125. b.interpolatedQuaternion.copy(b.quaternion);
  84126. }
  84127. }
  84128. }
  84129. };
  84130. };
  84131. return CannonJSPlugin;
  84132. }());
  84133. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84134. })(BABYLON || (BABYLON = {}));
  84135. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84136. var BABYLON;
  84137. (function (BABYLON) {
  84138. var OimoJSPlugin = /** @class */ (function () {
  84139. function OimoJSPlugin(iterations) {
  84140. this.name = "OimoJSPlugin";
  84141. this._tmpImpostorsArray = [];
  84142. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84143. this.BJSOIMO = OIMO;
  84144. this.world = new this.BJSOIMO.World({
  84145. iterations: iterations
  84146. });
  84147. this.world.clear();
  84148. }
  84149. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84150. this.world.gravity.copy(gravity);
  84151. };
  84152. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84153. this.world.timeStep = timeStep;
  84154. };
  84155. OimoJSPlugin.prototype.getTimeStep = function () {
  84156. return this.world.timeStep;
  84157. };
  84158. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84159. var _this = this;
  84160. impostors.forEach(function (impostor) {
  84161. impostor.beforeStep();
  84162. });
  84163. this.world.step();
  84164. impostors.forEach(function (impostor) {
  84165. impostor.afterStep();
  84166. //update the ordered impostors array
  84167. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84168. });
  84169. //check for collisions
  84170. var contact = this.world.contacts;
  84171. while (contact !== null) {
  84172. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84173. contact = contact.next;
  84174. continue;
  84175. }
  84176. //is this body colliding with any other? get the impostor
  84177. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84178. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84179. if (!mainImpostor || !collidingImpostor) {
  84180. contact = contact.next;
  84181. continue;
  84182. }
  84183. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84184. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84185. contact = contact.next;
  84186. }
  84187. };
  84188. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84189. var mass = impostor.physicsBody.mass;
  84190. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84191. };
  84192. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84193. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84194. this.applyImpulse(impostor, force, contactPoint);
  84195. };
  84196. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84197. var _this = this;
  84198. //parent-child relationship. Does this impostor has a parent impostor?
  84199. if (impostor.parent) {
  84200. if (impostor.physicsBody) {
  84201. this.removePhysicsBody(impostor);
  84202. //TODO is that needed?
  84203. impostor.forceUpdate();
  84204. }
  84205. return;
  84206. }
  84207. if (impostor.isBodyInitRequired()) {
  84208. var bodyConfig = {
  84209. name: impostor.uniqueId,
  84210. //Oimo must have mass, also for static objects.
  84211. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84212. size: [],
  84213. type: [],
  84214. pos: [],
  84215. posShape: [],
  84216. rot: [],
  84217. rotShape: [],
  84218. move: impostor.getParam("mass") !== 0,
  84219. density: impostor.getParam("mass"),
  84220. friction: impostor.getParam("friction"),
  84221. restitution: impostor.getParam("restitution"),
  84222. //Supporting older versions of Oimo
  84223. world: this.world
  84224. };
  84225. var impostors = [impostor];
  84226. var addToArray = function (parent) {
  84227. if (!parent.getChildMeshes)
  84228. return;
  84229. parent.getChildMeshes().forEach(function (m) {
  84230. if (m.physicsImpostor) {
  84231. impostors.push(m.physicsImpostor);
  84232. //m.physicsImpostor._init();
  84233. }
  84234. });
  84235. };
  84236. addToArray(impostor.object);
  84237. var checkWithEpsilon_1 = function (value) {
  84238. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84239. };
  84240. impostors.forEach(function (i) {
  84241. if (!i.object.rotationQuaternion) {
  84242. return;
  84243. }
  84244. //get the correct bounding box
  84245. var oldQuaternion = i.object.rotationQuaternion;
  84246. var rot = oldQuaternion.toEulerAngles();
  84247. var extendSize = i.getObjectExtendSize();
  84248. var radToDeg = 57.295779513082320876;
  84249. if (i === impostor) {
  84250. var center = impostor.getObjectCenter();
  84251. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84252. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84253. //Can also use Array.prototype.push.apply
  84254. bodyConfig.pos.push(center.x);
  84255. bodyConfig.pos.push(center.y);
  84256. bodyConfig.pos.push(center.z);
  84257. bodyConfig.posShape.push(0, 0, 0);
  84258. //tmp solution
  84259. bodyConfig.rot.push(rot.x * radToDeg);
  84260. bodyConfig.rot.push(rot.y * radToDeg);
  84261. bodyConfig.rot.push(rot.z * radToDeg);
  84262. bodyConfig.rotShape.push(0, 0, 0);
  84263. }
  84264. else {
  84265. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84266. bodyConfig.posShape.push(localPosition.x);
  84267. bodyConfig.posShape.push(localPosition.y);
  84268. bodyConfig.posShape.push(localPosition.z);
  84269. bodyConfig.pos.push(0, 0, 0);
  84270. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84271. bodyConfig.rot.push(0);
  84272. bodyConfig.rot.push(0);
  84273. bodyConfig.rot.push(0);
  84274. bodyConfig.rotShape.push(rot.x * radToDeg);
  84275. bodyConfig.rotShape.push(rot.y * radToDeg);
  84276. bodyConfig.rotShape.push(rot.z * radToDeg);
  84277. }
  84278. // register mesh
  84279. switch (i.type) {
  84280. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84281. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84282. case BABYLON.PhysicsImpostor.SphereImpostor:
  84283. var radiusX = extendSize.x;
  84284. var radiusY = extendSize.y;
  84285. var radiusZ = extendSize.z;
  84286. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84287. bodyConfig.type.push('sphere');
  84288. //due to the way oimo works with compounds, add 3 times
  84289. bodyConfig.size.push(size);
  84290. bodyConfig.size.push(size);
  84291. bodyConfig.size.push(size);
  84292. break;
  84293. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84294. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84295. var sizeY = checkWithEpsilon_1(extendSize.y);
  84296. bodyConfig.type.push('cylinder');
  84297. bodyConfig.size.push(sizeX);
  84298. bodyConfig.size.push(sizeY);
  84299. //due to the way oimo works with compounds, add one more value.
  84300. bodyConfig.size.push(sizeY);
  84301. break;
  84302. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84303. case BABYLON.PhysicsImpostor.BoxImpostor:
  84304. default:
  84305. var sizeX = checkWithEpsilon_1(extendSize.x);
  84306. var sizeY = checkWithEpsilon_1(extendSize.y);
  84307. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84308. bodyConfig.type.push('box');
  84309. //if (i === impostor) {
  84310. bodyConfig.size.push(sizeX);
  84311. bodyConfig.size.push(sizeY);
  84312. bodyConfig.size.push(sizeZ);
  84313. //} else {
  84314. // bodyConfig.size.push(0,0,0);
  84315. //}
  84316. break;
  84317. }
  84318. //actually not needed, but hey...
  84319. i.object.rotationQuaternion = oldQuaternion;
  84320. });
  84321. impostor.physicsBody = this.world.add(bodyConfig);
  84322. }
  84323. else {
  84324. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84325. }
  84326. impostor.setDeltaPosition(this._tmpPositionVector);
  84327. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84328. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84329. };
  84330. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84331. //impostor.physicsBody.dispose();
  84332. //Same as : (older oimo versions)
  84333. this.world.removeRigidBody(impostor.physicsBody);
  84334. };
  84335. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84336. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84337. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84338. if (!mainBody || !connectedBody) {
  84339. return;
  84340. }
  84341. var jointData = impostorJoint.joint.jointData;
  84342. var options = jointData.nativeParams || {};
  84343. var type;
  84344. var nativeJointData = {
  84345. body1: mainBody,
  84346. body2: connectedBody,
  84347. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84348. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84349. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84350. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84351. min: options.min,
  84352. max: options.max,
  84353. collision: options.collision || jointData.collision,
  84354. spring: options.spring,
  84355. //supporting older version of Oimo
  84356. world: this.world
  84357. };
  84358. switch (impostorJoint.joint.type) {
  84359. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84360. type = "jointBall";
  84361. break;
  84362. case BABYLON.PhysicsJoint.SpringJoint:
  84363. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84364. var springData = jointData;
  84365. nativeJointData.min = springData.length || nativeJointData.min;
  84366. //Max should also be set, just make sure it is at least min
  84367. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84368. case BABYLON.PhysicsJoint.DistanceJoint:
  84369. type = "jointDistance";
  84370. nativeJointData.max = jointData.maxDistance;
  84371. break;
  84372. case BABYLON.PhysicsJoint.PrismaticJoint:
  84373. type = "jointPrisme";
  84374. break;
  84375. case BABYLON.PhysicsJoint.SliderJoint:
  84376. type = "jointSlide";
  84377. break;
  84378. case BABYLON.PhysicsJoint.WheelJoint:
  84379. type = "jointWheel";
  84380. break;
  84381. case BABYLON.PhysicsJoint.HingeJoint:
  84382. default:
  84383. type = "jointHinge";
  84384. break;
  84385. }
  84386. nativeJointData.type = type;
  84387. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84388. };
  84389. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84390. //Bug in Oimo prevents us from disposing a joint in the playground
  84391. //joint.joint.physicsJoint.dispose();
  84392. //So we will bruteforce it!
  84393. try {
  84394. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84395. }
  84396. catch (e) {
  84397. BABYLON.Tools.Warn(e);
  84398. }
  84399. };
  84400. OimoJSPlugin.prototype.isSupported = function () {
  84401. return this.BJSOIMO !== undefined;
  84402. };
  84403. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84404. if (!impostor.physicsBody.sleeping) {
  84405. //TODO check that
  84406. /*if (impostor.physicsBody.shapes.next) {
  84407. var parentShape = this._getLastShape(impostor.physicsBody);
  84408. impostor.object.position.copyFrom(parentShape.position);
  84409. console.log(parentShape.position);
  84410. } else {*/
  84411. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84412. //}
  84413. if (impostor.object.rotationQuaternion) {
  84414. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84415. }
  84416. }
  84417. };
  84418. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84419. var body = impostor.physicsBody;
  84420. body.position.copy(newPosition);
  84421. body.orientation.copy(newRotation);
  84422. body.syncShapes();
  84423. body.awake();
  84424. };
  84425. /*private _getLastShape(body: any): any {
  84426. var lastShape = body.shapes;
  84427. while (lastShape.next) {
  84428. lastShape = lastShape.next;
  84429. }
  84430. return lastShape;
  84431. }*/
  84432. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84433. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84434. };
  84435. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84436. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84437. };
  84438. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84439. var v = impostor.physicsBody.linearVelocity;
  84440. if (!v) {
  84441. return null;
  84442. }
  84443. return new BABYLON.Vector3(v.x, v.y, v.z);
  84444. };
  84445. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84446. var v = impostor.physicsBody.angularVelocity;
  84447. if (!v) {
  84448. return null;
  84449. }
  84450. return new BABYLON.Vector3(v.x, v.y, v.z);
  84451. };
  84452. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84453. var staticBody = mass === 0;
  84454. //this will actually set the body's density and not its mass.
  84455. //But this is how oimo treats the mass variable.
  84456. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84457. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84458. };
  84459. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84460. return impostor.physicsBody.shapes.density;
  84461. };
  84462. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84463. return impostor.physicsBody.shapes.friction;
  84464. };
  84465. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84466. impostor.physicsBody.shapes.friction = friction;
  84467. };
  84468. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84469. return impostor.physicsBody.shapes.restitution;
  84470. };
  84471. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84472. impostor.physicsBody.shapes.restitution = restitution;
  84473. };
  84474. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84475. impostor.physicsBody.sleep();
  84476. };
  84477. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84478. impostor.physicsBody.awake();
  84479. };
  84480. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84481. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84482. if (minDistance !== void 0) {
  84483. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84484. }
  84485. };
  84486. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84487. //TODO separate rotational and transational motors.
  84488. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84489. if (motor) {
  84490. motor.setMotor(speed, maxForce);
  84491. }
  84492. };
  84493. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84494. //TODO separate rotational and transational motors.
  84495. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84496. if (motor) {
  84497. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84498. }
  84499. };
  84500. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84501. var body = impostor.physicsBody;
  84502. mesh.position.x = body.position.x;
  84503. mesh.position.y = body.position.y;
  84504. mesh.position.z = body.position.z;
  84505. if (mesh.rotationQuaternion) {
  84506. mesh.rotationQuaternion.x = body.orientation.x;
  84507. mesh.rotationQuaternion.y = body.orientation.y;
  84508. mesh.rotationQuaternion.z = body.orientation.z;
  84509. mesh.rotationQuaternion.w = body.orientation.s;
  84510. }
  84511. };
  84512. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84513. return impostor.physicsBody.shapes.radius;
  84514. };
  84515. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84516. var shape = impostor.physicsBody.shapes;
  84517. result.x = shape.halfWidth * 2;
  84518. result.y = shape.halfHeight * 2;
  84519. result.z = shape.halfDepth * 2;
  84520. };
  84521. OimoJSPlugin.prototype.dispose = function () {
  84522. this.world.clear();
  84523. };
  84524. return OimoJSPlugin;
  84525. }());
  84526. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84527. })(BABYLON || (BABYLON = {}));
  84528. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84529. var BABYLON;
  84530. (function (BABYLON) {
  84531. /*
  84532. * Based on jsTGALoader - Javascript loader for TGA file
  84533. * By Vincent Thibault
  84534. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84535. */
  84536. var TGATools = /** @class */ (function () {
  84537. function TGATools() {
  84538. }
  84539. TGATools.GetTGAHeader = function (data) {
  84540. var offset = 0;
  84541. var header = {
  84542. id_length: data[offset++],
  84543. colormap_type: data[offset++],
  84544. image_type: data[offset++],
  84545. colormap_index: data[offset++] | data[offset++] << 8,
  84546. colormap_length: data[offset++] | data[offset++] << 8,
  84547. colormap_size: data[offset++],
  84548. origin: [
  84549. data[offset++] | data[offset++] << 8,
  84550. data[offset++] | data[offset++] << 8
  84551. ],
  84552. width: data[offset++] | data[offset++] << 8,
  84553. height: data[offset++] | data[offset++] << 8,
  84554. pixel_size: data[offset++],
  84555. flags: data[offset++]
  84556. };
  84557. return header;
  84558. };
  84559. TGATools.UploadContent = function (gl, data) {
  84560. // Not enough data to contain header ?
  84561. if (data.length < 19) {
  84562. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84563. return;
  84564. }
  84565. // Read Header
  84566. var offset = 18;
  84567. var header = TGATools.GetTGAHeader(data);
  84568. // Assume it's a valid Targa file.
  84569. if (header.id_length + offset > data.length) {
  84570. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84571. return;
  84572. }
  84573. // Skip not needed data
  84574. offset += header.id_length;
  84575. var use_rle = false;
  84576. var use_pal = false;
  84577. var use_grey = false;
  84578. // Get some informations.
  84579. switch (header.image_type) {
  84580. case TGATools._TYPE_RLE_INDEXED:
  84581. use_rle = true;
  84582. case TGATools._TYPE_INDEXED:
  84583. use_pal = true;
  84584. break;
  84585. case TGATools._TYPE_RLE_RGB:
  84586. use_rle = true;
  84587. case TGATools._TYPE_RGB:
  84588. // use_rgb = true;
  84589. break;
  84590. case TGATools._TYPE_RLE_GREY:
  84591. use_rle = true;
  84592. case TGATools._TYPE_GREY:
  84593. use_grey = true;
  84594. break;
  84595. }
  84596. var pixel_data;
  84597. // var numAlphaBits = header.flags & 0xf;
  84598. var pixel_size = header.pixel_size >> 3;
  84599. var pixel_total = header.width * header.height * pixel_size;
  84600. // Read palettes
  84601. var palettes;
  84602. if (use_pal) {
  84603. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84604. }
  84605. // Read LRE
  84606. if (use_rle) {
  84607. pixel_data = new Uint8Array(pixel_total);
  84608. var c, count, i;
  84609. var localOffset = 0;
  84610. var pixels = new Uint8Array(pixel_size);
  84611. while (offset < pixel_total && localOffset < pixel_total) {
  84612. c = data[offset++];
  84613. count = (c & 0x7f) + 1;
  84614. // RLE pixels
  84615. if (c & 0x80) {
  84616. // Bind pixel tmp array
  84617. for (i = 0; i < pixel_size; ++i) {
  84618. pixels[i] = data[offset++];
  84619. }
  84620. // Copy pixel array
  84621. for (i = 0; i < count; ++i) {
  84622. pixel_data.set(pixels, localOffset + i * pixel_size);
  84623. }
  84624. localOffset += pixel_size * count;
  84625. }
  84626. // Raw pixels
  84627. else {
  84628. count *= pixel_size;
  84629. for (i = 0; i < count; ++i) {
  84630. pixel_data[localOffset + i] = data[offset++];
  84631. }
  84632. localOffset += count;
  84633. }
  84634. }
  84635. }
  84636. // RAW Pixels
  84637. else {
  84638. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84639. }
  84640. // Load to texture
  84641. var x_start, y_start, x_step, y_step, y_end, x_end;
  84642. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84643. default:
  84644. case TGATools._ORIGIN_UL:
  84645. x_start = 0;
  84646. x_step = 1;
  84647. x_end = header.width;
  84648. y_start = 0;
  84649. y_step = 1;
  84650. y_end = header.height;
  84651. break;
  84652. case TGATools._ORIGIN_BL:
  84653. x_start = 0;
  84654. x_step = 1;
  84655. x_end = header.width;
  84656. y_start = header.height - 1;
  84657. y_step = -1;
  84658. y_end = -1;
  84659. break;
  84660. case TGATools._ORIGIN_UR:
  84661. x_start = header.width - 1;
  84662. x_step = -1;
  84663. x_end = -1;
  84664. y_start = 0;
  84665. y_step = 1;
  84666. y_end = header.height;
  84667. break;
  84668. case TGATools._ORIGIN_BR:
  84669. x_start = header.width - 1;
  84670. x_step = -1;
  84671. x_end = -1;
  84672. y_start = header.height - 1;
  84673. y_step = -1;
  84674. y_end = -1;
  84675. break;
  84676. }
  84677. // Load the specify method
  84678. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84679. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84680. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84681. };
  84682. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84683. var image = pixel_data, colormap = palettes;
  84684. var width = header.width, height = header.height;
  84685. var color, i = 0, x, y;
  84686. var imageData = new Uint8Array(width * height * 4);
  84687. for (y = y_start; y !== y_end; y += y_step) {
  84688. for (x = x_start; x !== x_end; x += x_step, i++) {
  84689. color = image[i];
  84690. imageData[(x + width * y) * 4 + 3] = 255;
  84691. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84692. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84693. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84694. }
  84695. }
  84696. return imageData;
  84697. };
  84698. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84699. var image = pixel_data;
  84700. var width = header.width, height = header.height;
  84701. var color, i = 0, x, y;
  84702. var imageData = new Uint8Array(width * height * 4);
  84703. for (y = y_start; y !== y_end; y += y_step) {
  84704. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84705. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84706. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84707. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84708. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84709. imageData[(x + width * y) * 4 + 0] = r;
  84710. imageData[(x + width * y) * 4 + 1] = g;
  84711. imageData[(x + width * y) * 4 + 2] = b;
  84712. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84713. }
  84714. }
  84715. return imageData;
  84716. };
  84717. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84718. var image = pixel_data;
  84719. var width = header.width, height = header.height;
  84720. var i = 0, x, y;
  84721. var imageData = new Uint8Array(width * height * 4);
  84722. for (y = y_start; y !== y_end; y += y_step) {
  84723. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84724. imageData[(x + width * y) * 4 + 3] = 255;
  84725. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84726. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84727. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84728. }
  84729. }
  84730. return imageData;
  84731. };
  84732. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84733. var image = pixel_data;
  84734. var width = header.width, height = header.height;
  84735. var i = 0, x, y;
  84736. var imageData = new Uint8Array(width * height * 4);
  84737. for (y = y_start; y !== y_end; y += y_step) {
  84738. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84739. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84740. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84741. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84742. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84743. }
  84744. }
  84745. return imageData;
  84746. };
  84747. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84748. var image = pixel_data;
  84749. var width = header.width, height = header.height;
  84750. var color, i = 0, x, y;
  84751. var imageData = new Uint8Array(width * height * 4);
  84752. for (y = y_start; y !== y_end; y += y_step) {
  84753. for (x = x_start; x !== x_end; x += x_step, i++) {
  84754. color = image[i];
  84755. imageData[(x + width * y) * 4 + 0] = color;
  84756. imageData[(x + width * y) * 4 + 1] = color;
  84757. imageData[(x + width * y) * 4 + 2] = color;
  84758. imageData[(x + width * y) * 4 + 3] = 255;
  84759. }
  84760. }
  84761. return imageData;
  84762. };
  84763. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84764. var image = pixel_data;
  84765. var width = header.width, height = header.height;
  84766. var i = 0, x, y;
  84767. var imageData = new Uint8Array(width * height * 4);
  84768. for (y = y_start; y !== y_end; y += y_step) {
  84769. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84770. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84771. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84772. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84773. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84774. }
  84775. }
  84776. return imageData;
  84777. };
  84778. //private static _TYPE_NO_DATA = 0;
  84779. TGATools._TYPE_INDEXED = 1;
  84780. TGATools._TYPE_RGB = 2;
  84781. TGATools._TYPE_GREY = 3;
  84782. TGATools._TYPE_RLE_INDEXED = 9;
  84783. TGATools._TYPE_RLE_RGB = 10;
  84784. TGATools._TYPE_RLE_GREY = 11;
  84785. TGATools._ORIGIN_MASK = 0x30;
  84786. TGATools._ORIGIN_SHIFT = 0x04;
  84787. TGATools._ORIGIN_BL = 0x00;
  84788. TGATools._ORIGIN_BR = 0x01;
  84789. TGATools._ORIGIN_UL = 0x02;
  84790. TGATools._ORIGIN_UR = 0x03;
  84791. return TGATools;
  84792. }());
  84793. BABYLON.TGATools = TGATools;
  84794. })(BABYLON || (BABYLON = {}));
  84795. //# sourceMappingURL=babylon.tga.js.map
  84796. var BABYLON;
  84797. (function (BABYLON) {
  84798. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84799. // All values and structures referenced from:
  84800. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84801. var DDS_MAGIC = 0x20534444;
  84802. var
  84803. //DDSD_CAPS = 0x1,
  84804. //DDSD_HEIGHT = 0x2,
  84805. //DDSD_WIDTH = 0x4,
  84806. //DDSD_PITCH = 0x8,
  84807. //DDSD_PIXELFORMAT = 0x1000,
  84808. DDSD_MIPMAPCOUNT = 0x20000;
  84809. //DDSD_LINEARSIZE = 0x80000,
  84810. //DDSD_DEPTH = 0x800000;
  84811. // var DDSCAPS_COMPLEX = 0x8,
  84812. // DDSCAPS_MIPMAP = 0x400000,
  84813. // DDSCAPS_TEXTURE = 0x1000;
  84814. var DDSCAPS2_CUBEMAP = 0x200;
  84815. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84816. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84817. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84818. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84819. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84820. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84821. // DDSCAPS2_VOLUME = 0x200000;
  84822. var
  84823. //DDPF_ALPHAPIXELS = 0x1,
  84824. //DDPF_ALPHA = 0x2,
  84825. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84826. //DDPF_YUV = 0x200,
  84827. DDPF_LUMINANCE = 0x20000;
  84828. function FourCCToInt32(value) {
  84829. return value.charCodeAt(0) +
  84830. (value.charCodeAt(1) << 8) +
  84831. (value.charCodeAt(2) << 16) +
  84832. (value.charCodeAt(3) << 24);
  84833. }
  84834. function Int32ToFourCC(value) {
  84835. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84836. }
  84837. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84838. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84839. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84840. var FOURCC_DX10 = FourCCToInt32("DX10");
  84841. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84842. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84843. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84844. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84845. var headerLengthInt = 31; // The header length in 32 bit ints
  84846. // Offsets into the header array
  84847. var off_magic = 0;
  84848. var off_size = 1;
  84849. var off_flags = 2;
  84850. var off_height = 3;
  84851. var off_width = 4;
  84852. var off_mipmapCount = 7;
  84853. var off_pfFlags = 20;
  84854. var off_pfFourCC = 21;
  84855. var off_RGBbpp = 22;
  84856. var off_RMask = 23;
  84857. var off_GMask = 24;
  84858. var off_BMask = 25;
  84859. var off_AMask = 26;
  84860. // var off_caps1 = 27;
  84861. var off_caps2 = 28;
  84862. // var off_caps3 = 29;
  84863. // var off_caps4 = 30;
  84864. var off_dxgiFormat = 32;
  84865. ;
  84866. var DDSTools = /** @class */ (function () {
  84867. function DDSTools() {
  84868. }
  84869. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84870. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84871. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84872. var mipmapCount = 1;
  84873. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84874. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84875. }
  84876. var fourCC = header[off_pfFourCC];
  84877. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84878. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84879. switch (fourCC) {
  84880. case FOURCC_D3DFMT_R16G16B16A16F:
  84881. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84882. break;
  84883. case FOURCC_D3DFMT_R32G32B32A32F:
  84884. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84885. break;
  84886. case FOURCC_DX10:
  84887. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84888. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84889. break;
  84890. }
  84891. }
  84892. return {
  84893. width: header[off_width],
  84894. height: header[off_height],
  84895. mipmapCount: mipmapCount,
  84896. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84897. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84898. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84899. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84900. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84901. dxgiFormat: dxgiFormat,
  84902. textureType: textureType
  84903. };
  84904. };
  84905. DDSTools._ToHalfFloat = function (value) {
  84906. if (!DDSTools._FloatView) {
  84907. DDSTools._FloatView = new Float32Array(1);
  84908. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84909. }
  84910. DDSTools._FloatView[0] = value;
  84911. var x = DDSTools._Int32View[0];
  84912. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84913. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84914. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84915. /* If zero, or denormal, or exponent underflows too much for a denormal
  84916. * half, return signed zero. */
  84917. if (e < 103) {
  84918. return bits;
  84919. }
  84920. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84921. if (e > 142) {
  84922. bits |= 0x7c00;
  84923. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84924. * not Inf, so make sure we set one mantissa bit too. */
  84925. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84926. return bits;
  84927. }
  84928. /* If exponent underflows but not too much, return a denormal */
  84929. if (e < 113) {
  84930. m |= 0x0800;
  84931. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84932. * to 1, which is OK. */
  84933. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84934. return bits;
  84935. }
  84936. bits |= ((e - 112) << 10) | (m >> 1);
  84937. bits += m & 1;
  84938. return bits;
  84939. };
  84940. DDSTools._FromHalfFloat = function (value) {
  84941. var s = (value & 0x8000) >> 15;
  84942. var e = (value & 0x7C00) >> 10;
  84943. var f = value & 0x03FF;
  84944. if (e === 0) {
  84945. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84946. }
  84947. else if (e == 0x1F) {
  84948. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84949. }
  84950. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84951. };
  84952. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84953. var destArray = new Float32Array(dataLength);
  84954. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84955. var index = 0;
  84956. for (var y = 0; y < height; y++) {
  84957. for (var x = 0; x < width; x++) {
  84958. var srcPos = (x + y * width) * 4;
  84959. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84960. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84961. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84962. if (DDSTools.StoreLODInAlphaChannel) {
  84963. destArray[index + 3] = lod;
  84964. }
  84965. else {
  84966. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84967. }
  84968. index += 4;
  84969. }
  84970. }
  84971. return destArray;
  84972. };
  84973. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84974. if (DDSTools.StoreLODInAlphaChannel) {
  84975. var destArray = new Uint16Array(dataLength);
  84976. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84977. var index = 0;
  84978. for (var y = 0; y < height; y++) {
  84979. for (var x = 0; x < width; x++) {
  84980. var srcPos = (x + y * width) * 4;
  84981. destArray[index] = srcData[srcPos];
  84982. destArray[index + 1] = srcData[srcPos + 1];
  84983. destArray[index + 2] = srcData[srcPos + 2];
  84984. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84985. index += 4;
  84986. }
  84987. }
  84988. return destArray;
  84989. }
  84990. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84991. };
  84992. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84993. if (DDSTools.StoreLODInAlphaChannel) {
  84994. var destArray = new Float32Array(dataLength);
  84995. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84996. var index = 0;
  84997. for (var y = 0; y < height; y++) {
  84998. for (var x = 0; x < width; x++) {
  84999. var srcPos = (x + y * width) * 4;
  85000. destArray[index] = srcData[srcPos];
  85001. destArray[index + 1] = srcData[srcPos + 1];
  85002. destArray[index + 2] = srcData[srcPos + 2];
  85003. destArray[index + 3] = lod;
  85004. index += 4;
  85005. }
  85006. }
  85007. return destArray;
  85008. }
  85009. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85010. };
  85011. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85012. var destArray = new Uint8Array(dataLength);
  85013. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85014. var index = 0;
  85015. for (var y = 0; y < height; y++) {
  85016. for (var x = 0; x < width; x++) {
  85017. var srcPos = (x + y * width) * 4;
  85018. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85019. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85020. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85021. if (DDSTools.StoreLODInAlphaChannel) {
  85022. destArray[index + 3] = lod;
  85023. }
  85024. else {
  85025. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85026. }
  85027. index += 4;
  85028. }
  85029. }
  85030. return destArray;
  85031. };
  85032. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85033. var destArray = new Uint8Array(dataLength);
  85034. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85035. var index = 0;
  85036. for (var y = 0; y < height; y++) {
  85037. for (var x = 0; x < width; x++) {
  85038. var srcPos = (x + y * width) * 4;
  85039. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85040. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85041. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85042. if (DDSTools.StoreLODInAlphaChannel) {
  85043. destArray[index + 3] = lod;
  85044. }
  85045. else {
  85046. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85047. }
  85048. index += 4;
  85049. }
  85050. }
  85051. return destArray;
  85052. };
  85053. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85054. var byteArray = new Uint8Array(dataLength);
  85055. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85056. var index = 0;
  85057. for (var y = 0; y < height; y++) {
  85058. for (var x = 0; x < width; x++) {
  85059. var srcPos = (x + y * width) * 4;
  85060. byteArray[index] = srcData[srcPos + rOffset];
  85061. byteArray[index + 1] = srcData[srcPos + gOffset];
  85062. byteArray[index + 2] = srcData[srcPos + bOffset];
  85063. byteArray[index + 3] = srcData[srcPos + aOffset];
  85064. index += 4;
  85065. }
  85066. }
  85067. return byteArray;
  85068. };
  85069. DDSTools._ExtractLongWordOrder = function (value) {
  85070. if (value === 0 || value === 255 || value === -16777216) {
  85071. return 0;
  85072. }
  85073. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85074. };
  85075. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85076. var byteArray = new Uint8Array(dataLength);
  85077. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85078. var index = 0;
  85079. for (var y = 0; y < height; y++) {
  85080. for (var x = 0; x < width; x++) {
  85081. var srcPos = (x + y * width) * 3;
  85082. byteArray[index] = srcData[srcPos + rOffset];
  85083. byteArray[index + 1] = srcData[srcPos + gOffset];
  85084. byteArray[index + 2] = srcData[srcPos + bOffset];
  85085. index += 3;
  85086. }
  85087. }
  85088. return byteArray;
  85089. };
  85090. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85091. var byteArray = new Uint8Array(dataLength);
  85092. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85093. var index = 0;
  85094. for (var y = 0; y < height; y++) {
  85095. for (var x = 0; x < width; x++) {
  85096. var srcPos = (x + y * width);
  85097. byteArray[index] = srcData[srcPos];
  85098. index++;
  85099. }
  85100. }
  85101. return byteArray;
  85102. };
  85103. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85104. if (lodIndex === void 0) { lodIndex = -1; }
  85105. var sphericalPolynomialFaces = null;
  85106. if (info.sphericalPolynomial) {
  85107. sphericalPolynomialFaces = new Array();
  85108. }
  85109. var ext = engine.getCaps().s3tc;
  85110. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85111. var fourCC, width, height, dataLength = 0, dataOffset;
  85112. var byteArray, mipmapCount, mip;
  85113. var internalFormat = 0;
  85114. var format = 0;
  85115. var blockBytes = 1;
  85116. if (header[off_magic] !== DDS_MAGIC) {
  85117. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85118. return;
  85119. }
  85120. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85121. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85122. return;
  85123. }
  85124. if (info.isCompressed && !ext) {
  85125. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85126. return;
  85127. }
  85128. var bpp = header[off_RGBbpp];
  85129. dataOffset = header[off_size] + 4;
  85130. var computeFormats = false;
  85131. if (info.isFourCC) {
  85132. fourCC = header[off_pfFourCC];
  85133. switch (fourCC) {
  85134. case FOURCC_DXT1:
  85135. blockBytes = 8;
  85136. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85137. break;
  85138. case FOURCC_DXT3:
  85139. blockBytes = 16;
  85140. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85141. break;
  85142. case FOURCC_DXT5:
  85143. blockBytes = 16;
  85144. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85145. break;
  85146. case FOURCC_D3DFMT_R16G16B16A16F:
  85147. computeFormats = true;
  85148. break;
  85149. case FOURCC_D3DFMT_R32G32B32A32F:
  85150. computeFormats = true;
  85151. break;
  85152. case FOURCC_DX10:
  85153. // There is an additionnal header so dataOffset need to be changed
  85154. dataOffset += 5 * 4; // 5 uints
  85155. var supported = false;
  85156. switch (info.dxgiFormat) {
  85157. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85158. computeFormats = true;
  85159. supported = true;
  85160. break;
  85161. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85162. info.isRGB = true;
  85163. info.isFourCC = false;
  85164. bpp = 32;
  85165. supported = true;
  85166. break;
  85167. }
  85168. if (supported) {
  85169. break;
  85170. }
  85171. default:
  85172. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85173. return;
  85174. }
  85175. }
  85176. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85177. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85178. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85179. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85180. if (computeFormats) {
  85181. format = engine._getWebGLTextureType(info.textureType);
  85182. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85183. }
  85184. mipmapCount = 1;
  85185. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85186. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85187. }
  85188. for (var face = 0; face < faces; face++) {
  85189. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85190. width = header[off_width];
  85191. height = header[off_height];
  85192. for (mip = 0; mip < mipmapCount; ++mip) {
  85193. if (lodIndex === -1 || lodIndex === mip) {
  85194. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85195. var i = (lodIndex === -1) ? mip : 0;
  85196. if (!info.isCompressed && info.isFourCC) {
  85197. dataLength = width * height * 4;
  85198. var floatArray = null;
  85199. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85200. if (bpp === 128) {
  85201. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85202. if (sphericalPolynomialFaces && i == 0) {
  85203. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85204. }
  85205. }
  85206. else if (bpp === 64) {
  85207. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85208. if (sphericalPolynomialFaces && i == 0) {
  85209. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85210. }
  85211. }
  85212. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85213. format = engine._getWebGLTextureType(info.textureType);
  85214. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85215. }
  85216. else {
  85217. if (bpp === 128) {
  85218. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85219. if (sphericalPolynomialFaces && i == 0) {
  85220. sphericalPolynomialFaces.push(floatArray);
  85221. }
  85222. }
  85223. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85224. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85225. if (sphericalPolynomialFaces && i == 0) {
  85226. sphericalPolynomialFaces.push(floatArray);
  85227. }
  85228. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85229. format = engine._getWebGLTextureType(info.textureType);
  85230. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85231. }
  85232. else { // 64
  85233. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85234. if (sphericalPolynomialFaces && i == 0) {
  85235. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85236. }
  85237. }
  85238. }
  85239. if (floatArray) {
  85240. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85241. }
  85242. }
  85243. else if (info.isRGB) {
  85244. if (bpp === 24) {
  85245. dataLength = width * height * 3;
  85246. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85247. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85248. }
  85249. else { // 32
  85250. dataLength = width * height * 4;
  85251. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85252. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85253. }
  85254. }
  85255. else if (info.isLuminance) {
  85256. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85257. var unpaddedRowSize = width;
  85258. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85259. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85260. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85261. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85262. }
  85263. else {
  85264. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85265. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85266. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85267. }
  85268. }
  85269. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85270. width *= 0.5;
  85271. height *= 0.5;
  85272. width = Math.max(1.0, width);
  85273. height = Math.max(1.0, height);
  85274. }
  85275. if (currentFace !== undefined) {
  85276. // Loading a single face
  85277. break;
  85278. }
  85279. }
  85280. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85281. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85282. size: header[off_width],
  85283. right: sphericalPolynomialFaces[0],
  85284. left: sphericalPolynomialFaces[1],
  85285. up: sphericalPolynomialFaces[2],
  85286. down: sphericalPolynomialFaces[3],
  85287. front: sphericalPolynomialFaces[4],
  85288. back: sphericalPolynomialFaces[5],
  85289. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85290. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85291. gammaSpace: false,
  85292. });
  85293. }
  85294. else {
  85295. info.sphericalPolynomial = undefined;
  85296. }
  85297. };
  85298. DDSTools.StoreLODInAlphaChannel = false;
  85299. return DDSTools;
  85300. }());
  85301. BABYLON.DDSTools = DDSTools;
  85302. })(BABYLON || (BABYLON = {}));
  85303. //# sourceMappingURL=babylon.dds.js.map
  85304. var BABYLON;
  85305. (function (BABYLON) {
  85306. /**
  85307. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85308. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85309. */
  85310. var KhronosTextureContainer = /** @class */ (function () {
  85311. /**
  85312. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85313. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85314. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85315. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85316. */
  85317. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85318. this.arrayBuffer = arrayBuffer;
  85319. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85320. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85321. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85322. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85323. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85324. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85325. BABYLON.Tools.Error("texture missing KTX identifier");
  85326. return;
  85327. }
  85328. // load the reset of the header in native 32 bit int
  85329. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85330. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85331. var oppositeEndianess = header[0] === 0x01020304;
  85332. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85333. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85334. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85335. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85336. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85337. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85338. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85339. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85340. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85341. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85342. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85343. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85344. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85345. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85346. if (this.glType !== 0) {
  85347. BABYLON.Tools.Error("only compressed formats currently supported");
  85348. return;
  85349. }
  85350. else {
  85351. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85352. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85353. }
  85354. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85355. BABYLON.Tools.Error("only 2D textures currently supported");
  85356. return;
  85357. }
  85358. if (this.numberOfArrayElements !== 0) {
  85359. BABYLON.Tools.Error("texture arrays not currently supported");
  85360. return;
  85361. }
  85362. if (this.numberOfFaces !== facesExpected) {
  85363. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85364. return;
  85365. }
  85366. // we now have a completely validated file, so could use existence of loadType as success
  85367. // would need to make this more elaborate & adjust checks above to support more than one load type
  85368. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85369. }
  85370. // not as fast hardware based, but will probably never need to use
  85371. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85372. return ((val & 0xFF) << 24)
  85373. | ((val & 0xFF00) << 8)
  85374. | ((val >> 8) & 0xFF00)
  85375. | ((val >> 24) & 0xFF);
  85376. };
  85377. /**
  85378. * It is assumed that the texture has already been created & is currently bound
  85379. */
  85380. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85381. switch (this.loadType) {
  85382. case KhronosTextureContainer.COMPRESSED_2D:
  85383. this._upload2DCompressedLevels(gl, loadMipmaps);
  85384. break;
  85385. case KhronosTextureContainer.TEX_2D:
  85386. case KhronosTextureContainer.COMPRESSED_3D:
  85387. case KhronosTextureContainer.TEX_3D:
  85388. }
  85389. };
  85390. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85391. // initialize width & height for level 1
  85392. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85393. var width = this.pixelWidth;
  85394. var height = this.pixelHeight;
  85395. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85396. for (var level = 0; level < mipmapCount; level++) {
  85397. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85398. for (var face = 0; face < this.numberOfFaces; face++) {
  85399. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85400. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85401. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85402. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85403. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85404. }
  85405. width = Math.max(1.0, width * 0.5);
  85406. height = Math.max(1.0, height * 0.5);
  85407. }
  85408. };
  85409. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85410. // load types
  85411. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85412. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85413. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85414. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85415. return KhronosTextureContainer;
  85416. }());
  85417. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85418. })(BABYLON || (BABYLON = {}));
  85419. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85420. var BABYLON;
  85421. (function (BABYLON) {
  85422. var Debug;
  85423. (function (Debug) {
  85424. /**
  85425. * Class used to render a debug view of a given skeleton
  85426. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  85427. */
  85428. var SkeletonViewer = /** @class */ (function () {
  85429. /**
  85430. * Creates a new SkeletonViewer
  85431. * @param skeleton defines the skeleton to render
  85432. * @param mesh defines the mesh attached to the skeleton
  85433. * @param scene defines the hosting scene
  85434. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  85435. * @param renderingGroupId defines the rendering group id to use with the viewer
  85436. */
  85437. function SkeletonViewer(
  85438. /** defines the skeleton to render */
  85439. skeleton,
  85440. /** defines the mesh attached to the skeleton */
  85441. mesh, scene,
  85442. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  85443. autoUpdateBonesMatrices,
  85444. /** defines the rendering group id to use with the viewer */
  85445. renderingGroupId) {
  85446. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85447. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85448. this.skeleton = skeleton;
  85449. this.mesh = mesh;
  85450. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85451. this.renderingGroupId = renderingGroupId;
  85452. /** Gets or sets the color used to render the skeleton */
  85453. this.color = BABYLON.Color3.White();
  85454. this._debugLines = new Array();
  85455. this._isEnabled = false;
  85456. this._scene = scene;
  85457. this.update();
  85458. this._renderFunction = this.update.bind(this);
  85459. }
  85460. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85461. get: function () {
  85462. return this._isEnabled;
  85463. },
  85464. /** Gets or sets a boolean indicating if the viewer is enabled */
  85465. set: function (value) {
  85466. if (this._isEnabled === value) {
  85467. return;
  85468. }
  85469. this._isEnabled = value;
  85470. if (value) {
  85471. this._scene.registerBeforeRender(this._renderFunction);
  85472. }
  85473. else {
  85474. this._scene.unregisterBeforeRender(this._renderFunction);
  85475. }
  85476. },
  85477. enumerable: true,
  85478. configurable: true
  85479. });
  85480. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85481. if (x === void 0) { x = 0; }
  85482. if (y === void 0) { y = 0; }
  85483. if (z === void 0) { z = 0; }
  85484. var tmat = BABYLON.Tmp.Matrix[0];
  85485. var parentBone = bone.getParent();
  85486. tmat.copyFrom(bone.getLocalMatrix());
  85487. if (x !== 0 || y !== 0 || z !== 0) {
  85488. var tmat2 = BABYLON.Tmp.Matrix[1];
  85489. BABYLON.Matrix.IdentityToRef(tmat2);
  85490. tmat2.m[12] = x;
  85491. tmat2.m[13] = y;
  85492. tmat2.m[14] = z;
  85493. tmat2.multiplyToRef(tmat, tmat);
  85494. }
  85495. if (parentBone) {
  85496. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85497. }
  85498. tmat.multiplyToRef(meshMat, tmat);
  85499. position.x = tmat.m[12];
  85500. position.y = tmat.m[13];
  85501. position.z = tmat.m[14];
  85502. };
  85503. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85504. var len = bones.length;
  85505. var meshPos = this.mesh.position;
  85506. for (var i = 0; i < len; i++) {
  85507. var bone = bones[i];
  85508. var points = this._debugLines[i];
  85509. if (!points) {
  85510. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85511. this._debugLines[i] = points;
  85512. }
  85513. this._getBonePosition(points[0], bone, meshMat);
  85514. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85515. points[0].subtractInPlace(meshPos);
  85516. points[1].subtractInPlace(meshPos);
  85517. }
  85518. };
  85519. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85520. var len = bones.length;
  85521. var boneNum = 0;
  85522. var meshPos = this.mesh.position;
  85523. for (var i = len - 1; i >= 0; i--) {
  85524. var childBone = bones[i];
  85525. var parentBone = childBone.getParent();
  85526. if (!parentBone) {
  85527. continue;
  85528. }
  85529. var points = this._debugLines[boneNum];
  85530. if (!points) {
  85531. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85532. this._debugLines[boneNum] = points;
  85533. }
  85534. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85535. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85536. points[0].subtractInPlace(meshPos);
  85537. points[1].subtractInPlace(meshPos);
  85538. boneNum++;
  85539. }
  85540. };
  85541. /** Update the viewer to sync with current skeleton state */
  85542. SkeletonViewer.prototype.update = function () {
  85543. if (this.autoUpdateBonesMatrices) {
  85544. this.skeleton.computeAbsoluteTransforms();
  85545. }
  85546. if (this.skeleton.bones[0].length === undefined) {
  85547. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85548. }
  85549. else {
  85550. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85551. }
  85552. if (!this._debugMesh) {
  85553. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85554. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85555. }
  85556. else {
  85557. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85558. }
  85559. this._debugMesh.position.copyFrom(this.mesh.position);
  85560. this._debugMesh.color = this.color;
  85561. };
  85562. /** Release associated resources */
  85563. SkeletonViewer.prototype.dispose = function () {
  85564. if (this._debugMesh) {
  85565. this.isEnabled = false;
  85566. this._debugMesh.dispose();
  85567. this._debugMesh = null;
  85568. }
  85569. };
  85570. return SkeletonViewer;
  85571. }());
  85572. Debug.SkeletonViewer = SkeletonViewer;
  85573. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85574. })(BABYLON || (BABYLON = {}));
  85575. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85576. /**
  85577. * Module Debug contains the (visual) components to debug a scene correctly
  85578. */
  85579. var BABYLON;
  85580. (function (BABYLON) {
  85581. var Debug;
  85582. (function (Debug) {
  85583. /**
  85584. * The Axes viewer will show 3 axes in a specific point in space
  85585. */
  85586. var AxesViewer = /** @class */ (function () {
  85587. /**
  85588. * Creates a new AxesViewer
  85589. * @param scene defines the hosting scene
  85590. * @param scaleLines defines a number used to scale line length (1 by default)
  85591. */
  85592. function AxesViewer(scene, scaleLines) {
  85593. if (scaleLines === void 0) { scaleLines = 1; }
  85594. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85595. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85596. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85597. /**
  85598. * Gets or sets a number used to scale line length
  85599. */
  85600. this.scaleLines = 1;
  85601. this.scaleLines = scaleLines;
  85602. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85603. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85604. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85605. this._xmesh.renderingGroupId = 2;
  85606. this._ymesh.renderingGroupId = 2;
  85607. this._zmesh.renderingGroupId = 2;
  85608. this._xmesh.material.checkReadyOnlyOnce = true;
  85609. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85610. this._ymesh.material.checkReadyOnlyOnce = true;
  85611. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85612. this._zmesh.material.checkReadyOnlyOnce = true;
  85613. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85614. this.scene = scene;
  85615. }
  85616. /**
  85617. * Force the viewer to update
  85618. * @param position defines the position of the viewer
  85619. * @param xaxis defines the x axis of the viewer
  85620. * @param yaxis defines the y axis of the viewer
  85621. * @param zaxis defines the z axis of the viewer
  85622. */
  85623. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85624. var scaleLines = this.scaleLines;
  85625. if (this._xmesh) {
  85626. this._xmesh.position.copyFrom(position);
  85627. }
  85628. if (this._ymesh) {
  85629. this._ymesh.position.copyFrom(position);
  85630. }
  85631. if (this._zmesh) {
  85632. this._zmesh.position.copyFrom(position);
  85633. }
  85634. var point2 = this._xline[1];
  85635. point2.x = xaxis.x * scaleLines;
  85636. point2.y = xaxis.y * scaleLines;
  85637. point2.z = xaxis.z * scaleLines;
  85638. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85639. point2 = this._yline[1];
  85640. point2.x = yaxis.x * scaleLines;
  85641. point2.y = yaxis.y * scaleLines;
  85642. point2.z = yaxis.z * scaleLines;
  85643. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85644. point2 = this._zline[1];
  85645. point2.x = zaxis.x * scaleLines;
  85646. point2.y = zaxis.y * scaleLines;
  85647. point2.z = zaxis.z * scaleLines;
  85648. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85649. };
  85650. /** Releases resources */
  85651. AxesViewer.prototype.dispose = function () {
  85652. if (this._xmesh) {
  85653. this._xmesh.dispose();
  85654. }
  85655. if (this._ymesh) {
  85656. this._ymesh.dispose();
  85657. }
  85658. if (this._zmesh) {
  85659. this._zmesh.dispose();
  85660. }
  85661. this._xmesh = null;
  85662. this._ymesh = null;
  85663. this._zmesh = null;
  85664. this.scene = null;
  85665. };
  85666. return AxesViewer;
  85667. }());
  85668. Debug.AxesViewer = AxesViewer;
  85669. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85670. })(BABYLON || (BABYLON = {}));
  85671. //# sourceMappingURL=babylon.axesViewer.js.map
  85672. var BABYLON;
  85673. (function (BABYLON) {
  85674. var Debug;
  85675. (function (Debug) {
  85676. /**
  85677. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85678. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  85679. */
  85680. var BoneAxesViewer = /** @class */ (function (_super) {
  85681. __extends(BoneAxesViewer, _super);
  85682. /**
  85683. * Creates a new BoneAxesViewer
  85684. * @param scene defines the hosting scene
  85685. * @param bone defines the target bone
  85686. * @param mesh defines the target mesh
  85687. * @param scaleLines defines a scaling factor for line length (1 by default)
  85688. */
  85689. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85690. if (scaleLines === void 0) { scaleLines = 1; }
  85691. var _this = _super.call(this, scene, scaleLines) || this;
  85692. /** Gets current position */
  85693. _this.pos = BABYLON.Vector3.Zero();
  85694. /** Gets direction of X axis */
  85695. _this.xaxis = BABYLON.Vector3.Zero();
  85696. /** Gets direction of Y axis */
  85697. _this.yaxis = BABYLON.Vector3.Zero();
  85698. /** Gets direction of Z axis */
  85699. _this.zaxis = BABYLON.Vector3.Zero();
  85700. _this.mesh = mesh;
  85701. _this.bone = bone;
  85702. return _this;
  85703. }
  85704. /**
  85705. * Force the viewer to update
  85706. */
  85707. BoneAxesViewer.prototype.update = function () {
  85708. if (!this.mesh || !this.bone) {
  85709. return;
  85710. }
  85711. var bone = this.bone;
  85712. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85713. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85714. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85715. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85716. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85717. };
  85718. /** Releases resources */
  85719. BoneAxesViewer.prototype.dispose = function () {
  85720. if (this.mesh) {
  85721. this.mesh = null;
  85722. this.bone = null;
  85723. _super.prototype.dispose.call(this);
  85724. }
  85725. };
  85726. return BoneAxesViewer;
  85727. }(Debug.AxesViewer));
  85728. Debug.BoneAxesViewer = BoneAxesViewer;
  85729. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85730. })(BABYLON || (BABYLON = {}));
  85731. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85732. var BABYLON;
  85733. (function (BABYLON) {
  85734. var RayHelper = /** @class */ (function () {
  85735. function RayHelper(ray) {
  85736. this.ray = ray;
  85737. }
  85738. RayHelper.CreateAndShow = function (ray, scene, color) {
  85739. var helper = new RayHelper(ray);
  85740. helper.show(scene, color);
  85741. return helper;
  85742. };
  85743. RayHelper.prototype.show = function (scene, color) {
  85744. if (!this._renderFunction && this.ray) {
  85745. var ray = this.ray;
  85746. this._renderFunction = this._render.bind(this);
  85747. this._scene = scene;
  85748. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85749. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85750. if (this._renderFunction) {
  85751. this._scene.registerBeforeRender(this._renderFunction);
  85752. }
  85753. }
  85754. if (color && this._renderLine) {
  85755. this._renderLine.color.copyFrom(color);
  85756. }
  85757. };
  85758. RayHelper.prototype.hide = function () {
  85759. if (this._renderFunction && this._scene) {
  85760. this._scene.unregisterBeforeRender(this._renderFunction);
  85761. this._scene = null;
  85762. this._renderFunction = null;
  85763. if (this._renderLine) {
  85764. this._renderLine.dispose();
  85765. this._renderLine = null;
  85766. }
  85767. this._renderPoints = [];
  85768. }
  85769. };
  85770. RayHelper.prototype._render = function () {
  85771. var ray = this.ray;
  85772. if (!ray) {
  85773. return;
  85774. }
  85775. var point = this._renderPoints[1];
  85776. var len = Math.min(ray.length, 1000000);
  85777. point.copyFrom(ray.direction);
  85778. point.scaleInPlace(len);
  85779. point.addInPlace(ray.origin);
  85780. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85781. };
  85782. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85783. this._attachedToMesh = mesh;
  85784. var ray = this.ray;
  85785. if (!ray) {
  85786. return;
  85787. }
  85788. if (!ray.direction) {
  85789. ray.direction = BABYLON.Vector3.Zero();
  85790. }
  85791. if (!ray.origin) {
  85792. ray.origin = BABYLON.Vector3.Zero();
  85793. }
  85794. if (length) {
  85795. ray.length = length;
  85796. }
  85797. if (!meshSpaceOrigin) {
  85798. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85799. }
  85800. if (!meshSpaceDirection) {
  85801. // -1 so that this will work with Mesh.lookAt
  85802. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85803. }
  85804. if (!this._meshSpaceDirection) {
  85805. this._meshSpaceDirection = meshSpaceDirection.clone();
  85806. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85807. }
  85808. else {
  85809. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85810. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85811. }
  85812. if (!this._updateToMeshFunction) {
  85813. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85814. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85815. }
  85816. this._updateToMesh();
  85817. };
  85818. RayHelper.prototype.detachFromMesh = function () {
  85819. if (this._attachedToMesh) {
  85820. if (this._updateToMeshFunction) {
  85821. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85822. }
  85823. this._attachedToMesh = null;
  85824. this._updateToMeshFunction = null;
  85825. }
  85826. };
  85827. RayHelper.prototype._updateToMesh = function () {
  85828. var ray = this.ray;
  85829. if (!this._attachedToMesh || !ray) {
  85830. return;
  85831. }
  85832. if (this._attachedToMesh._isDisposed) {
  85833. this.detachFromMesh();
  85834. return;
  85835. }
  85836. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85837. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85838. };
  85839. RayHelper.prototype.dispose = function () {
  85840. this.hide();
  85841. this.detachFromMesh();
  85842. this.ray = null;
  85843. };
  85844. return RayHelper;
  85845. }());
  85846. BABYLON.RayHelper = RayHelper;
  85847. })(BABYLON || (BABYLON = {}));
  85848. //# sourceMappingURL=babylon.rayHelper.js.map
  85849. var BABYLON;
  85850. (function (BABYLON) {
  85851. // load the inspector using require, if not present in the global namespace.
  85852. var DebugLayer = /** @class */ (function () {
  85853. function DebugLayer(scene) {
  85854. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85855. this._scene = scene;
  85856. // load inspector using require, if it doesn't exist on the global namespace.
  85857. }
  85858. /** Creates the inspector window. */
  85859. DebugLayer.prototype._createInspector = function (config) {
  85860. if (config === void 0) { config = {}; }
  85861. var popup = config.popup || false;
  85862. var initialTab = config.initialTab || 0;
  85863. var parentElement = config.parentElement || null;
  85864. if (!this._inspector) {
  85865. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85866. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85867. } // else nothing to do,; instance is already existing
  85868. };
  85869. DebugLayer.prototype.isVisible = function () {
  85870. if (!this._inspector) {
  85871. return false;
  85872. }
  85873. return true;
  85874. };
  85875. DebugLayer.prototype.hide = function () {
  85876. if (this._inspector) {
  85877. try {
  85878. this._inspector.dispose();
  85879. }
  85880. catch (e) {
  85881. // If the inspector has been removed directly from the inspector tool
  85882. }
  85883. this._inspector = null;
  85884. }
  85885. };
  85886. DebugLayer.prototype.show = function (config) {
  85887. if (config === void 0) { config = {}; }
  85888. if (typeof this.BJSINSPECTOR == 'undefined') {
  85889. // Load inspector and add it to the DOM
  85890. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85891. }
  85892. else {
  85893. // Otherwise creates the inspector
  85894. this._createInspector(config);
  85895. }
  85896. };
  85897. /**
  85898. * Gets the active tab
  85899. * @return the index of the active tab or -1 if the inspector is hidden
  85900. */
  85901. DebugLayer.prototype.getActiveTab = function () {
  85902. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85903. };
  85904. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85905. return DebugLayer;
  85906. }());
  85907. BABYLON.DebugLayer = DebugLayer;
  85908. })(BABYLON || (BABYLON = {}));
  85909. //# sourceMappingURL=babylon.debugLayer.js.map
  85910. var BABYLON;
  85911. (function (BABYLON) {
  85912. var Debug;
  85913. (function (Debug) {
  85914. /**
  85915. * Used to show the physics impostor around the specific mesh
  85916. */
  85917. var PhysicsViewer = /** @class */ (function () {
  85918. /**
  85919. * Creates a new PhysicsViewer
  85920. * @param scene defines the hosting scene
  85921. */
  85922. function PhysicsViewer(scene) {
  85923. /** @hidden */
  85924. this._impostors = [];
  85925. /** @hidden */
  85926. this._meshes = [];
  85927. /** @hidden */
  85928. this._numMeshes = 0;
  85929. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85930. var physicEngine = this._scene.getPhysicsEngine();
  85931. if (physicEngine) {
  85932. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85933. }
  85934. }
  85935. /** @hidden */
  85936. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85937. var plugin = this._physicsEnginePlugin;
  85938. for (var i = 0; i < this._numMeshes; i++) {
  85939. var impostor = this._impostors[i];
  85940. if (!impostor) {
  85941. continue;
  85942. }
  85943. if (impostor.isDisposed) {
  85944. this.hideImpostor(this._impostors[i--]);
  85945. }
  85946. else {
  85947. var mesh = this._meshes[i];
  85948. if (mesh && plugin) {
  85949. plugin.syncMeshWithImpostor(mesh, impostor);
  85950. }
  85951. }
  85952. }
  85953. };
  85954. /**
  85955. * Renders a specified physic impostor
  85956. * @param impostor defines the impostor to render
  85957. */
  85958. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85959. if (!this._scene) {
  85960. return;
  85961. }
  85962. for (var i = 0; i < this._numMeshes; i++) {
  85963. if (this._impostors[i] == impostor) {
  85964. return;
  85965. }
  85966. }
  85967. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85968. if (debugMesh) {
  85969. this._impostors[this._numMeshes] = impostor;
  85970. this._meshes[this._numMeshes] = debugMesh;
  85971. if (this._numMeshes === 0) {
  85972. this._renderFunction = this._updateDebugMeshes.bind(this);
  85973. this._scene.registerBeforeRender(this._renderFunction);
  85974. }
  85975. this._numMeshes++;
  85976. }
  85977. };
  85978. /**
  85979. * Hides a specified physic impostor
  85980. * @param impostor defines the impostor to hide
  85981. */
  85982. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85983. if (!impostor || !this._scene) {
  85984. return;
  85985. }
  85986. var removed = false;
  85987. for (var i = 0; i < this._numMeshes; i++) {
  85988. if (this._impostors[i] == impostor) {
  85989. var mesh = this._meshes[i];
  85990. if (!mesh) {
  85991. continue;
  85992. }
  85993. this._scene.removeMesh(mesh);
  85994. mesh.dispose();
  85995. this._numMeshes--;
  85996. if (this._numMeshes > 0) {
  85997. this._meshes[i] = this._meshes[this._numMeshes];
  85998. this._impostors[i] = this._impostors[this._numMeshes];
  85999. this._meshes[this._numMeshes] = null;
  86000. this._impostors[this._numMeshes] = null;
  86001. }
  86002. else {
  86003. this._meshes[0] = null;
  86004. this._impostors[0] = null;
  86005. }
  86006. removed = true;
  86007. break;
  86008. }
  86009. }
  86010. if (removed && this._numMeshes === 0) {
  86011. this._scene.unregisterBeforeRender(this._renderFunction);
  86012. }
  86013. };
  86014. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86015. if (!this._debugMaterial) {
  86016. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86017. this._debugMaterial.wireframe = true;
  86018. }
  86019. return this._debugMaterial;
  86020. };
  86021. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86022. if (!this._debugBoxMesh) {
  86023. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86024. this._debugBoxMesh.renderingGroupId = 1;
  86025. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86026. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86027. scene.removeMesh(this._debugBoxMesh);
  86028. }
  86029. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86030. };
  86031. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86032. if (!this._debugSphereMesh) {
  86033. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86034. this._debugSphereMesh.renderingGroupId = 1;
  86035. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86036. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86037. scene.removeMesh(this._debugSphereMesh);
  86038. }
  86039. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86040. };
  86041. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86042. var mesh = null;
  86043. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86044. mesh = this._getDebugBoxMesh(scene);
  86045. impostor.getBoxSizeToRef(mesh.scaling);
  86046. }
  86047. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86048. mesh = this._getDebugSphereMesh(scene);
  86049. var radius = impostor.getRadius();
  86050. mesh.scaling.x = radius * 2;
  86051. mesh.scaling.y = radius * 2;
  86052. mesh.scaling.z = radius * 2;
  86053. }
  86054. return mesh;
  86055. };
  86056. /** Releases all resources */
  86057. PhysicsViewer.prototype.dispose = function () {
  86058. for (var i = 0; i < this._numMeshes; i++) {
  86059. this.hideImpostor(this._impostors[i]);
  86060. }
  86061. if (this._debugBoxMesh) {
  86062. this._debugBoxMesh.dispose();
  86063. }
  86064. if (this._debugSphereMesh) {
  86065. this._debugSphereMesh.dispose();
  86066. }
  86067. if (this._debugMaterial) {
  86068. this._debugMaterial.dispose();
  86069. }
  86070. this._impostors.length = 0;
  86071. this._scene = null;
  86072. this._physicsEnginePlugin = null;
  86073. };
  86074. return PhysicsViewer;
  86075. }());
  86076. Debug.PhysicsViewer = PhysicsViewer;
  86077. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86078. })(BABYLON || (BABYLON = {}));
  86079. //# sourceMappingURL=babylon.physicsViewer.js.map
  86080. var BABYLON;
  86081. (function (BABYLON) {
  86082. var BoundingBoxRenderer = /** @class */ (function () {
  86083. function BoundingBoxRenderer(scene) {
  86084. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86085. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86086. this.showBackLines = true;
  86087. this.renderList = new BABYLON.SmartArray(32);
  86088. this._vertexBuffers = {};
  86089. this._scene = scene;
  86090. }
  86091. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86092. if (this._colorShader) {
  86093. return;
  86094. }
  86095. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86096. attributes: [BABYLON.VertexBuffer.PositionKind],
  86097. uniforms: ["world", "viewProjection", "color"]
  86098. });
  86099. var engine = this._scene.getEngine();
  86100. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86101. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86102. this._createIndexBuffer();
  86103. };
  86104. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86105. var engine = this._scene.getEngine();
  86106. 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]);
  86107. };
  86108. BoundingBoxRenderer.prototype._rebuild = function () {
  86109. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86110. if (vb) {
  86111. vb._rebuild();
  86112. }
  86113. this._createIndexBuffer();
  86114. };
  86115. BoundingBoxRenderer.prototype.reset = function () {
  86116. this.renderList.reset();
  86117. };
  86118. BoundingBoxRenderer.prototype.render = function () {
  86119. if (this.renderList.length === 0) {
  86120. return;
  86121. }
  86122. this._prepareRessources();
  86123. if (!this._colorShader.isReady()) {
  86124. return;
  86125. }
  86126. var engine = this._scene.getEngine();
  86127. engine.setDepthWrite(false);
  86128. this._colorShader._preBind();
  86129. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86130. var boundingBox = this.renderList.data[boundingBoxIndex];
  86131. var min = boundingBox.minimum;
  86132. var max = boundingBox.maximum;
  86133. var diff = max.subtract(min);
  86134. var median = min.add(diff.scale(0.5));
  86135. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86136. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86137. .multiply(boundingBox.getWorldMatrix());
  86138. // VBOs
  86139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86140. if (this.showBackLines) {
  86141. // Back
  86142. engine.setDepthFunctionToGreaterOrEqual();
  86143. this._scene.resetCachedMaterial();
  86144. this._colorShader.setColor4("color", this.backColor.toColor4());
  86145. this._colorShader.bind(worldMatrix);
  86146. // Draw order
  86147. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86148. }
  86149. // Front
  86150. engine.setDepthFunctionToLess();
  86151. this._scene.resetCachedMaterial();
  86152. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86153. this._colorShader.bind(worldMatrix);
  86154. // Draw order
  86155. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86156. }
  86157. this._colorShader.unbind();
  86158. engine.setDepthFunctionToLessOrEqual();
  86159. engine.setDepthWrite(true);
  86160. };
  86161. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86162. this._prepareRessources();
  86163. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86164. return;
  86165. }
  86166. var engine = this._scene.getEngine();
  86167. engine.setDepthWrite(false);
  86168. engine.setColorWrite(false);
  86169. this._colorShader._preBind();
  86170. var boundingBox = mesh._boundingInfo.boundingBox;
  86171. var min = boundingBox.minimum;
  86172. var max = boundingBox.maximum;
  86173. var diff = max.subtract(min);
  86174. var median = min.add(diff.scale(0.5));
  86175. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86176. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86177. .multiply(boundingBox.getWorldMatrix());
  86178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86179. engine.setDepthFunctionToLess();
  86180. this._scene.resetCachedMaterial();
  86181. this._colorShader.bind(worldMatrix);
  86182. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86183. this._colorShader.unbind();
  86184. engine.setDepthFunctionToLessOrEqual();
  86185. engine.setDepthWrite(true);
  86186. engine.setColorWrite(true);
  86187. };
  86188. BoundingBoxRenderer.prototype.dispose = function () {
  86189. if (!this._colorShader) {
  86190. return;
  86191. }
  86192. this.renderList.dispose();
  86193. this._colorShader.dispose();
  86194. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86195. if (buffer) {
  86196. buffer.dispose();
  86197. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86198. }
  86199. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86200. };
  86201. return BoundingBoxRenderer;
  86202. }());
  86203. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86204. })(BABYLON || (BABYLON = {}));
  86205. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86206. var BABYLON;
  86207. (function (BABYLON) {
  86208. /**
  86209. * Renders a layer on top of an existing scene
  86210. */
  86211. var UtilityLayerRenderer = /** @class */ (function () {
  86212. /**
  86213. * Instantiates a UtilityLayerRenderer
  86214. * @param originalScene the original scene that will be rendered on top of
  86215. */
  86216. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86217. var _this = this;
  86218. this.originalScene = originalScene;
  86219. /**
  86220. * If the utility layer should automatically be rendered on top of existing scene
  86221. */
  86222. this.shouldRender = true;
  86223. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86224. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86225. originalScene.getEngine().scenes.pop();
  86226. // Render directly on top of existing scene without clearing
  86227. this.utilityLayerScene.autoClear = false;
  86228. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86229. if (_this.shouldRender) {
  86230. _this.render();
  86231. }
  86232. });
  86233. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86234. _this.dispose();
  86235. });
  86236. this._updateCamera();
  86237. }
  86238. /**
  86239. * Renders the utility layers scene on top of the original scene
  86240. */
  86241. UtilityLayerRenderer.prototype.render = function () {
  86242. this._updateCamera();
  86243. this.utilityLayerScene.render(false);
  86244. };
  86245. /**
  86246. * Disposes of the renderer
  86247. */
  86248. UtilityLayerRenderer.prototype.dispose = function () {
  86249. if (this._afterRenderObserver) {
  86250. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86251. }
  86252. if (this._sceneDisposeObserver) {
  86253. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86254. }
  86255. this.utilityLayerScene.dispose();
  86256. };
  86257. UtilityLayerRenderer.prototype._updateCamera = function () {
  86258. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86259. };
  86260. return UtilityLayerRenderer;
  86261. }());
  86262. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86263. })(BABYLON || (BABYLON = {}));
  86264. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86265. var BABYLON;
  86266. (function (BABYLON) {
  86267. /**
  86268. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86269. */
  86270. var Gizmo = /** @class */ (function () {
  86271. /**
  86272. * Creates a gizmo
  86273. * @param gizmoLayer The utility layer the gizmo will be added to
  86274. */
  86275. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86276. var _this = this;
  86277. this.gizmoLayer = gizmoLayer;
  86278. this._interactionsEnabled = true;
  86279. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86280. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86281. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86282. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  86283. _this._rootMesh.scaling.set(dist, dist, dist);
  86284. }
  86285. if (_this.attachedMesh) {
  86286. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86287. }
  86288. });
  86289. }
  86290. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86291. };
  86292. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  86293. get: function () {
  86294. return this._interactionsEnabled;
  86295. },
  86296. /**
  86297. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  86298. */
  86299. set: function (value) {
  86300. this._interactionsEnabled = value;
  86301. this._onInteractionsEnabledChanged(value);
  86302. },
  86303. enumerable: true,
  86304. configurable: true
  86305. });
  86306. /**
  86307. * Disposes of the gizmo
  86308. */
  86309. Gizmo.prototype.dispose = function () {
  86310. this._rootMesh.dispose();
  86311. if (this._beforeRenderObserver) {
  86312. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86313. }
  86314. };
  86315. return Gizmo;
  86316. }());
  86317. BABYLON.Gizmo = Gizmo;
  86318. })(BABYLON || (BABYLON = {}));
  86319. //# sourceMappingURL=babylon.gizmo.js.map
  86320. var BABYLON;
  86321. (function (BABYLON) {
  86322. /**
  86323. * Single axis drag gizmo
  86324. */
  86325. var AxisDragGizmo = /** @class */ (function (_super) {
  86326. __extends(AxisDragGizmo, _super);
  86327. /**
  86328. * Creates an AxisDragGizmo
  86329. * @param gizmoLayer The utility layer the gizmo will be added to
  86330. * @param dragAxis The axis which the gizmo will be able to drag on
  86331. * @param color The color of the gizmo
  86332. */
  86333. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86334. var _this = _super.call(this, gizmoLayer) || this;
  86335. // Create Material
  86336. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86337. coloredMaterial.disableLighting = true;
  86338. coloredMaterial.emissiveColor = color;
  86339. // Build mesh on root node
  86340. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86341. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86342. _this._rootMesh.addChild(arrowMesh);
  86343. _this._rootMesh.addChild(arrowTail);
  86344. // Position arrow pointing in its drag axis
  86345. arrowMesh.scaling.scaleInPlace(0.1);
  86346. arrowMesh.material = coloredMaterial;
  86347. arrowMesh.rotation.x = Math.PI / 2;
  86348. arrowMesh.position.z += 0.3;
  86349. arrowTail.rotation.x = Math.PI / 2;
  86350. arrowTail.material = coloredMaterial;
  86351. arrowTail.position.z += 0.2;
  86352. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86353. // Add drag behavior to handle events when the gizmo is dragged
  86354. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86355. _this._dragBehavior.moveAttached = false;
  86356. _this._rootMesh.addBehavior(_this._dragBehavior);
  86357. _this._dragBehavior.onDragObservable.add(function (event) {
  86358. if (!_this.interactionsEnabled) {
  86359. return;
  86360. }
  86361. if (_this.attachedMesh) {
  86362. _this.attachedMesh.position.addInPlace(event.delta);
  86363. }
  86364. });
  86365. return _this;
  86366. }
  86367. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86368. this._dragBehavior.enabled = value;
  86369. };
  86370. /**
  86371. * Disposes of the gizmo
  86372. */
  86373. AxisDragGizmo.prototype.dispose = function () {
  86374. this._dragBehavior.detach();
  86375. _super.prototype.dispose.call(this);
  86376. };
  86377. return AxisDragGizmo;
  86378. }(BABYLON.Gizmo));
  86379. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86380. })(BABYLON || (BABYLON = {}));
  86381. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86382. var BABYLON;
  86383. (function (BABYLON) {
  86384. /**
  86385. * Single axis scale gizmo
  86386. */
  86387. var AxisScaleGizmo = /** @class */ (function (_super) {
  86388. __extends(AxisScaleGizmo, _super);
  86389. /**
  86390. * Creates an AxisScaleGizmo
  86391. * @param gizmoLayer The utility layer the gizmo will be added to
  86392. * @param dragAxis The axis which the gizmo will be able to scale on
  86393. * @param color The color of the gizmo
  86394. */
  86395. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  86396. var _this = _super.call(this, gizmoLayer) || this;
  86397. // Create Material
  86398. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86399. coloredMaterial.disableLighting = true;
  86400. coloredMaterial.emissiveColor = color;
  86401. // Build mesh on root node
  86402. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  86403. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86404. _this._rootMesh.addChild(arrowMesh);
  86405. _this._rootMesh.addChild(arrowTail);
  86406. // Position arrow pointing in its drag axis
  86407. arrowMesh.scaling.scaleInPlace(0.1);
  86408. arrowMesh.material = coloredMaterial;
  86409. arrowMesh.rotation.x = Math.PI / 2;
  86410. arrowMesh.position.z += 0.3;
  86411. arrowTail.rotation.x = Math.PI / 2;
  86412. arrowTail.material = coloredMaterial;
  86413. arrowTail.position.z += 0.2;
  86414. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86415. // Add drag behavior to handle events when the gizmo is dragged
  86416. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86417. _this._dragBehavior.moveAttached = false;
  86418. _this._rootMesh.addBehavior(_this._dragBehavior);
  86419. _this._dragBehavior.onDragObservable.add(function (event) {
  86420. if (!_this.interactionsEnabled) {
  86421. return;
  86422. }
  86423. if (_this.attachedMesh) {
  86424. _this.attachedMesh.scaling.addInPlace(event.delta);
  86425. }
  86426. });
  86427. return _this;
  86428. }
  86429. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86430. this._dragBehavior.enabled = value;
  86431. };
  86432. /**
  86433. * Disposes of the gizmo
  86434. */
  86435. AxisScaleGizmo.prototype.dispose = function () {
  86436. this._dragBehavior.detach();
  86437. _super.prototype.dispose.call(this);
  86438. };
  86439. return AxisScaleGizmo;
  86440. }(BABYLON.Gizmo));
  86441. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  86442. })(BABYLON || (BABYLON = {}));
  86443. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  86444. var BABYLON;
  86445. (function (BABYLON) {
  86446. /**
  86447. * Single plane rotation gizmo
  86448. */
  86449. var PlaneRotationGizmo = /** @class */ (function (_super) {
  86450. __extends(PlaneRotationGizmo, _super);
  86451. /**
  86452. * Creates a PlaneRotationGizmo
  86453. * @param gizmoLayer The utility layer the gizmo will be added to
  86454. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  86455. * @param color The color of the gizmo
  86456. */
  86457. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  86458. var _this = _super.call(this, gizmoLayer) || this;
  86459. // Create Material
  86460. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86461. coloredMaterial.disableLighting = true;
  86462. coloredMaterial.emissiveColor = color;
  86463. // Build mesh on root node
  86464. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  86465. _this._rootMesh.addChild(rotationMesh);
  86466. // Position arrow pointing in its drag axis
  86467. rotationMesh.scaling.scaleInPlace(0.1);
  86468. rotationMesh.material = coloredMaterial;
  86469. rotationMesh.rotation.x = Math.PI / 2;
  86470. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  86471. // Add drag behavior to handle events when the gizmo is dragged
  86472. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal, pointerObservableScene: gizmoLayer.originalScene });
  86473. _this._dragBehavior.moveAttached = false;
  86474. _this._rootMesh.addBehavior(_this._dragBehavior);
  86475. var lastDragPosition = null;
  86476. _this._dragBehavior.onDragStartObservable.add(function (e) {
  86477. if (!_this.interactionsEnabled) {
  86478. return;
  86479. }
  86480. lastDragPosition = e.dragPlanePoint;
  86481. });
  86482. _this._dragBehavior.onDragObservable.add(function (event) {
  86483. if (!_this.interactionsEnabled) {
  86484. return;
  86485. }
  86486. if (_this.attachedMesh && lastDragPosition) {
  86487. if (!_this.attachedMesh.rotationQuaternion) {
  86488. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  86489. }
  86490. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  86491. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  86492. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  86493. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  86494. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  86495. var angle = Math.atan2(cross.length(), dot);
  86496. var up = planeNormal.clone();
  86497. // Flip up vector depending on which side the camera is on
  86498. if (gizmoLayer.utilityLayerScene.activeCamera) {
  86499. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  86500. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  86501. up.scaleInPlace(-1);
  86502. }
  86503. }
  86504. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  86505. if (halfCircleSide)
  86506. angle = -angle;
  86507. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  86508. var quaternionCoefficient = Math.sin(angle / 2);
  86509. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  86510. // Rotate selected mesh quaternion over fixed axis
  86511. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  86512. lastDragPosition = event.dragPlanePoint;
  86513. }
  86514. });
  86515. return _this;
  86516. }
  86517. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86518. this._dragBehavior.enabled = value;
  86519. };
  86520. /**
  86521. * Disposes of the gizmo
  86522. */
  86523. PlaneRotationGizmo.prototype.dispose = function () {
  86524. this._dragBehavior.detach();
  86525. _super.prototype.dispose.call(this);
  86526. };
  86527. return PlaneRotationGizmo;
  86528. }(BABYLON.Gizmo));
  86529. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  86530. })(BABYLON || (BABYLON = {}));
  86531. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  86532. var BABYLON;
  86533. (function (BABYLON) {
  86534. /**
  86535. * Gizmo that enables dragging a mesh along 3 axis
  86536. */
  86537. var PositionGizmo = /** @class */ (function (_super) {
  86538. __extends(PositionGizmo, _super);
  86539. /**
  86540. * Creates a PositionGizmo
  86541. * @param gizmoLayer The utility layer the gizmo will be added to
  86542. */
  86543. function PositionGizmo(gizmoLayer) {
  86544. var _this = _super.call(this, gizmoLayer) || this;
  86545. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86546. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86547. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86548. return _this;
  86549. }
  86550. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86551. set: function (mesh) {
  86552. this._xDrag.attachedMesh = mesh;
  86553. this._yDrag.attachedMesh = mesh;
  86554. this._zDrag.attachedMesh = mesh;
  86555. },
  86556. enumerable: true,
  86557. configurable: true
  86558. });
  86559. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86560. this._xDrag.interactionsEnabled = value;
  86561. this._yDrag.interactionsEnabled = value;
  86562. this._zDrag.interactionsEnabled = value;
  86563. };
  86564. /**
  86565. * Disposes of the gizmo
  86566. */
  86567. PositionGizmo.prototype.dispose = function () {
  86568. this._xDrag.dispose();
  86569. this._yDrag.dispose();
  86570. this._zDrag.dispose();
  86571. };
  86572. return PositionGizmo;
  86573. }(BABYLON.Gizmo));
  86574. BABYLON.PositionGizmo = PositionGizmo;
  86575. })(BABYLON || (BABYLON = {}));
  86576. //# sourceMappingURL=babylon.positionGizmo.js.map
  86577. var BABYLON;
  86578. (function (BABYLON) {
  86579. /**
  86580. * Gizmo that enables rotating a mesh along 3 axis
  86581. */
  86582. var RotationGizmo = /** @class */ (function (_super) {
  86583. __extends(RotationGizmo, _super);
  86584. /**
  86585. * Creates a RotationGizmo
  86586. * @param gizmoLayer The utility layer the gizmo will be added to
  86587. */
  86588. function RotationGizmo(gizmoLayer) {
  86589. var _this = _super.call(this, gizmoLayer) || this;
  86590. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86591. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86592. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86593. return _this;
  86594. }
  86595. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  86596. set: function (mesh) {
  86597. this._xDrag.attachedMesh = mesh;
  86598. this._yDrag.attachedMesh = mesh;
  86599. this._zDrag.attachedMesh = mesh;
  86600. },
  86601. enumerable: true,
  86602. configurable: true
  86603. });
  86604. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86605. this._xDrag.interactionsEnabled = value;
  86606. this._yDrag.interactionsEnabled = value;
  86607. this._zDrag.interactionsEnabled = value;
  86608. };
  86609. /**
  86610. * Disposes of the gizmo
  86611. */
  86612. RotationGizmo.prototype.dispose = function () {
  86613. this._xDrag.dispose();
  86614. this._yDrag.dispose();
  86615. this._zDrag.dispose();
  86616. };
  86617. return RotationGizmo;
  86618. }(BABYLON.Gizmo));
  86619. BABYLON.RotationGizmo = RotationGizmo;
  86620. })(BABYLON || (BABYLON = {}));
  86621. //# sourceMappingURL=babylon.rotationGizmo.js.map
  86622. var BABYLON;
  86623. (function (BABYLON) {
  86624. /**
  86625. * Gizmo that enables scaling a mesh along 3 axis
  86626. */
  86627. var ScaleGizmo = /** @class */ (function (_super) {
  86628. __extends(ScaleGizmo, _super);
  86629. /**
  86630. * Creates a ScaleGizmo
  86631. * @param gizmoLayer The utility layer the gizmo will be added to
  86632. */
  86633. function ScaleGizmo(gizmoLayer) {
  86634. var _this = _super.call(this, gizmoLayer) || this;
  86635. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86636. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86637. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86638. return _this;
  86639. }
  86640. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  86641. set: function (mesh) {
  86642. this._xDrag.attachedMesh = mesh;
  86643. this._yDrag.attachedMesh = mesh;
  86644. this._zDrag.attachedMesh = mesh;
  86645. },
  86646. enumerable: true,
  86647. configurable: true
  86648. });
  86649. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86650. this._xDrag.interactionsEnabled = value;
  86651. this._yDrag.interactionsEnabled = value;
  86652. this._zDrag.interactionsEnabled = value;
  86653. };
  86654. /**
  86655. * Disposes of the gizmo
  86656. */
  86657. ScaleGizmo.prototype.dispose = function () {
  86658. this._xDrag.dispose();
  86659. this._yDrag.dispose();
  86660. this._zDrag.dispose();
  86661. };
  86662. return ScaleGizmo;
  86663. }(BABYLON.Gizmo));
  86664. BABYLON.ScaleGizmo = ScaleGizmo;
  86665. })(BABYLON || (BABYLON = {}));
  86666. //# sourceMappingURL=babylon.scaleGizmo.js.map
  86667. var BABYLON;
  86668. (function (BABYLON) {
  86669. /**
  86670. * Defines a target to use with MorphTargetManager
  86671. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86672. */
  86673. var MorphTarget = /** @class */ (function () {
  86674. /**
  86675. * Creates a new MorphTarget
  86676. * @param name defines the name of the target
  86677. * @param influence defines the influence to use
  86678. */
  86679. function MorphTarget(
  86680. /** defines the name of the target */
  86681. name, influence, scene) {
  86682. if (influence === void 0) { influence = 0; }
  86683. if (scene === void 0) { scene = null; }
  86684. this.name = name;
  86685. /**
  86686. * Gets or sets the list of animations
  86687. */
  86688. this.animations = new Array();
  86689. this._positions = null;
  86690. this._normals = null;
  86691. this._tangents = null;
  86692. /**
  86693. * Observable raised when the influence changes
  86694. */
  86695. this.onInfluenceChanged = new BABYLON.Observable();
  86696. this._animationPropertiesOverride = null;
  86697. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86698. this.influence = influence;
  86699. }
  86700. Object.defineProperty(MorphTarget.prototype, "influence", {
  86701. /**
  86702. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86703. */
  86704. get: function () {
  86705. return this._influence;
  86706. },
  86707. set: function (influence) {
  86708. if (this._influence === influence) {
  86709. return;
  86710. }
  86711. var previous = this._influence;
  86712. this._influence = influence;
  86713. if (this.onInfluenceChanged.hasObservers) {
  86714. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86715. }
  86716. },
  86717. enumerable: true,
  86718. configurable: true
  86719. });
  86720. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86721. /**
  86722. * Gets or sets the animation properties override
  86723. */
  86724. get: function () {
  86725. if (!this._animationPropertiesOverride && this._scene) {
  86726. return this._scene.animationPropertiesOverride;
  86727. }
  86728. return this._animationPropertiesOverride;
  86729. },
  86730. set: function (value) {
  86731. this._animationPropertiesOverride = value;
  86732. },
  86733. enumerable: true,
  86734. configurable: true
  86735. });
  86736. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86737. /**
  86738. * Gets a boolean defining if the target contains position data
  86739. */
  86740. get: function () {
  86741. return !!this._positions;
  86742. },
  86743. enumerable: true,
  86744. configurable: true
  86745. });
  86746. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86747. /**
  86748. * Gets a boolean defining if the target contains normal data
  86749. */
  86750. get: function () {
  86751. return !!this._normals;
  86752. },
  86753. enumerable: true,
  86754. configurable: true
  86755. });
  86756. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86757. /**
  86758. * Gets a boolean defining if the target contains tangent data
  86759. */
  86760. get: function () {
  86761. return !!this._tangents;
  86762. },
  86763. enumerable: true,
  86764. configurable: true
  86765. });
  86766. /**
  86767. * Affects position data to this target
  86768. * @param data defines the position data to use
  86769. */
  86770. MorphTarget.prototype.setPositions = function (data) {
  86771. this._positions = data;
  86772. };
  86773. /**
  86774. * Gets the position data stored in this target
  86775. * @returns a FloatArray containing the position data (or null if not present)
  86776. */
  86777. MorphTarget.prototype.getPositions = function () {
  86778. return this._positions;
  86779. };
  86780. /**
  86781. * Affects normal data to this target
  86782. * @param data defines the normal data to use
  86783. */
  86784. MorphTarget.prototype.setNormals = function (data) {
  86785. this._normals = data;
  86786. };
  86787. /**
  86788. * Gets the normal data stored in this target
  86789. * @returns a FloatArray containing the normal data (or null if not present)
  86790. */
  86791. MorphTarget.prototype.getNormals = function () {
  86792. return this._normals;
  86793. };
  86794. /**
  86795. * Affects tangent data to this target
  86796. * @param data defines the tangent data to use
  86797. */
  86798. MorphTarget.prototype.setTangents = function (data) {
  86799. this._tangents = data;
  86800. };
  86801. /**
  86802. * Gets the tangent data stored in this target
  86803. * @returns a FloatArray containing the tangent data (or null if not present)
  86804. */
  86805. MorphTarget.prototype.getTangents = function () {
  86806. return this._tangents;
  86807. };
  86808. /**
  86809. * Serializes the current target into a Serialization object
  86810. * @returns the serialized object
  86811. */
  86812. MorphTarget.prototype.serialize = function () {
  86813. var serializationObject = {};
  86814. serializationObject.name = this.name;
  86815. serializationObject.influence = this.influence;
  86816. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86817. if (this.hasNormals) {
  86818. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86819. }
  86820. if (this.hasTangents) {
  86821. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86822. }
  86823. // Animations
  86824. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86825. return serializationObject;
  86826. };
  86827. // Statics
  86828. /**
  86829. * Creates a new target from serialized data
  86830. * @param serializationObject defines the serialized data to use
  86831. * @returns a new MorphTarget
  86832. */
  86833. MorphTarget.Parse = function (serializationObject) {
  86834. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86835. result.setPositions(serializationObject.positions);
  86836. if (serializationObject.normals) {
  86837. result.setNormals(serializationObject.normals);
  86838. }
  86839. if (serializationObject.tangents) {
  86840. result.setTangents(serializationObject.tangents);
  86841. }
  86842. // Animations
  86843. if (serializationObject.animations) {
  86844. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86845. var parsedAnimation = serializationObject.animations[animationIndex];
  86846. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86847. }
  86848. }
  86849. return result;
  86850. };
  86851. /**
  86852. * Creates a MorphTarget from mesh data
  86853. * @param mesh defines the source mesh
  86854. * @param name defines the name to use for the new target
  86855. * @param influence defines the influence to attach to the target
  86856. * @returns a new MorphTarget
  86857. */
  86858. MorphTarget.FromMesh = function (mesh, name, influence) {
  86859. if (!name) {
  86860. name = mesh.name;
  86861. }
  86862. var result = new MorphTarget(name, influence, mesh.getScene());
  86863. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86865. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86866. }
  86867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86868. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86869. }
  86870. return result;
  86871. };
  86872. return MorphTarget;
  86873. }());
  86874. BABYLON.MorphTarget = MorphTarget;
  86875. })(BABYLON || (BABYLON = {}));
  86876. //# sourceMappingURL=babylon.morphTarget.js.map
  86877. var BABYLON;
  86878. (function (BABYLON) {
  86879. /**
  86880. * This class is used to deform meshes using morphing between different targets
  86881. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86882. */
  86883. var MorphTargetManager = /** @class */ (function () {
  86884. /**
  86885. * Creates a new MorphTargetManager
  86886. * @param scene defines the current scene
  86887. */
  86888. function MorphTargetManager(scene) {
  86889. if (scene === void 0) { scene = null; }
  86890. this._targets = new Array();
  86891. this._targetObservable = new Array();
  86892. this._activeTargets = new BABYLON.SmartArray(16);
  86893. this._supportsNormals = false;
  86894. this._supportsTangents = false;
  86895. this._vertexCount = 0;
  86896. this._uniqueId = 0;
  86897. this._tempInfluences = new Array();
  86898. if (!scene) {
  86899. scene = BABYLON.Engine.LastCreatedScene;
  86900. }
  86901. this._scene = scene;
  86902. if (this._scene) {
  86903. this._scene.morphTargetManagers.push(this);
  86904. this._uniqueId = this._scene.getUniqueId();
  86905. }
  86906. }
  86907. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86908. /**
  86909. * Gets the unique ID of this manager
  86910. */
  86911. get: function () {
  86912. return this._uniqueId;
  86913. },
  86914. enumerable: true,
  86915. configurable: true
  86916. });
  86917. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86918. /**
  86919. * Gets the number of vertices handled by this manager
  86920. */
  86921. get: function () {
  86922. return this._vertexCount;
  86923. },
  86924. enumerable: true,
  86925. configurable: true
  86926. });
  86927. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86928. /**
  86929. * Gets a boolean indicating if this manager supports morphing of normals
  86930. */
  86931. get: function () {
  86932. return this._supportsNormals;
  86933. },
  86934. enumerable: true,
  86935. configurable: true
  86936. });
  86937. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86938. /**
  86939. * Gets a boolean indicating if this manager supports morphing of tangents
  86940. */
  86941. get: function () {
  86942. return this._supportsTangents;
  86943. },
  86944. enumerable: true,
  86945. configurable: true
  86946. });
  86947. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86948. /**
  86949. * Gets the number of targets stored in this manager
  86950. */
  86951. get: function () {
  86952. return this._targets.length;
  86953. },
  86954. enumerable: true,
  86955. configurable: true
  86956. });
  86957. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86958. /**
  86959. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86960. */
  86961. get: function () {
  86962. return this._activeTargets.length;
  86963. },
  86964. enumerable: true,
  86965. configurable: true
  86966. });
  86967. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86968. /**
  86969. * Gets the list of influences (one per target)
  86970. */
  86971. get: function () {
  86972. return this._influences;
  86973. },
  86974. enumerable: true,
  86975. configurable: true
  86976. });
  86977. /**
  86978. * Gets the active target at specified index. An active target is a target with an influence > 0
  86979. * @param index defines the index to check
  86980. * @returns the requested target
  86981. */
  86982. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86983. return this._activeTargets.data[index];
  86984. };
  86985. /**
  86986. * Gets the target at specified index
  86987. * @param index defines the index to check
  86988. * @returns the requested target
  86989. */
  86990. MorphTargetManager.prototype.getTarget = function (index) {
  86991. return this._targets[index];
  86992. };
  86993. /**
  86994. * Add a new target to this manager
  86995. * @param target defines the target to add
  86996. */
  86997. MorphTargetManager.prototype.addTarget = function (target) {
  86998. var _this = this;
  86999. this._targets.push(target);
  87000. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  87001. _this._syncActiveTargets(needUpdate);
  87002. }));
  87003. this._syncActiveTargets(true);
  87004. };
  87005. /**
  87006. * Removes a target from the manager
  87007. * @param target defines the target to remove
  87008. */
  87009. MorphTargetManager.prototype.removeTarget = function (target) {
  87010. var index = this._targets.indexOf(target);
  87011. if (index >= 0) {
  87012. this._targets.splice(index, 1);
  87013. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  87014. this._syncActiveTargets(true);
  87015. }
  87016. };
  87017. /**
  87018. * Serializes the current manager into a Serialization object
  87019. * @returns the serialized object
  87020. */
  87021. MorphTargetManager.prototype.serialize = function () {
  87022. var serializationObject = {};
  87023. serializationObject.id = this.uniqueId;
  87024. serializationObject.targets = [];
  87025. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  87026. var target = _a[_i];
  87027. serializationObject.targets.push(target.serialize());
  87028. }
  87029. return serializationObject;
  87030. };
  87031. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  87032. var influenceCount = 0;
  87033. this._activeTargets.reset();
  87034. this._supportsNormals = true;
  87035. this._supportsTangents = true;
  87036. this._vertexCount = 0;
  87037. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  87038. var target = _a[_i];
  87039. this._activeTargets.push(target);
  87040. this._tempInfluences[influenceCount++] = target.influence;
  87041. var positions = target.getPositions();
  87042. if (positions) {
  87043. this._supportsNormals = this._supportsNormals && target.hasNormals;
  87044. this._supportsTangents = this._supportsTangents && target.hasTangents;
  87045. var vertexCount = positions.length / 3;
  87046. if (this._vertexCount === 0) {
  87047. this._vertexCount = vertexCount;
  87048. }
  87049. else if (this._vertexCount !== vertexCount) {
  87050. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  87051. return;
  87052. }
  87053. }
  87054. }
  87055. if (!this._influences || this._influences.length !== influenceCount) {
  87056. this._influences = new Float32Array(influenceCount);
  87057. }
  87058. for (var index = 0; index < influenceCount; index++) {
  87059. this._influences[index] = this._tempInfluences[index];
  87060. }
  87061. if (needUpdate) {
  87062. this.synchronize();
  87063. }
  87064. };
  87065. /**
  87066. * Syncrhonize the targets with all the meshes using this morph target manager
  87067. */
  87068. MorphTargetManager.prototype.synchronize = function () {
  87069. if (!this._scene) {
  87070. return;
  87071. }
  87072. // Flag meshes as dirty to resync with the active targets
  87073. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  87074. var mesh = _a[_i];
  87075. if (mesh.morphTargetManager === this) {
  87076. mesh._syncGeometryWithMorphTargetManager();
  87077. }
  87078. }
  87079. };
  87080. // Statics
  87081. /**
  87082. * Creates a new MorphTargetManager from serialized data
  87083. * @param serializationObject defines the serialized data
  87084. * @param scene defines the hosting scene
  87085. * @returns the new MorphTargetManager
  87086. */
  87087. MorphTargetManager.Parse = function (serializationObject, scene) {
  87088. var result = new MorphTargetManager(scene);
  87089. result._uniqueId = serializationObject.id;
  87090. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  87091. var targetData = _a[_i];
  87092. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  87093. }
  87094. return result;
  87095. };
  87096. return MorphTargetManager;
  87097. }());
  87098. BABYLON.MorphTargetManager = MorphTargetManager;
  87099. })(BABYLON || (BABYLON = {}));
  87100. //# sourceMappingURL=babylon.morphTargetManager.js.map
  87101. var BABYLON;
  87102. (function (BABYLON) {
  87103. var Octree = /** @class */ (function () {
  87104. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  87105. if (maxDepth === void 0) { maxDepth = 2; }
  87106. this.maxDepth = maxDepth;
  87107. this.dynamicContent = new Array();
  87108. this._maxBlockCapacity = maxBlockCapacity || 64;
  87109. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  87110. this._creationFunc = creationFunc;
  87111. }
  87112. // Methods
  87113. Octree.prototype.update = function (worldMin, worldMax, entries) {
  87114. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  87115. };
  87116. Octree.prototype.addMesh = function (entry) {
  87117. for (var index = 0; index < this.blocks.length; index++) {
  87118. var block = this.blocks[index];
  87119. block.addEntry(entry);
  87120. }
  87121. };
  87122. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  87123. this._selectionContent.reset();
  87124. for (var index = 0; index < this.blocks.length; index++) {
  87125. var block = this.blocks[index];
  87126. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  87127. }
  87128. if (allowDuplicate) {
  87129. this._selectionContent.concat(this.dynamicContent);
  87130. }
  87131. else {
  87132. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87133. }
  87134. return this._selectionContent;
  87135. };
  87136. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  87137. this._selectionContent.reset();
  87138. for (var index = 0; index < this.blocks.length; index++) {
  87139. var block = this.blocks[index];
  87140. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  87141. }
  87142. if (allowDuplicate) {
  87143. this._selectionContent.concat(this.dynamicContent);
  87144. }
  87145. else {
  87146. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87147. }
  87148. return this._selectionContent;
  87149. };
  87150. Octree.prototype.intersectsRay = function (ray) {
  87151. this._selectionContent.reset();
  87152. for (var index = 0; index < this.blocks.length; index++) {
  87153. var block = this.blocks[index];
  87154. block.intersectsRay(ray, this._selectionContent);
  87155. }
  87156. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87157. return this._selectionContent;
  87158. };
  87159. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  87160. target.blocks = new Array();
  87161. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  87162. // Segmenting space
  87163. for (var x = 0; x < 2; x++) {
  87164. for (var y = 0; y < 2; y++) {
  87165. for (var z = 0; z < 2; z++) {
  87166. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  87167. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  87168. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  87169. block.addEntries(entries);
  87170. target.blocks.push(block);
  87171. }
  87172. }
  87173. }
  87174. };
  87175. Octree.CreationFuncForMeshes = function (entry, block) {
  87176. var boundingInfo = entry.getBoundingInfo();
  87177. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  87178. block.entries.push(entry);
  87179. }
  87180. };
  87181. Octree.CreationFuncForSubMeshes = function (entry, block) {
  87182. var boundingInfo = entry.getBoundingInfo();
  87183. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  87184. block.entries.push(entry);
  87185. }
  87186. };
  87187. return Octree;
  87188. }());
  87189. BABYLON.Octree = Octree;
  87190. })(BABYLON || (BABYLON = {}));
  87191. //# sourceMappingURL=babylon.octree.js.map
  87192. var BABYLON;
  87193. (function (BABYLON) {
  87194. var OctreeBlock = /** @class */ (function () {
  87195. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  87196. this.entries = new Array();
  87197. this._boundingVectors = new Array();
  87198. this._capacity = capacity;
  87199. this._depth = depth;
  87200. this._maxDepth = maxDepth;
  87201. this._creationFunc = creationFunc;
  87202. this._minPoint = minPoint;
  87203. this._maxPoint = maxPoint;
  87204. this._boundingVectors.push(minPoint.clone());
  87205. this._boundingVectors.push(maxPoint.clone());
  87206. this._boundingVectors.push(minPoint.clone());
  87207. this._boundingVectors[2].x = maxPoint.x;
  87208. this._boundingVectors.push(minPoint.clone());
  87209. this._boundingVectors[3].y = maxPoint.y;
  87210. this._boundingVectors.push(minPoint.clone());
  87211. this._boundingVectors[4].z = maxPoint.z;
  87212. this._boundingVectors.push(maxPoint.clone());
  87213. this._boundingVectors[5].z = minPoint.z;
  87214. this._boundingVectors.push(maxPoint.clone());
  87215. this._boundingVectors[6].x = minPoint.x;
  87216. this._boundingVectors.push(maxPoint.clone());
  87217. this._boundingVectors[7].y = minPoint.y;
  87218. }
  87219. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  87220. // Property
  87221. get: function () {
  87222. return this._capacity;
  87223. },
  87224. enumerable: true,
  87225. configurable: true
  87226. });
  87227. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  87228. get: function () {
  87229. return this._minPoint;
  87230. },
  87231. enumerable: true,
  87232. configurable: true
  87233. });
  87234. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  87235. get: function () {
  87236. return this._maxPoint;
  87237. },
  87238. enumerable: true,
  87239. configurable: true
  87240. });
  87241. // Methods
  87242. OctreeBlock.prototype.addEntry = function (entry) {
  87243. if (this.blocks) {
  87244. for (var index = 0; index < this.blocks.length; index++) {
  87245. var block = this.blocks[index];
  87246. block.addEntry(entry);
  87247. }
  87248. return;
  87249. }
  87250. this._creationFunc(entry, this);
  87251. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  87252. this.createInnerBlocks();
  87253. }
  87254. };
  87255. OctreeBlock.prototype.addEntries = function (entries) {
  87256. for (var index = 0; index < entries.length; index++) {
  87257. var mesh = entries[index];
  87258. this.addEntry(mesh);
  87259. }
  87260. };
  87261. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  87262. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  87263. if (this.blocks) {
  87264. for (var index = 0; index < this.blocks.length; index++) {
  87265. var block = this.blocks[index];
  87266. block.select(frustumPlanes, selection, allowDuplicate);
  87267. }
  87268. return;
  87269. }
  87270. if (allowDuplicate) {
  87271. selection.concat(this.entries);
  87272. }
  87273. else {
  87274. selection.concatWithNoDuplicate(this.entries);
  87275. }
  87276. }
  87277. };
  87278. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  87279. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  87280. if (this.blocks) {
  87281. for (var index = 0; index < this.blocks.length; index++) {
  87282. var block = this.blocks[index];
  87283. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  87284. }
  87285. return;
  87286. }
  87287. if (allowDuplicate) {
  87288. selection.concat(this.entries);
  87289. }
  87290. else {
  87291. selection.concatWithNoDuplicate(this.entries);
  87292. }
  87293. }
  87294. };
  87295. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  87296. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  87297. if (this.blocks) {
  87298. for (var index = 0; index < this.blocks.length; index++) {
  87299. var block = this.blocks[index];
  87300. block.intersectsRay(ray, selection);
  87301. }
  87302. return;
  87303. }
  87304. selection.concatWithNoDuplicate(this.entries);
  87305. }
  87306. };
  87307. OctreeBlock.prototype.createInnerBlocks = function () {
  87308. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  87309. };
  87310. return OctreeBlock;
  87311. }());
  87312. BABYLON.OctreeBlock = OctreeBlock;
  87313. })(BABYLON || (BABYLON = {}));
  87314. //# sourceMappingURL=babylon.octreeBlock.js.map
  87315. var BABYLON;
  87316. (function (BABYLON) {
  87317. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  87318. __extends(VRDistortionCorrectionPostProcess, _super);
  87319. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  87320. var _this = _super.call(this, name, "vrDistortionCorrection", [
  87321. 'LensCenter',
  87322. 'Scale',
  87323. 'ScaleIn',
  87324. 'HmdWarpParam'
  87325. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  87326. _this._isRightEye = isRightEye;
  87327. _this._distortionFactors = vrMetrics.distortionK;
  87328. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  87329. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  87330. _this.adaptScaleToCurrentViewport = true;
  87331. _this.onSizeChangedObservable.add(function () {
  87332. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  87333. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  87334. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  87335. });
  87336. _this.onApplyObservable.add(function (effect) {
  87337. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  87338. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  87339. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  87340. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  87341. });
  87342. return _this;
  87343. }
  87344. return VRDistortionCorrectionPostProcess;
  87345. }(BABYLON.PostProcess));
  87346. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  87347. })(BABYLON || (BABYLON = {}));
  87348. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  87349. var BABYLON;
  87350. (function (BABYLON) {
  87351. /**
  87352. * Postprocess used to generate anaglyphic rendering
  87353. */
  87354. var AnaglyphPostProcess = /** @class */ (function (_super) {
  87355. __extends(AnaglyphPostProcess, _super);
  87356. /**
  87357. * Creates a new AnaglyphPostProcess
  87358. * @param name defines postprocess name
  87359. * @param options defines creation options or target ratio scale
  87360. * @param rigCameras defines cameras using this postprocess
  87361. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  87362. * @param engine defines hosting engine
  87363. * @param reusable defines if the postprocess will be reused multiple times per frame
  87364. */
  87365. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  87366. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  87367. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87368. _this.onApplyObservable.add(function (effect) {
  87369. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87370. });
  87371. return _this;
  87372. }
  87373. return AnaglyphPostProcess;
  87374. }(BABYLON.PostProcess));
  87375. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87376. })(BABYLON || (BABYLON = {}));
  87377. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87378. var BABYLON;
  87379. (function (BABYLON) {
  87380. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87381. __extends(StereoscopicInterlacePostProcess, _super);
  87382. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87383. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87384. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87385. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87386. _this.onSizeChangedObservable.add(function () {
  87387. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87388. });
  87389. _this.onApplyObservable.add(function (effect) {
  87390. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87391. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87392. });
  87393. return _this;
  87394. }
  87395. return StereoscopicInterlacePostProcess;
  87396. }(BABYLON.PostProcess));
  87397. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87398. })(BABYLON || (BABYLON = {}));
  87399. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87400. var BABYLON;
  87401. (function (BABYLON) {
  87402. /**
  87403. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87404. * Screen rotation is taken into account.
  87405. */
  87406. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87407. function FreeCameraDeviceOrientationInput() {
  87408. var _this = this;
  87409. this._screenOrientationAngle = 0;
  87410. this._screenQuaternion = new BABYLON.Quaternion();
  87411. this._alpha = 0;
  87412. this._beta = 0;
  87413. this._gamma = 0;
  87414. this._orientationChanged = function () {
  87415. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87416. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87417. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87418. };
  87419. this._deviceOrientation = function (evt) {
  87420. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87421. _this._beta = evt.beta !== null ? evt.beta : 0;
  87422. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87423. };
  87424. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87425. this._orientationChanged();
  87426. }
  87427. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87428. get: function () {
  87429. return this._camera;
  87430. },
  87431. set: function (camera) {
  87432. this._camera = camera;
  87433. if (this._camera != null && !this._camera.rotationQuaternion) {
  87434. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87435. }
  87436. },
  87437. enumerable: true,
  87438. configurable: true
  87439. });
  87440. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87441. window.addEventListener("orientationchange", this._orientationChanged);
  87442. window.addEventListener("deviceorientation", this._deviceOrientation);
  87443. //In certain cases, the attach control is called AFTER orientation was changed,
  87444. //So this is needed.
  87445. this._orientationChanged();
  87446. };
  87447. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87448. window.removeEventListener("orientationchange", this._orientationChanged);
  87449. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87450. };
  87451. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87452. //if no device orientation provided, don't update the rotation.
  87453. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87454. if (!this._alpha)
  87455. return;
  87456. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87457. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87458. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87459. //Mirror on XY Plane
  87460. this._camera.rotationQuaternion.z *= -1;
  87461. this._camera.rotationQuaternion.w *= -1;
  87462. };
  87463. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87464. return "FreeCameraDeviceOrientationInput";
  87465. };
  87466. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87467. return "deviceOrientation";
  87468. };
  87469. return FreeCameraDeviceOrientationInput;
  87470. }());
  87471. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87472. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87473. })(BABYLON || (BABYLON = {}));
  87474. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87475. var BABYLON;
  87476. (function (BABYLON) {
  87477. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87478. function ArcRotateCameraVRDeviceOrientationInput() {
  87479. this.alphaCorrection = 1;
  87480. this.betaCorrection = 1;
  87481. this.gammaCorrection = 1;
  87482. this._alpha = 0;
  87483. this._gamma = 0;
  87484. this._dirty = false;
  87485. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87486. }
  87487. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87488. this.camera.attachControl(element, noPreventDefault);
  87489. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87490. };
  87491. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87492. if (evt.alpha !== null) {
  87493. this._alpha = +evt.alpha | 0;
  87494. }
  87495. if (evt.gamma !== null) {
  87496. this._gamma = +evt.gamma | 0;
  87497. }
  87498. this._dirty = true;
  87499. };
  87500. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87501. if (this._dirty) {
  87502. this._dirty = false;
  87503. if (this._gamma < 0) {
  87504. this._gamma = 180 + this._gamma;
  87505. }
  87506. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87507. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87508. }
  87509. };
  87510. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87511. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87512. };
  87513. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87514. return "ArcRotateCameraVRDeviceOrientationInput";
  87515. };
  87516. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87517. return "VRDeviceOrientation";
  87518. };
  87519. return ArcRotateCameraVRDeviceOrientationInput;
  87520. }());
  87521. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87522. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87523. })(BABYLON || (BABYLON = {}));
  87524. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87525. var BABYLON;
  87526. (function (BABYLON) {
  87527. var VRCameraMetrics = /** @class */ (function () {
  87528. function VRCameraMetrics() {
  87529. this.compensateDistortion = true;
  87530. }
  87531. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87532. get: function () {
  87533. return this.hResolution / (2 * this.vResolution);
  87534. },
  87535. enumerable: true,
  87536. configurable: true
  87537. });
  87538. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87539. get: function () {
  87540. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87541. },
  87542. enumerable: true,
  87543. configurable: true
  87544. });
  87545. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87546. get: function () {
  87547. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87548. var h = (4 * meters) / this.hScreenSize;
  87549. return BABYLON.Matrix.Translation(h, 0, 0);
  87550. },
  87551. enumerable: true,
  87552. configurable: true
  87553. });
  87554. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87555. get: function () {
  87556. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87557. var h = (4 * meters) / this.hScreenSize;
  87558. return BABYLON.Matrix.Translation(-h, 0, 0);
  87559. },
  87560. enumerable: true,
  87561. configurable: true
  87562. });
  87563. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87564. get: function () {
  87565. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87566. },
  87567. enumerable: true,
  87568. configurable: true
  87569. });
  87570. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87571. get: function () {
  87572. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87573. },
  87574. enumerable: true,
  87575. configurable: true
  87576. });
  87577. VRCameraMetrics.GetDefault = function () {
  87578. var result = new VRCameraMetrics();
  87579. result.hResolution = 1280;
  87580. result.vResolution = 800;
  87581. result.hScreenSize = 0.149759993;
  87582. result.vScreenSize = 0.0935999975;
  87583. result.vScreenCenter = 0.0467999987;
  87584. result.eyeToScreenDistance = 0.0410000011;
  87585. result.lensSeparationDistance = 0.0635000020;
  87586. result.interpupillaryDistance = 0.0640000030;
  87587. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87588. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87589. result.postProcessScaleFactor = 1.714605507808412;
  87590. result.lensCenterOffset = 0.151976421;
  87591. return result;
  87592. };
  87593. return VRCameraMetrics;
  87594. }());
  87595. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87596. })(BABYLON || (BABYLON = {}));
  87597. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87598. var BABYLON;
  87599. (function (BABYLON) {
  87600. /**
  87601. * This represents a WebVR camera.
  87602. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87603. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87604. */
  87605. var WebVRFreeCamera = /** @class */ (function (_super) {
  87606. __extends(WebVRFreeCamera, _super);
  87607. /**
  87608. * Instantiates a WebVRFreeCamera.
  87609. * @param name The name of the WebVRFreeCamera
  87610. * @param position The starting anchor position for the camera
  87611. * @param scene The scene the camera belongs to
  87612. * @param webVROptions a set of customizable options for the webVRCamera
  87613. */
  87614. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87615. if (webVROptions === void 0) { webVROptions = {}; }
  87616. var _this = _super.call(this, name, position, scene) || this;
  87617. _this.webVROptions = webVROptions;
  87618. /**
  87619. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87620. */
  87621. _this._vrDevice = null;
  87622. /**
  87623. * The rawPose of the vrDevice.
  87624. */
  87625. _this.rawPose = null;
  87626. _this._specsVersion = "1.1";
  87627. _this._attached = false;
  87628. _this._descendants = [];
  87629. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87630. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87631. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87632. _this._standingMatrix = null;
  87633. /**
  87634. * Represents device position in babylon space.
  87635. */
  87636. _this.devicePosition = BABYLON.Vector3.Zero();
  87637. /**
  87638. * Represents device rotation in babylon space.
  87639. */
  87640. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87641. /**
  87642. * The scale of the device to be used when translating from device space to babylon space.
  87643. */
  87644. _this.deviceScaleFactor = 1;
  87645. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87646. _this._worldToDevice = BABYLON.Matrix.Identity();
  87647. /**
  87648. * References to the webVR controllers for the vrDevice.
  87649. */
  87650. _this.controllers = [];
  87651. /**
  87652. * Emits an event when a controller is attached.
  87653. */
  87654. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87655. /**
  87656. * Emits an event when a controller's mesh has been loaded;
  87657. */
  87658. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87659. /**
  87660. * If the rig cameras be used as parent instead of this camera.
  87661. */
  87662. _this.rigParenting = true;
  87663. _this._defaultHeight = undefined;
  87664. _this._workingVector = BABYLON.Vector3.Zero();
  87665. _this._oneVector = BABYLON.Vector3.One();
  87666. _this._workingMatrix = BABYLON.Matrix.Identity();
  87667. _this._cache.position = BABYLON.Vector3.Zero();
  87668. if (webVROptions.defaultHeight) {
  87669. _this._defaultHeight = webVROptions.defaultHeight;
  87670. _this.position.y = _this._defaultHeight;
  87671. }
  87672. _this.minZ = 0.1;
  87673. //legacy support - the compensation boolean was removed.
  87674. if (arguments.length === 5) {
  87675. _this.webVROptions = arguments[4];
  87676. }
  87677. // default webVR options
  87678. if (_this.webVROptions.trackPosition == undefined) {
  87679. _this.webVROptions.trackPosition = true;
  87680. }
  87681. if (_this.webVROptions.controllerMeshes == undefined) {
  87682. _this.webVROptions.controllerMeshes = true;
  87683. }
  87684. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87685. _this.webVROptions.defaultLightingOnControllers = true;
  87686. }
  87687. _this.rotationQuaternion = new BABYLON.Quaternion();
  87688. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87689. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87690. }
  87691. //enable VR
  87692. var engine = _this.getEngine();
  87693. _this._onVREnabled = function (success) { if (success) {
  87694. _this.initControllers();
  87695. } };
  87696. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87697. engine.initWebVR().add(function (event) {
  87698. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87699. return;
  87700. }
  87701. _this._vrDevice = event.vrDisplay;
  87702. //reset the rig parameters.
  87703. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87704. if (_this._attached) {
  87705. _this.getEngine().enableVR();
  87706. }
  87707. });
  87708. if (typeof (VRFrameData) !== "undefined")
  87709. _this._frameData = new VRFrameData();
  87710. /**
  87711. * The idea behind the following lines:
  87712. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87713. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87714. * the second will not show it correctly.
  87715. *
  87716. * To solve this - each object that has the camera as parent will be added to a protected array.
  87717. * When the rig camera renders, it will take this array and set all of those to be its children.
  87718. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87719. * Amazing!
  87720. */
  87721. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87722. if (camera.parent === _this && _this.rigParenting) {
  87723. _this._descendants = _this.getDescendants(true, function (n) {
  87724. // don't take the cameras or the controllers!
  87725. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87726. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87727. return !isController && !isRigCamera;
  87728. });
  87729. _this._descendants.forEach(function (node) {
  87730. node.parent = camera;
  87731. });
  87732. }
  87733. });
  87734. scene.onAfterCameraRenderObservable.add(function (camera) {
  87735. if (camera.parent === _this && _this.rigParenting) {
  87736. _this._descendants.forEach(function (node) {
  87737. node.parent = _this;
  87738. });
  87739. }
  87740. });
  87741. return _this;
  87742. }
  87743. /**
  87744. * Gets the device distance from the ground in meters.
  87745. * @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.
  87746. */
  87747. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87748. if (this._standingMatrix) {
  87749. // Add standing matrix offset to get real offset from ground in room
  87750. this._standingMatrix.getTranslationToRef(this._workingVector);
  87751. return this._deviceRoomPosition.y + this._workingVector.y;
  87752. }
  87753. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87754. return this._defaultHeight || 0;
  87755. };
  87756. /**
  87757. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87758. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87759. */
  87760. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87761. var _this = this;
  87762. if (callback === void 0) { callback = function (bool) { }; }
  87763. // Use standing matrix if available
  87764. this.getEngine().initWebVRAsync().then(function (result) {
  87765. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87766. callback(false);
  87767. }
  87768. else {
  87769. _this._standingMatrix = new BABYLON.Matrix();
  87770. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87771. if (!_this.getScene().useRightHandedSystem) {
  87772. [2, 6, 8, 9, 14].forEach(function (num) {
  87773. if (_this._standingMatrix) {
  87774. _this._standingMatrix.m[num] *= -1;
  87775. }
  87776. });
  87777. }
  87778. callback(true);
  87779. }
  87780. });
  87781. };
  87782. /**
  87783. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87784. * @returns A promise with a boolean set to if the standing matrix is supported.
  87785. */
  87786. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87787. var _this = this;
  87788. return new Promise(function (res, rej) {
  87789. _this.useStandingMatrix(function (supported) {
  87790. res(supported);
  87791. });
  87792. });
  87793. };
  87794. /**
  87795. * Disposes the camera
  87796. */
  87797. WebVRFreeCamera.prototype.dispose = function () {
  87798. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87799. _super.prototype.dispose.call(this);
  87800. };
  87801. /**
  87802. * Gets a vrController by name.
  87803. * @param name The name of the controller to retreive
  87804. * @returns the controller matching the name specified or null if not found
  87805. */
  87806. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87807. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87808. var gp = _a[_i];
  87809. if (gp.hand === name) {
  87810. return gp;
  87811. }
  87812. }
  87813. return null;
  87814. };
  87815. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87816. /**
  87817. * The controller corrisponding to the users left hand.
  87818. */
  87819. get: function () {
  87820. if (!this._leftController) {
  87821. this._leftController = this.getControllerByName("left");
  87822. }
  87823. return this._leftController;
  87824. },
  87825. enumerable: true,
  87826. configurable: true
  87827. });
  87828. ;
  87829. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87830. /**
  87831. * The controller corrisponding to the users right hand.
  87832. */
  87833. get: function () {
  87834. if (!this._rightController) {
  87835. this._rightController = this.getControllerByName("right");
  87836. }
  87837. return this._rightController;
  87838. },
  87839. enumerable: true,
  87840. configurable: true
  87841. });
  87842. ;
  87843. /**
  87844. * Casts a ray forward from the vrCamera's gaze.
  87845. * @param length Length of the ray (default: 100)
  87846. * @returns the ray corrisponding to the gaze
  87847. */
  87848. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87849. if (length === void 0) { length = 100; }
  87850. if (this.leftCamera) {
  87851. // Use left eye to avoid computation to compute center on every call
  87852. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87853. }
  87854. else {
  87855. return _super.prototype.getForwardRay.call(this, length);
  87856. }
  87857. };
  87858. /**
  87859. * Updates the camera based on device's frame data
  87860. */
  87861. WebVRFreeCamera.prototype._checkInputs = function () {
  87862. if (this._vrDevice && this._vrDevice.isPresenting) {
  87863. this._vrDevice.getFrameData(this._frameData);
  87864. this.updateFromDevice(this._frameData.pose);
  87865. }
  87866. _super.prototype._checkInputs.call(this);
  87867. };
  87868. /**
  87869. * Updates the poseControlled values based on the input device pose.
  87870. * @param poseData Pose coming from the device
  87871. */
  87872. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87873. if (poseData && poseData.orientation) {
  87874. this.rawPose = poseData;
  87875. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87876. if (this.getScene().useRightHandedSystem) {
  87877. this._deviceRoomRotationQuaternion.z *= -1;
  87878. this._deviceRoomRotationQuaternion.w *= -1;
  87879. }
  87880. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87881. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87882. if (this.getScene().useRightHandedSystem) {
  87883. this._deviceRoomPosition.z *= -1;
  87884. }
  87885. }
  87886. }
  87887. };
  87888. /**
  87889. * WebVR's attach control will start broadcasting frames to the device.
  87890. * Note that in certain browsers (chrome for example) this function must be called
  87891. * within a user-interaction callback. Example:
  87892. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87893. *
  87894. * @param element html element to attach the vrDevice to
  87895. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87896. */
  87897. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87898. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87899. this._attached = true;
  87900. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87901. if (this._vrDevice) {
  87902. this.getEngine().enableVR();
  87903. }
  87904. };
  87905. /**
  87906. * Detaches the camera from the html element and disables VR
  87907. *
  87908. * @param element html element to detach from
  87909. */
  87910. WebVRFreeCamera.prototype.detachControl = function (element) {
  87911. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87912. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87913. _super.prototype.detachControl.call(this, element);
  87914. this._attached = false;
  87915. this.getEngine().disableVR();
  87916. };
  87917. /**
  87918. * @returns the name of this class
  87919. */
  87920. WebVRFreeCamera.prototype.getClassName = function () {
  87921. return "WebVRFreeCamera";
  87922. };
  87923. /**
  87924. * Calls resetPose on the vrDisplay
  87925. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87926. */
  87927. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87928. //uses the vrDisplay's "resetPose()".
  87929. //pitch and roll won't be affected.
  87930. this._vrDevice.resetPose();
  87931. };
  87932. /**
  87933. * Updates the rig cameras (left and right eye)
  87934. */
  87935. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87936. var camLeft = this._rigCameras[0];
  87937. var camRight = this._rigCameras[1];
  87938. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87939. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87940. camLeft.position.copyFrom(this._deviceRoomPosition);
  87941. camRight.position.copyFrom(this._deviceRoomPosition);
  87942. };
  87943. /**
  87944. * Updates the cached values of the camera
  87945. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87946. */
  87947. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87948. var _this = this;
  87949. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87950. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87951. if (!this.updateCacheCalled) {
  87952. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87953. this.updateCacheCalled = true;
  87954. this.update();
  87955. }
  87956. // Set working vector to the device position in room space rotated by the new rotation
  87957. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87958. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87959. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87960. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87961. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87962. // Add translation from anchor position
  87963. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87964. this._workingVector.addInPlace(this.position);
  87965. this._workingVector.subtractInPlace(this._cache.position);
  87966. this._deviceToWorld.setTranslation(this._workingVector);
  87967. // Set an inverted matrix to be used when updating the camera
  87968. this._deviceToWorld.invertToRef(this._worldToDevice);
  87969. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87970. this.controllers.forEach(function (controller) {
  87971. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87972. controller.update();
  87973. });
  87974. }
  87975. if (!ignoreParentClass) {
  87976. _super.prototype._updateCache.call(this);
  87977. }
  87978. this.updateCacheCalled = false;
  87979. };
  87980. /**
  87981. * Updates the current device position and rotation in the babylon world
  87982. */
  87983. WebVRFreeCamera.prototype.update = function () {
  87984. // Get current device position in babylon world
  87985. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87986. // Get current device rotation in babylon world
  87987. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87988. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87989. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87990. _super.prototype.update.call(this);
  87991. };
  87992. /**
  87993. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87994. * @returns an identity matrix
  87995. */
  87996. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87997. return BABYLON.Matrix.Identity();
  87998. };
  87999. /**
  88000. * This function is called by the two RIG cameras.
  88001. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  88002. */
  88003. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  88004. var _this = this;
  88005. // Update the parent camera prior to using a child camera to avoid desynchronization
  88006. var parentCamera = this._cameraRigParams["parentCamera"];
  88007. parentCamera._updateCache();
  88008. //WebVR 1.1
  88009. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  88010. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  88011. if (!this.getScene().useRightHandedSystem) {
  88012. [2, 6, 8, 9, 14].forEach(function (num) {
  88013. _this._webvrViewMatrix.m[num] *= -1;
  88014. });
  88015. }
  88016. // update the camera rotation matrix
  88017. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  88018. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  88019. // Computing target and final matrix
  88020. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  88021. // should the view matrix be updated with scale and position offset?
  88022. if (parentCamera.deviceScaleFactor !== 1) {
  88023. this._webvrViewMatrix.invert();
  88024. // scale the position, if set
  88025. if (parentCamera.deviceScaleFactor) {
  88026. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  88027. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  88028. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  88029. }
  88030. this._webvrViewMatrix.invert();
  88031. }
  88032. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  88033. // Compute global position
  88034. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  88035. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  88036. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  88037. this._workingMatrix.getTranslationToRef(this._globalPosition);
  88038. this._markSyncedWithParent();
  88039. return this._webvrViewMatrix;
  88040. };
  88041. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  88042. var _this = this;
  88043. var parentCamera = this.parent;
  88044. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  88045. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  88046. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  88047. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  88048. //babylon compatible matrix
  88049. if (!this.getScene().useRightHandedSystem) {
  88050. [8, 9, 10, 11].forEach(function (num) {
  88051. _this._projectionMatrix.m[num] *= -1;
  88052. });
  88053. }
  88054. return this._projectionMatrix;
  88055. };
  88056. /**
  88057. * Initializes the controllers and their meshes
  88058. */
  88059. WebVRFreeCamera.prototype.initControllers = function () {
  88060. var _this = this;
  88061. this.controllers = [];
  88062. var manager = this.getScene().gamepadManager;
  88063. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  88064. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  88065. var webVrController = gamepad;
  88066. if (webVrController.defaultModel) {
  88067. webVrController.defaultModel.setEnabled(false);
  88068. }
  88069. if (webVrController.hand === "right") {
  88070. _this._rightController = null;
  88071. }
  88072. if (webVrController.hand === "left") {
  88073. _this._leftController = null;
  88074. }
  88075. var controllerIndex = _this.controllers.indexOf(webVrController);
  88076. if (controllerIndex !== -1) {
  88077. _this.controllers.splice(controllerIndex, 1);
  88078. }
  88079. }
  88080. });
  88081. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  88082. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  88083. var webVrController_1 = gamepad;
  88084. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  88085. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  88086. if (_this.webVROptions.controllerMeshes) {
  88087. if (webVrController_1.defaultModel) {
  88088. webVrController_1.defaultModel.setEnabled(true);
  88089. }
  88090. else {
  88091. // Load the meshes
  88092. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  88093. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  88094. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  88095. if (_this.webVROptions.defaultLightingOnControllers) {
  88096. if (!_this._lightOnControllers) {
  88097. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  88098. }
  88099. var activateLightOnSubMeshes_1 = function (mesh, light) {
  88100. var children = mesh.getChildren();
  88101. if (children.length !== 0) {
  88102. children.forEach(function (mesh) {
  88103. light.includedOnlyMeshes.push(mesh);
  88104. activateLightOnSubMeshes_1(mesh, light);
  88105. });
  88106. }
  88107. };
  88108. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  88109. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  88110. }
  88111. });
  88112. }
  88113. }
  88114. webVrController_1.attachToPoseControlledCamera(_this);
  88115. // since this is async - sanity check. Is the controller already stored?
  88116. if (_this.controllers.indexOf(webVrController_1) === -1) {
  88117. //add to the controllers array
  88118. _this.controllers.push(webVrController_1);
  88119. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  88120. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  88121. // So we're overriding setting left & right manually to be sure
  88122. var firstViveWandDetected = false;
  88123. for (var i = 0; i < _this.controllers.length; i++) {
  88124. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88125. if (!firstViveWandDetected) {
  88126. firstViveWandDetected = true;
  88127. _this.controllers[i].hand = "left";
  88128. }
  88129. else {
  88130. _this.controllers[i].hand = "right";
  88131. }
  88132. }
  88133. }
  88134. //did we find enough controllers? Great! let the developer know.
  88135. if (_this.controllers.length >= 2) {
  88136. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  88137. }
  88138. }
  88139. }
  88140. });
  88141. };
  88142. return WebVRFreeCamera;
  88143. }(BABYLON.FreeCamera));
  88144. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  88145. })(BABYLON || (BABYLON = {}));
  88146. //# sourceMappingURL=babylon.webVRCamera.js.map
  88147. var BABYLON;
  88148. (function (BABYLON) {
  88149. // We're mainly based on the logic defined into the FreeCamera code
  88150. /**
  88151. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  88152. * being tilted forward or back and left or right.
  88153. */
  88154. var DeviceOrientationCamera = /** @class */ (function (_super) {
  88155. __extends(DeviceOrientationCamera, _super);
  88156. /**
  88157. * Creates a new device orientation camera
  88158. * @param name The name of the camera
  88159. * @param position The start position camera
  88160. * @param scene The scene the camera belongs to
  88161. */
  88162. function DeviceOrientationCamera(name, position, scene) {
  88163. var _this = _super.call(this, name, position, scene) || this;
  88164. _this._quaternionCache = new BABYLON.Quaternion();
  88165. _this.inputs.addDeviceOrientation();
  88166. return _this;
  88167. }
  88168. /**
  88169. * Gets the current instance class name ("DeviceOrientationCamera").
  88170. * This helps avoiding instanceof at run time.
  88171. * @returns the class name
  88172. */
  88173. DeviceOrientationCamera.prototype.getClassName = function () {
  88174. return "DeviceOrientationCamera";
  88175. };
  88176. /**
  88177. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  88178. */
  88179. DeviceOrientationCamera.prototype._checkInputs = function () {
  88180. _super.prototype._checkInputs.call(this);
  88181. this._quaternionCache.copyFrom(this.rotationQuaternion);
  88182. if (this._initialQuaternion) {
  88183. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  88184. }
  88185. };
  88186. /**
  88187. * Reset the camera to its default orientation on the specified axis only.
  88188. * @param axis The axis to reset
  88189. */
  88190. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  88191. var _this = this;
  88192. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  88193. //can only work if this camera has a rotation quaternion already.
  88194. if (!this.rotationQuaternion)
  88195. return;
  88196. if (!this._initialQuaternion) {
  88197. this._initialQuaternion = new BABYLON.Quaternion();
  88198. }
  88199. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  88200. ['x', 'y', 'z'].forEach(function (axisName) {
  88201. if (!axis[axisName]) {
  88202. _this._initialQuaternion[axisName] = 0;
  88203. }
  88204. else {
  88205. _this._initialQuaternion[axisName] *= -1;
  88206. }
  88207. });
  88208. this._initialQuaternion.normalize();
  88209. //force rotation update
  88210. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  88211. };
  88212. return DeviceOrientationCamera;
  88213. }(BABYLON.FreeCamera));
  88214. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  88215. })(BABYLON || (BABYLON = {}));
  88216. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  88217. var BABYLON;
  88218. (function (BABYLON) {
  88219. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  88220. __extends(VRDeviceOrientationFreeCamera, _super);
  88221. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  88222. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88223. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88224. var _this = _super.call(this, name, position, scene) || this;
  88225. vrCameraMetrics.compensateDistortion = compensateDistortion;
  88226. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  88227. return _this;
  88228. }
  88229. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  88230. return "VRDeviceOrientationFreeCamera";
  88231. };
  88232. return VRDeviceOrientationFreeCamera;
  88233. }(BABYLON.DeviceOrientationCamera));
  88234. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  88235. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  88236. __extends(VRDeviceOrientationGamepadCamera, _super);
  88237. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  88238. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88239. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88240. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  88241. _this.inputs.addGamepad();
  88242. return _this;
  88243. }
  88244. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  88245. return "VRDeviceOrientationGamepadCamera";
  88246. };
  88247. return VRDeviceOrientationGamepadCamera;
  88248. }(VRDeviceOrientationFreeCamera));
  88249. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  88250. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  88251. __extends(VRDeviceOrientationArcRotateCamera, _super);
  88252. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  88253. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88254. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88255. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88256. vrCameraMetrics.compensateDistortion = compensateDistortion;
  88257. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  88258. _this.inputs.addVRDeviceOrientation();
  88259. return _this;
  88260. }
  88261. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  88262. return "VRDeviceOrientationArcRotateCamera";
  88263. };
  88264. return VRDeviceOrientationArcRotateCamera;
  88265. }(BABYLON.ArcRotateCamera));
  88266. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  88267. })(BABYLON || (BABYLON = {}));
  88268. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  88269. var BABYLON;
  88270. (function (BABYLON) {
  88271. /**
  88272. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  88273. */
  88274. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  88275. __extends(AnaglyphFreeCamera, _super);
  88276. /**
  88277. * Creates a new AnaglyphFreeCamera
  88278. * @param name defines camera name
  88279. * @param position defines initial position
  88280. * @param interaxialDistance defines distance between each color axis
  88281. * @param scene defines the hosting scene
  88282. */
  88283. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  88284. var _this = _super.call(this, name, position, scene) || this;
  88285. _this.interaxialDistance = interaxialDistance;
  88286. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88287. return _this;
  88288. }
  88289. /**
  88290. * Gets camera class name
  88291. * @returns AnaglyphFreeCamera
  88292. */
  88293. AnaglyphFreeCamera.prototype.getClassName = function () {
  88294. return "AnaglyphFreeCamera";
  88295. };
  88296. return AnaglyphFreeCamera;
  88297. }(BABYLON.FreeCamera));
  88298. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  88299. /**
  88300. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  88301. */
  88302. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  88303. __extends(AnaglyphArcRotateCamera, _super);
  88304. /**
  88305. * Creates a new AnaglyphArcRotateCamera
  88306. * @param name defines camera name
  88307. * @param alpha defines alpha angle (in radians)
  88308. * @param beta defines beta angle (in radians)
  88309. * @param radius defines radius
  88310. * @param target defines camera target
  88311. * @param interaxialDistance defines distance between each color axis
  88312. * @param scene defines the hosting scene
  88313. */
  88314. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  88315. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88316. _this.interaxialDistance = interaxialDistance;
  88317. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88318. return _this;
  88319. }
  88320. /**
  88321. * Gets camera class name
  88322. * @returns AnaglyphArcRotateCamera
  88323. */
  88324. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  88325. return "AnaglyphArcRotateCamera";
  88326. };
  88327. return AnaglyphArcRotateCamera;
  88328. }(BABYLON.ArcRotateCamera));
  88329. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  88330. /**
  88331. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  88332. */
  88333. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  88334. __extends(AnaglyphGamepadCamera, _super);
  88335. /**
  88336. * Creates a new AnaglyphGamepadCamera
  88337. * @param name defines camera name
  88338. * @param position defines initial position
  88339. * @param interaxialDistance defines distance between each color axis
  88340. * @param scene defines the hosting scene
  88341. */
  88342. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  88343. var _this = _super.call(this, name, position, scene) || this;
  88344. _this.interaxialDistance = interaxialDistance;
  88345. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88346. return _this;
  88347. }
  88348. /**
  88349. * Gets camera class name
  88350. * @returns AnaglyphGamepadCamera
  88351. */
  88352. AnaglyphGamepadCamera.prototype.getClassName = function () {
  88353. return "AnaglyphGamepadCamera";
  88354. };
  88355. return AnaglyphGamepadCamera;
  88356. }(BABYLON.GamepadCamera));
  88357. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  88358. /**
  88359. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  88360. */
  88361. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  88362. __extends(AnaglyphUniversalCamera, _super);
  88363. /**
  88364. * Creates a new AnaglyphUniversalCamera
  88365. * @param name defines camera name
  88366. * @param position defines initial position
  88367. * @param interaxialDistance defines distance between each color axis
  88368. * @param scene defines the hosting scene
  88369. */
  88370. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88371. var _this = _super.call(this, name, position, scene) || this;
  88372. _this.interaxialDistance = interaxialDistance;
  88373. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88374. return _this;
  88375. }
  88376. /**
  88377. * Gets camera class name
  88378. * @returns AnaglyphUniversalCamera
  88379. */
  88380. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88381. return "AnaglyphUniversalCamera";
  88382. };
  88383. return AnaglyphUniversalCamera;
  88384. }(BABYLON.UniversalCamera));
  88385. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88386. /**
  88387. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88388. */
  88389. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88390. __extends(StereoscopicFreeCamera, _super);
  88391. /**
  88392. * Creates a new StereoscopicFreeCamera
  88393. * @param name defines camera name
  88394. * @param position defines initial position
  88395. * @param interaxialDistance defines distance between each color axis
  88396. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88397. * @param scene defines the hosting scene
  88398. */
  88399. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88400. var _this = _super.call(this, name, position, scene) || this;
  88401. _this.interaxialDistance = interaxialDistance;
  88402. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88403. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88404. return _this;
  88405. }
  88406. /**
  88407. * Gets camera class name
  88408. * @returns StereoscopicFreeCamera
  88409. */
  88410. StereoscopicFreeCamera.prototype.getClassName = function () {
  88411. return "StereoscopicFreeCamera";
  88412. };
  88413. return StereoscopicFreeCamera;
  88414. }(BABYLON.FreeCamera));
  88415. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88416. /**
  88417. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88418. */
  88419. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88420. __extends(StereoscopicArcRotateCamera, _super);
  88421. /**
  88422. * Creates a new StereoscopicArcRotateCamera
  88423. * @param name defines camera name
  88424. * @param alpha defines alpha angle (in radians)
  88425. * @param beta defines beta angle (in radians)
  88426. * @param radius defines radius
  88427. * @param target defines camera target
  88428. * @param interaxialDistance defines distance between each color axis
  88429. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88430. * @param scene defines the hosting scene
  88431. */
  88432. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88433. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88434. _this.interaxialDistance = interaxialDistance;
  88435. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88436. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88437. return _this;
  88438. }
  88439. /**
  88440. * Gets camera class name
  88441. * @returns StereoscopicArcRotateCamera
  88442. */
  88443. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88444. return "StereoscopicArcRotateCamera";
  88445. };
  88446. return StereoscopicArcRotateCamera;
  88447. }(BABYLON.ArcRotateCamera));
  88448. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88449. /**
  88450. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88451. */
  88452. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88453. __extends(StereoscopicGamepadCamera, _super);
  88454. /**
  88455. * Creates a new StereoscopicGamepadCamera
  88456. * @param name defines camera name
  88457. * @param position defines initial position
  88458. * @param interaxialDistance defines distance between each color axis
  88459. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88460. * @param scene defines the hosting scene
  88461. */
  88462. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88463. var _this = _super.call(this, name, position, scene) || this;
  88464. _this.interaxialDistance = interaxialDistance;
  88465. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88466. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88467. return _this;
  88468. }
  88469. /**
  88470. * Gets camera class name
  88471. * @returns StereoscopicGamepadCamera
  88472. */
  88473. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88474. return "StereoscopicGamepadCamera";
  88475. };
  88476. return StereoscopicGamepadCamera;
  88477. }(BABYLON.GamepadCamera));
  88478. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88479. /**
  88480. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88481. */
  88482. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88483. __extends(StereoscopicUniversalCamera, _super);
  88484. /**
  88485. * Creates a new StereoscopicUniversalCamera
  88486. * @param name defines camera name
  88487. * @param position defines initial position
  88488. * @param interaxialDistance defines distance between each color axis
  88489. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88490. * @param scene defines the hosting scene
  88491. */
  88492. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88493. var _this = _super.call(this, name, position, scene) || this;
  88494. _this.interaxialDistance = interaxialDistance;
  88495. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88496. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88497. return _this;
  88498. }
  88499. /**
  88500. * Gets camera class name
  88501. * @returns StereoscopicUniversalCamera
  88502. */
  88503. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88504. return "StereoscopicUniversalCamera";
  88505. };
  88506. return StereoscopicUniversalCamera;
  88507. }(BABYLON.UniversalCamera));
  88508. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88509. })(BABYLON || (BABYLON = {}));
  88510. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88511. var BABYLON;
  88512. (function (BABYLON) {
  88513. var VRExperienceHelperGazer = /** @class */ (function () {
  88514. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88515. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88516. this.scene = scene;
  88517. this._pointerDownOnMeshAsked = false;
  88518. this._isActionableMesh = false;
  88519. this._teleportationRequestInitiated = false;
  88520. this._teleportationBackRequestInitiated = false;
  88521. this._rotationRightAsked = false;
  88522. this._rotationLeftAsked = false;
  88523. this._dpadPressed = true;
  88524. this._activePointer = false;
  88525. this._id = VRExperienceHelperGazer._idCounter++;
  88526. // Gaze tracker
  88527. if (!gazeTrackerToClone) {
  88528. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88529. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88530. this._gazeTracker.isPickable = false;
  88531. this._gazeTracker.isVisible = false;
  88532. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88533. targetMat.specularColor = BABYLON.Color3.Black();
  88534. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88535. targetMat.backFaceCulling = false;
  88536. this._gazeTracker.material = targetMat;
  88537. }
  88538. else {
  88539. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88540. }
  88541. }
  88542. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88543. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88544. };
  88545. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88546. this._pointerDownOnMeshAsked = true;
  88547. if (this._currentHit) {
  88548. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88549. }
  88550. };
  88551. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88552. if (this._currentHit) {
  88553. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88554. }
  88555. this._pointerDownOnMeshAsked = false;
  88556. };
  88557. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88558. this._activePointer = true;
  88559. };
  88560. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88561. this._activePointer = false;
  88562. };
  88563. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88564. if (distance === void 0) { distance = 100; }
  88565. };
  88566. VRExperienceHelperGazer.prototype.dispose = function () {
  88567. this._interactionsEnabled = false;
  88568. this._teleportationEnabled = false;
  88569. if (this._gazeTracker) {
  88570. this._gazeTracker.dispose();
  88571. }
  88572. };
  88573. VRExperienceHelperGazer._idCounter = 0;
  88574. return VRExperienceHelperGazer;
  88575. }());
  88576. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88577. __extends(VRExperienceHelperControllerGazer, _super);
  88578. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88579. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88580. _this.webVRController = webVRController;
  88581. // Laser pointer
  88582. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88583. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88584. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88585. laserPointerMaterial.alpha = 0.6;
  88586. _this._laserPointer.material = laserPointerMaterial;
  88587. _this._laserPointer.rotation.x = Math.PI / 2;
  88588. _this._laserPointer.position.z = -0.5;
  88589. _this._laserPointer.isVisible = false;
  88590. if (!webVRController.mesh) {
  88591. // Create an empty mesh that is used prior to loading the high quality model
  88592. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88593. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88594. preloadPointerPose.rotation.x = -0.7;
  88595. preloadMesh.addChild(preloadPointerPose);
  88596. webVRController.attachToMesh(preloadMesh);
  88597. }
  88598. _this._setLaserPointerParent(webVRController.mesh);
  88599. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88600. _this._setLaserPointerParent(mesh);
  88601. });
  88602. return _this;
  88603. }
  88604. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88605. return this.webVRController.getForwardRay(length);
  88606. };
  88607. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88608. _super.prototype._activatePointer.call(this);
  88609. this._laserPointer.isVisible = true;
  88610. };
  88611. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88612. _super.prototype._deactivatePointer.call(this);
  88613. this._laserPointer.isVisible = false;
  88614. };
  88615. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88616. this._laserPointer.material.emissiveColor = color;
  88617. };
  88618. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88619. var makeNotPick = function (root) {
  88620. root.name += " laserPointer";
  88621. root.getChildMeshes().forEach(function (c) {
  88622. makeNotPick(c);
  88623. });
  88624. };
  88625. makeNotPick(mesh);
  88626. var childMeshes = mesh.getChildMeshes();
  88627. this.webVRController._pointingPoseNode = null;
  88628. for (var i = 0; i < childMeshes.length; i++) {
  88629. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88630. mesh = childMeshes[i];
  88631. this.webVRController._pointingPoseNode = mesh;
  88632. break;
  88633. }
  88634. }
  88635. this._laserPointer.parent = mesh;
  88636. };
  88637. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88638. if (distance === void 0) { distance = 100; }
  88639. this._laserPointer.scaling.y = distance;
  88640. this._laserPointer.position.z = -distance / 2;
  88641. };
  88642. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88643. _super.prototype.dispose.call(this);
  88644. this._laserPointer.dispose();
  88645. if (this._meshAttachedObserver) {
  88646. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88647. }
  88648. };
  88649. return VRExperienceHelperControllerGazer;
  88650. }(VRExperienceHelperGazer));
  88651. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88652. __extends(VRExperienceHelperCameraGazer, _super);
  88653. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88654. var _this = _super.call(this, scene) || this;
  88655. _this.getCamera = getCamera;
  88656. return _this;
  88657. }
  88658. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88659. var camera = this.getCamera();
  88660. if (camera) {
  88661. return camera.getForwardRay(length);
  88662. }
  88663. else {
  88664. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88665. }
  88666. };
  88667. return VRExperienceHelperCameraGazer;
  88668. }(VRExperienceHelperGazer));
  88669. /**
  88670. * Helps to quickly add VR support to an existing scene.
  88671. * See http://doc.babylonjs.com/how_to/webvr_helper
  88672. */
  88673. var VRExperienceHelper = /** @class */ (function () {
  88674. /**
  88675. * Instantiates a VRExperienceHelper.
  88676. * Helps to quickly add VR support to an existing scene.
  88677. * @param scene The scene the VRExperienceHelper belongs to.
  88678. * @param webVROptions Options to modify the vr experience helper's behavior.
  88679. */
  88680. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88681. if (webVROptions === void 0) { webVROptions = {}; }
  88682. var _this = this;
  88683. this.webVROptions = webVROptions;
  88684. // Can the system support WebVR, even if a headset isn't plugged in?
  88685. this._webVRsupported = false;
  88686. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88687. this._webVRready = false;
  88688. // Are we waiting for the requestPresent callback to complete?
  88689. this._webVRrequesting = false;
  88690. // Are we presenting to the headset right now?
  88691. this._webVRpresenting = false;
  88692. // Are we presenting in the fullscreen fallback?
  88693. this._fullscreenVRpresenting = false;
  88694. /**
  88695. * Observable raised when entering VR.
  88696. */
  88697. this.onEnteringVRObservable = new BABYLON.Observable();
  88698. /**
  88699. * Observable raised when exiting VR.
  88700. */
  88701. this.onExitingVRObservable = new BABYLON.Observable();
  88702. /**
  88703. * Observable raised when controller mesh is loaded.
  88704. */
  88705. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88706. this._useCustomVRButton = false;
  88707. this._teleportationRequested = false;
  88708. this._teleportActive = false;
  88709. this._floorMeshesCollection = [];
  88710. this._rotationAllowed = true;
  88711. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88712. this._isDefaultTeleportationTarget = true;
  88713. this._teleportationFillColor = "#444444";
  88714. this._teleportationBorderColor = "#FFFFFF";
  88715. this._rotationAngle = 0;
  88716. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88717. this._padSensibilityUp = 0.65;
  88718. this._padSensibilityDown = 0.35;
  88719. this.leftController = null;
  88720. this.rightController = null;
  88721. /**
  88722. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88723. */
  88724. this.onNewMeshSelected = new BABYLON.Observable();
  88725. /**
  88726. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88727. */
  88728. this.onNewMeshPicked = new BABYLON.Observable();
  88729. /**
  88730. * Observable raised before camera teleportation
  88731. */
  88732. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88733. /**
  88734. * Observable raised after camera teleportation
  88735. */
  88736. this.onAfterCameraTeleport = new BABYLON.Observable();
  88737. /**
  88738. * Observable raised when current selected mesh gets unselected
  88739. */
  88740. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88741. /**
  88742. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88743. */
  88744. this.teleportationEnabled = true;
  88745. this._teleportationInitialized = false;
  88746. this._interactionsEnabled = false;
  88747. this._interactionsRequested = false;
  88748. this._displayGaze = true;
  88749. this._displayLaserPointer = true;
  88750. this._onResize = function () {
  88751. _this.moveButtonToBottomRight();
  88752. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88753. _this.exitVR();
  88754. }
  88755. };
  88756. this._onFullscreenChange = function () {
  88757. if (document.fullscreen !== undefined) {
  88758. _this._fullscreenVRpresenting = document.fullscreen;
  88759. }
  88760. else if (document.mozFullScreen !== undefined) {
  88761. _this._fullscreenVRpresenting = document.mozFullScreen;
  88762. }
  88763. else if (document.webkitIsFullScreen !== undefined) {
  88764. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88765. }
  88766. else if (document.msIsFullScreen !== undefined) {
  88767. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88768. }
  88769. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88770. _this.exitVR();
  88771. if (!_this._useCustomVRButton) {
  88772. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88773. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88774. }
  88775. }
  88776. };
  88777. this.beforeRender = function () {
  88778. if (_this.leftController && _this.leftController._activePointer) {
  88779. _this._castRayAndSelectObject(_this.leftController);
  88780. }
  88781. if (_this.rightController && _this.rightController._activePointer) {
  88782. _this._castRayAndSelectObject(_this.rightController);
  88783. }
  88784. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88785. _this._castRayAndSelectObject(_this._cameraGazer);
  88786. }
  88787. else {
  88788. _this._cameraGazer._gazeTracker.isVisible = false;
  88789. }
  88790. };
  88791. this._onNewGamepadConnected = function (gamepad) {
  88792. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88793. if (gamepad.leftStick) {
  88794. gamepad.onleftstickchanged(function (stickValues) {
  88795. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88796. // Listening to classic/xbox gamepad only if no VR controller is active
  88797. if ((!_this.leftController && !_this.rightController) ||
  88798. ((_this.leftController && !_this.leftController._activePointer) &&
  88799. (_this.rightController && !_this.rightController._activePointer))) {
  88800. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88801. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88802. }
  88803. }
  88804. });
  88805. }
  88806. if (gamepad.rightStick) {
  88807. gamepad.onrightstickchanged(function (stickValues) {
  88808. if (_this._teleportationInitialized) {
  88809. _this._checkRotate(stickValues, _this._cameraGazer);
  88810. }
  88811. });
  88812. }
  88813. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88814. gamepad.onbuttondown(function (buttonPressed) {
  88815. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88816. _this._cameraGazer._selectionPointerDown();
  88817. }
  88818. });
  88819. gamepad.onbuttonup(function (buttonPressed) {
  88820. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88821. _this._cameraGazer._selectionPointerUp();
  88822. }
  88823. });
  88824. }
  88825. }
  88826. else {
  88827. var webVRController = gamepad;
  88828. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88829. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88830. _this.rightController = controller;
  88831. }
  88832. else {
  88833. _this.leftController = controller;
  88834. }
  88835. _this._tryEnableInteractionOnController(controller);
  88836. }
  88837. };
  88838. // 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
  88839. this._tryEnableInteractionOnController = function (controller) {
  88840. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88841. _this._enableInteractionOnController(controller);
  88842. }
  88843. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88844. _this._enableTeleportationOnController(controller);
  88845. }
  88846. };
  88847. this._onNewGamepadDisconnected = function (gamepad) {
  88848. if (gamepad instanceof BABYLON.WebVRController) {
  88849. if (gamepad.hand === "left" && _this.leftController != null) {
  88850. _this.leftController.dispose();
  88851. _this.leftController = null;
  88852. }
  88853. if (gamepad.hand === "right" && _this.rightController != null) {
  88854. _this.rightController.dispose();
  88855. _this.rightController = null;
  88856. }
  88857. }
  88858. };
  88859. this._workingVector = BABYLON.Vector3.Zero();
  88860. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88861. this._workingMatrix = BABYLON.Matrix.Identity();
  88862. this._scene = scene;
  88863. this._canvas = scene.getEngine().getRenderingCanvas();
  88864. // Parse options
  88865. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88866. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88867. }
  88868. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88869. webVROptions.createDeviceOrientationCamera = true;
  88870. }
  88871. if (webVROptions.laserToggle === undefined) {
  88872. webVROptions.laserToggle = true;
  88873. }
  88874. if (webVROptions.defaultHeight === undefined) {
  88875. webVROptions.defaultHeight = 1.7;
  88876. }
  88877. if (webVROptions.useCustomVRButton) {
  88878. this._useCustomVRButton = true;
  88879. if (webVROptions.customVRButton) {
  88880. this._btnVR = webVROptions.customVRButton;
  88881. }
  88882. }
  88883. if (webVROptions.rayLength) {
  88884. this._rayLength = webVROptions.rayLength;
  88885. }
  88886. this._defaultHeight = webVROptions.defaultHeight;
  88887. if (webVROptions.positionScale) {
  88888. this._rayLength *= webVROptions.positionScale;
  88889. this._defaultHeight *= webVROptions.positionScale;
  88890. }
  88891. // Set position
  88892. if (this._scene.activeCamera) {
  88893. this._position = this._scene.activeCamera.position.clone();
  88894. }
  88895. else {
  88896. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88897. }
  88898. // Set non-vr camera
  88899. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88900. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88901. // Copy data from existing camera
  88902. if (this._scene.activeCamera) {
  88903. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88904. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88905. // Set rotation from previous camera
  88906. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88907. var targetCamera = this._scene.activeCamera;
  88908. if (targetCamera.rotationQuaternion) {
  88909. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88910. }
  88911. else {
  88912. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88913. }
  88914. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88915. }
  88916. }
  88917. this._scene.activeCamera = this._deviceOrientationCamera;
  88918. if (this._canvas) {
  88919. this._scene.activeCamera.attachControl(this._canvas);
  88920. }
  88921. }
  88922. else {
  88923. this._existingCamera = this._scene.activeCamera;
  88924. }
  88925. // Create VR cameras
  88926. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88927. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88928. }
  88929. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88930. this._webVRCamera.useStandingMatrix();
  88931. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88932. // Create default button
  88933. if (!this._useCustomVRButton) {
  88934. this._btnVR = document.createElement("BUTTON");
  88935. this._btnVR.className = "babylonVRicon";
  88936. this._btnVR.id = "babylonVRiconbtn";
  88937. this._btnVR.title = "Click to switch to VR";
  88938. 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) }";
  88939. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88940. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88941. // css += ".babylonVRicon.vrdisplaysupported { }";
  88942. // css += ".babylonVRicon.vrdisplayready { }";
  88943. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88944. var style = document.createElement('style');
  88945. style.appendChild(document.createTextNode(css));
  88946. document.getElementsByTagName('head')[0].appendChild(style);
  88947. this.moveButtonToBottomRight();
  88948. }
  88949. // VR button click event
  88950. if (this._btnVR) {
  88951. this._btnVR.addEventListener("click", function () {
  88952. if (!_this.isInVRMode) {
  88953. _this.enterVR();
  88954. }
  88955. else {
  88956. _this.exitVR();
  88957. }
  88958. });
  88959. }
  88960. // Window events
  88961. window.addEventListener("resize", this._onResize);
  88962. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88963. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88964. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88965. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88966. // Display vr button when headset is connected
  88967. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88968. this.displayVRButton();
  88969. }
  88970. else {
  88971. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88972. if (e.vrDisplay) {
  88973. _this.displayVRButton();
  88974. }
  88975. });
  88976. }
  88977. // Exiting VR mode using 'ESC' key on desktop
  88978. this._onKeyDown = function (event) {
  88979. if (event.keyCode === 27 && _this.isInVRMode) {
  88980. _this.exitVR();
  88981. }
  88982. };
  88983. document.addEventListener("keydown", this._onKeyDown);
  88984. // Exiting VR mode double tapping the touch screen
  88985. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88986. if (_this.isInVRMode) {
  88987. _this.exitVR();
  88988. if (_this._fullscreenVRpresenting) {
  88989. _this._scene.getEngine().switchFullscreen(true);
  88990. }
  88991. }
  88992. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88993. // Listen for WebVR display changes
  88994. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88995. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88996. this._onVRRequestPresentStart = function () {
  88997. _this._webVRrequesting = true;
  88998. _this.updateButtonVisibility();
  88999. };
  89000. this._onVRRequestPresentComplete = function (success) {
  89001. _this._webVRrequesting = false;
  89002. _this.updateButtonVisibility();
  89003. };
  89004. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  89005. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  89006. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  89007. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89008. scene.onDisposeObservable.add(function () {
  89009. _this.dispose();
  89010. });
  89011. // Gamepad connection events
  89012. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  89013. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  89014. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  89015. this.updateButtonVisibility();
  89016. //create easing functions
  89017. this._circleEase = new BABYLON.CircleEase();
  89018. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89019. if (this.webVROptions.floorMeshes) {
  89020. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  89021. }
  89022. }
  89023. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  89024. /** Return this.onEnteringVRObservable
  89025. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  89026. */
  89027. get: function () {
  89028. return this.onEnteringVRObservable;
  89029. },
  89030. enumerable: true,
  89031. configurable: true
  89032. });
  89033. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  89034. /** Return this.onExitingVRObservable
  89035. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  89036. */
  89037. get: function () {
  89038. return this.onExitingVRObservable;
  89039. },
  89040. enumerable: true,
  89041. configurable: true
  89042. });
  89043. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  89044. /** Return this.onControllerMeshLoadedObservable
  89045. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  89046. */
  89047. get: function () {
  89048. return this.onControllerMeshLoadedObservable;
  89049. },
  89050. enumerable: true,
  89051. configurable: true
  89052. });
  89053. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  89054. /**
  89055. * The mesh used to display where the user is going to teleport.
  89056. */
  89057. get: function () {
  89058. return this._teleportationTarget;
  89059. },
  89060. /**
  89061. * Sets the mesh to be used to display where the user is going to teleport.
  89062. */
  89063. set: function (value) {
  89064. if (value) {
  89065. value.name = "teleportationTarget";
  89066. this._isDefaultTeleportationTarget = false;
  89067. this._teleportationTarget = value;
  89068. }
  89069. },
  89070. enumerable: true,
  89071. configurable: true
  89072. });
  89073. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  89074. /**
  89075. * The mesh used to display where the user is selecting,
  89076. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  89077. * See http://doc.babylonjs.com/resources/baking_transformations
  89078. */
  89079. get: function () {
  89080. return this._cameraGazer._gazeTracker;
  89081. },
  89082. set: function (value) {
  89083. if (value) {
  89084. this._cameraGazer._gazeTracker = value;
  89085. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  89086. this._cameraGazer._gazeTracker.isPickable = false;
  89087. this._cameraGazer._gazeTracker.isVisible = false;
  89088. this._cameraGazer._gazeTracker.name = "gazeTracker";
  89089. if (this.leftController) {
  89090. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  89091. }
  89092. if (this.rightController) {
  89093. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  89094. }
  89095. }
  89096. },
  89097. enumerable: true,
  89098. configurable: true
  89099. });
  89100. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  89101. /**
  89102. * If the ray of the gaze should be displayed.
  89103. */
  89104. get: function () {
  89105. return this._displayGaze;
  89106. },
  89107. /**
  89108. * Sets if the ray of the gaze should be displayed.
  89109. */
  89110. set: function (value) {
  89111. this._displayGaze = value;
  89112. if (!value) {
  89113. this._cameraGazer._gazeTracker.isVisible = false;
  89114. if (this.leftController) {
  89115. this.leftController._gazeTracker.isVisible = false;
  89116. }
  89117. if (this.rightController) {
  89118. this.rightController._gazeTracker.isVisible = false;
  89119. }
  89120. }
  89121. },
  89122. enumerable: true,
  89123. configurable: true
  89124. });
  89125. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  89126. /**
  89127. * If the ray of the LaserPointer should be displayed.
  89128. */
  89129. get: function () {
  89130. return this._displayLaserPointer;
  89131. },
  89132. /**
  89133. * Sets if the ray of the LaserPointer should be displayed.
  89134. */
  89135. set: function (value) {
  89136. this._displayLaserPointer = value;
  89137. if (!value) {
  89138. if (this.rightController) {
  89139. this.rightController._deactivatePointer();
  89140. this.rightController._gazeTracker.isVisible = false;
  89141. }
  89142. if (this.leftController) {
  89143. this.leftController._deactivatePointer();
  89144. this.leftController._gazeTracker.isVisible = false;
  89145. }
  89146. }
  89147. else {
  89148. if (this.rightController) {
  89149. this.rightController._activatePointer();
  89150. }
  89151. if (this.leftController) {
  89152. this.leftController._activatePointer();
  89153. }
  89154. }
  89155. },
  89156. enumerable: true,
  89157. configurable: true
  89158. });
  89159. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  89160. /**
  89161. * The deviceOrientationCamera used as the camera when not in VR.
  89162. */
  89163. get: function () {
  89164. return this._deviceOrientationCamera;
  89165. },
  89166. enumerable: true,
  89167. configurable: true
  89168. });
  89169. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  89170. /**
  89171. * Based on the current WebVR support, returns the current VR camera used.
  89172. */
  89173. get: function () {
  89174. if (this._webVRready) {
  89175. return this._webVRCamera;
  89176. }
  89177. else {
  89178. return this._scene.activeCamera;
  89179. }
  89180. },
  89181. enumerable: true,
  89182. configurable: true
  89183. });
  89184. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  89185. /**
  89186. * The webVRCamera which is used when in VR.
  89187. */
  89188. get: function () {
  89189. return this._webVRCamera;
  89190. },
  89191. enumerable: true,
  89192. configurable: true
  89193. });
  89194. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  89195. /**
  89196. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  89197. */
  89198. get: function () {
  89199. return this._vrDeviceOrientationCamera;
  89200. },
  89201. enumerable: true,
  89202. configurable: true
  89203. });
  89204. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  89205. get: function () {
  89206. var result = this._cameraGazer._teleportationRequestInitiated
  89207. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  89208. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  89209. return result;
  89210. },
  89211. enumerable: true,
  89212. configurable: true
  89213. });
  89214. // Raised when one of the controller has loaded successfully its associated default mesh
  89215. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  89216. if (this.leftController && this.leftController.webVRController == webVRController) {
  89217. if (webVRController.mesh) {
  89218. this.leftController._setLaserPointerParent(webVRController.mesh);
  89219. }
  89220. }
  89221. if (this.rightController && this.rightController.webVRController == webVRController) {
  89222. if (webVRController.mesh) {
  89223. this.rightController._setLaserPointerParent(webVRController.mesh);
  89224. }
  89225. }
  89226. try {
  89227. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  89228. }
  89229. catch (err) {
  89230. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  89231. }
  89232. };
  89233. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  89234. /**
  89235. * Gets a value indicating if we are currently in VR mode.
  89236. */
  89237. get: function () {
  89238. return this._webVRpresenting || this._fullscreenVRpresenting;
  89239. },
  89240. enumerable: true,
  89241. configurable: true
  89242. });
  89243. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  89244. var vrDisplay = this._scene.getEngine().getVRDevice();
  89245. if (vrDisplay) {
  89246. var wasPresenting = this._webVRpresenting;
  89247. // A VR display is connected
  89248. this._webVRpresenting = vrDisplay.isPresenting;
  89249. if (wasPresenting && !this._webVRpresenting)
  89250. this.exitVR();
  89251. }
  89252. else {
  89253. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  89254. }
  89255. this.updateButtonVisibility();
  89256. };
  89257. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  89258. this._webVRsupported = eventArgs.vrSupported;
  89259. this._webVRready = !!eventArgs.vrDisplay;
  89260. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  89261. this.updateButtonVisibility();
  89262. };
  89263. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  89264. if (this._canvas && !this._useCustomVRButton) {
  89265. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  89266. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  89267. }
  89268. };
  89269. VRExperienceHelper.prototype.displayVRButton = function () {
  89270. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  89271. document.body.appendChild(this._btnVR);
  89272. this._btnVRDisplayed = true;
  89273. }
  89274. };
  89275. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  89276. if (!this._btnVR || this._useCustomVRButton) {
  89277. return;
  89278. }
  89279. this._btnVR.className = "babylonVRicon";
  89280. if (this.isInVRMode) {
  89281. this._btnVR.className += " vrdisplaypresenting";
  89282. }
  89283. else {
  89284. if (this._webVRready)
  89285. this._btnVR.className += " vrdisplayready";
  89286. if (this._webVRsupported)
  89287. this._btnVR.className += " vrdisplaysupported";
  89288. if (this._webVRrequesting)
  89289. this._btnVR.className += " vrdisplayrequesting";
  89290. }
  89291. };
  89292. /**
  89293. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  89294. * Otherwise, will use the fullscreen API.
  89295. */
  89296. VRExperienceHelper.prototype.enterVR = function () {
  89297. if (this.onEnteringVRObservable) {
  89298. try {
  89299. this.onEnteringVRObservable.notifyObservers(this);
  89300. }
  89301. catch (err) {
  89302. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  89303. }
  89304. }
  89305. if (this._scene.activeCamera) {
  89306. this._position = this._scene.activeCamera.position.clone();
  89307. // make sure that we return to the last active camera
  89308. this._existingCamera = this._scene.activeCamera;
  89309. }
  89310. if (this._webVRrequesting)
  89311. return;
  89312. // If WebVR is supported and a headset is connected
  89313. if (this._webVRready) {
  89314. if (!this._webVRpresenting) {
  89315. this._webVRCamera.position = this._position;
  89316. this._scene.activeCamera = this._webVRCamera;
  89317. }
  89318. }
  89319. else if (this._vrDeviceOrientationCamera) {
  89320. this._vrDeviceOrientationCamera.position = this._position;
  89321. if (this._scene.activeCamera) {
  89322. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89323. }
  89324. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  89325. this._scene.getEngine().switchFullscreen(true);
  89326. this.updateButtonVisibility();
  89327. }
  89328. if (this._scene.activeCamera && this._canvas) {
  89329. this._scene.activeCamera.attachControl(this._canvas);
  89330. }
  89331. if (this._interactionsEnabled) {
  89332. this._scene.registerBeforeRender(this.beforeRender);
  89333. }
  89334. };
  89335. /**
  89336. * Attempt to exit VR, or fullscreen.
  89337. */
  89338. VRExperienceHelper.prototype.exitVR = function () {
  89339. if (this.onExitingVRObservable) {
  89340. try {
  89341. this.onExitingVRObservable.notifyObservers(this);
  89342. }
  89343. catch (err) {
  89344. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  89345. }
  89346. }
  89347. if (this._webVRpresenting) {
  89348. this._scene.getEngine().disableVR();
  89349. }
  89350. if (this._scene.activeCamera) {
  89351. this._position = this._scene.activeCamera.position.clone();
  89352. }
  89353. if (this._deviceOrientationCamera) {
  89354. this._deviceOrientationCamera.position = this._position;
  89355. this._scene.activeCamera = this._deviceOrientationCamera;
  89356. if (this._canvas) {
  89357. this._scene.activeCamera.attachControl(this._canvas);
  89358. }
  89359. }
  89360. else if (this._existingCamera) {
  89361. this._existingCamera.position = this._position;
  89362. this._scene.activeCamera = this._existingCamera;
  89363. }
  89364. this.updateButtonVisibility();
  89365. if (this._interactionsEnabled) {
  89366. this._scene.unregisterBeforeRender(this.beforeRender);
  89367. }
  89368. // resize to update width and height when exiting vr exits fullscreen
  89369. this._scene.getEngine().resize();
  89370. };
  89371. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89372. /**
  89373. * The position of the vr experience helper.
  89374. */
  89375. get: function () {
  89376. return this._position;
  89377. },
  89378. /**
  89379. * Sets the position of the vr experience helper.
  89380. */
  89381. set: function (value) {
  89382. this._position = value;
  89383. if (this._scene.activeCamera) {
  89384. this._scene.activeCamera.position = value;
  89385. }
  89386. },
  89387. enumerable: true,
  89388. configurable: true
  89389. });
  89390. /**
  89391. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89392. */
  89393. VRExperienceHelper.prototype.enableInteractions = function () {
  89394. var _this = this;
  89395. if (!this._interactionsEnabled) {
  89396. this._interactionsRequested = true;
  89397. if (this.leftController) {
  89398. this._enableInteractionOnController(this.leftController);
  89399. }
  89400. if (this.rightController) {
  89401. this._enableInteractionOnController(this.rightController);
  89402. }
  89403. this.raySelectionPredicate = function (mesh) {
  89404. return mesh.isVisible;
  89405. };
  89406. this.meshSelectionPredicate = function (mesh) {
  89407. return true;
  89408. };
  89409. this._raySelectionPredicate = function (mesh) {
  89410. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89411. && mesh.name.indexOf("teleportationTarget") === -1
  89412. && mesh.name.indexOf("torusTeleportation") === -1
  89413. && mesh.name.indexOf("laserPointer") === -1)) {
  89414. return _this.raySelectionPredicate(mesh);
  89415. }
  89416. return false;
  89417. };
  89418. this._interactionsEnabled = true;
  89419. }
  89420. };
  89421. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89422. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89423. if (this._floorMeshesCollection[i].id === mesh.id) {
  89424. return true;
  89425. }
  89426. }
  89427. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89428. return true;
  89429. }
  89430. return false;
  89431. };
  89432. /**
  89433. * Adds a floor mesh to be used for teleportation.
  89434. * @param floorMesh the mesh to be used for teleportation.
  89435. */
  89436. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89437. if (!this._floorMeshesCollection) {
  89438. return;
  89439. }
  89440. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89441. return;
  89442. }
  89443. this._floorMeshesCollection.push(floorMesh);
  89444. };
  89445. /**
  89446. * Removes a floor mesh from being used for teleportation.
  89447. * @param floorMesh the mesh to be removed.
  89448. */
  89449. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89450. if (!this._floorMeshesCollection) {
  89451. return;
  89452. }
  89453. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89454. if (meshIndex !== -1) {
  89455. this._floorMeshesCollection.splice(meshIndex, 1);
  89456. }
  89457. };
  89458. /**
  89459. * Enables interactions and teleportation using the VR controllers and gaze.
  89460. * @param vrTeleportationOptions options to modify teleportation behavior.
  89461. */
  89462. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89463. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89464. if (!this._teleportationInitialized) {
  89465. this._teleportationRequested = true;
  89466. this.enableInteractions();
  89467. if (vrTeleportationOptions.floorMeshName) {
  89468. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89469. }
  89470. if (vrTeleportationOptions.floorMeshes) {
  89471. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89472. }
  89473. if (this.leftController != null) {
  89474. this._enableTeleportationOnController(this.leftController);
  89475. }
  89476. if (this.rightController != null) {
  89477. this._enableTeleportationOnController(this.rightController);
  89478. }
  89479. // Creates an image processing post process for the vignette not relying
  89480. // on the main scene configuration for image processing to reduce setup and spaces
  89481. // (gamma/linear) conflicts.
  89482. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89483. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89484. imageProcessingConfiguration.vignetteEnabled = true;
  89485. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89486. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89487. this._teleportationInitialized = true;
  89488. if (this._isDefaultTeleportationTarget) {
  89489. this._createTeleportationCircles();
  89490. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89491. }
  89492. }
  89493. };
  89494. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89495. var _this = this;
  89496. var controllerMesh = controller.webVRController.mesh;
  89497. if (controllerMesh) {
  89498. controller._interactionsEnabled = true;
  89499. controller._activatePointer();
  89500. if (this.webVROptions.laserToggle) {
  89501. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89502. // Enabling / disabling laserPointer
  89503. if (_this._displayLaserPointer && stateObject.value === 1) {
  89504. if (controller._activePointer) {
  89505. controller._deactivatePointer();
  89506. }
  89507. else {
  89508. controller._activatePointer();
  89509. }
  89510. if (_this.displayGaze) {
  89511. controller._gazeTracker.isVisible = controller._activePointer;
  89512. }
  89513. }
  89514. });
  89515. }
  89516. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89517. if (!controller._pointerDownOnMeshAsked) {
  89518. if (stateObject.value > _this._padSensibilityUp) {
  89519. controller._selectionPointerDown();
  89520. }
  89521. }
  89522. else if (stateObject.value < _this._padSensibilityDown) {
  89523. controller._selectionPointerUp();
  89524. }
  89525. });
  89526. }
  89527. };
  89528. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89529. // Dont teleport if another gaze already requested teleportation
  89530. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89531. return;
  89532. }
  89533. if (!gazer._teleportationRequestInitiated) {
  89534. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89535. gazer._activatePointer();
  89536. gazer._teleportationRequestInitiated = true;
  89537. }
  89538. }
  89539. else {
  89540. // Listening to the proper controller values changes to confirm teleportation
  89541. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89542. if (this._teleportActive) {
  89543. this._teleportCamera(this._haloCenter);
  89544. }
  89545. gazer._teleportationRequestInitiated = false;
  89546. }
  89547. }
  89548. };
  89549. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89550. // Only rotate when user is not currently selecting a teleportation location
  89551. if (gazer._teleportationRequestInitiated) {
  89552. return;
  89553. }
  89554. if (!gazer._rotationLeftAsked) {
  89555. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89556. gazer._rotationLeftAsked = true;
  89557. if (this._rotationAllowed) {
  89558. this._rotateCamera(false);
  89559. }
  89560. }
  89561. }
  89562. else {
  89563. if (stateObject.x > -this._padSensibilityDown) {
  89564. gazer._rotationLeftAsked = false;
  89565. }
  89566. }
  89567. if (!gazer._rotationRightAsked) {
  89568. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89569. gazer._rotationRightAsked = true;
  89570. if (this._rotationAllowed) {
  89571. this._rotateCamera(true);
  89572. }
  89573. }
  89574. }
  89575. else {
  89576. if (stateObject.x < this._padSensibilityDown) {
  89577. gazer._rotationRightAsked = false;
  89578. }
  89579. }
  89580. };
  89581. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89582. // Only teleport backwards when user is not currently selecting a teleportation location
  89583. if (gazer._teleportationRequestInitiated) {
  89584. return;
  89585. }
  89586. // Teleport backwards
  89587. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89588. if (!gazer._teleportationBackRequestInitiated) {
  89589. if (!this.currentVRCamera) {
  89590. return;
  89591. }
  89592. // Get rotation and position of the current camera
  89593. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89594. var position = this.currentVRCamera.position;
  89595. // If the camera has device position, use that instead
  89596. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89597. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89598. position = this.currentVRCamera.devicePosition;
  89599. }
  89600. // Get matrix with only the y rotation of the device rotation
  89601. rotation.toEulerAnglesToRef(this._workingVector);
  89602. this._workingVector.z = 0;
  89603. this._workingVector.x = 0;
  89604. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89605. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89606. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89607. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89608. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89609. var ray = new BABYLON.Ray(position, this._workingVector);
  89610. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89611. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89612. this._teleportCamera(hit.pickedPoint);
  89613. }
  89614. gazer._teleportationBackRequestInitiated = true;
  89615. }
  89616. }
  89617. else {
  89618. gazer._teleportationBackRequestInitiated = false;
  89619. }
  89620. };
  89621. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89622. var _this = this;
  89623. var controllerMesh = controller.webVRController.mesh;
  89624. if (controllerMesh) {
  89625. if (!controller._interactionsEnabled) {
  89626. this._enableInteractionOnController(controller);
  89627. }
  89628. controller._interactionsEnabled = true;
  89629. controller._teleportationEnabled = true;
  89630. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89631. controller._dpadPressed = false;
  89632. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89633. controller._dpadPressed = stateObject.pressed;
  89634. if (!controller._dpadPressed) {
  89635. controller._rotationLeftAsked = false;
  89636. controller._rotationRightAsked = false;
  89637. controller._teleportationBackRequestInitiated = false;
  89638. }
  89639. });
  89640. }
  89641. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89642. if (_this.teleportationEnabled) {
  89643. _this._checkTeleportBackwards(stateObject, controller);
  89644. _this._checkTeleportWithRay(stateObject, controller);
  89645. }
  89646. _this._checkRotate(stateObject, controller);
  89647. });
  89648. }
  89649. };
  89650. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89651. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89652. this._teleportationTarget.isPickable = false;
  89653. var length = 512;
  89654. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89655. dynamicTexture.hasAlpha = true;
  89656. var context = dynamicTexture.getContext();
  89657. var centerX = length / 2;
  89658. var centerY = length / 2;
  89659. var radius = 200;
  89660. context.beginPath();
  89661. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89662. context.fillStyle = this._teleportationFillColor;
  89663. context.fill();
  89664. context.lineWidth = 10;
  89665. context.strokeStyle = this._teleportationBorderColor;
  89666. context.stroke();
  89667. context.closePath();
  89668. dynamicTexture.update();
  89669. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89670. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89671. this._teleportationTarget.material = teleportationCircleMaterial;
  89672. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89673. torus.isPickable = false;
  89674. torus.parent = this._teleportationTarget;
  89675. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89676. var keys = [];
  89677. keys.push({
  89678. frame: 0,
  89679. value: 0
  89680. });
  89681. keys.push({
  89682. frame: 30,
  89683. value: 0.4
  89684. });
  89685. keys.push({
  89686. frame: 60,
  89687. value: 0
  89688. });
  89689. animationInnerCircle.setKeys(keys);
  89690. var easingFunction = new BABYLON.SineEase();
  89691. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89692. animationInnerCircle.setEasingFunction(easingFunction);
  89693. torus.animations = [];
  89694. torus.animations.push(animationInnerCircle);
  89695. this._scene.beginAnimation(torus, 0, 60, true);
  89696. this._hideTeleportationTarget();
  89697. };
  89698. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89699. this._teleportActive = true;
  89700. if (this._teleportationInitialized) {
  89701. this._teleportationTarget.isVisible = true;
  89702. if (this._isDefaultTeleportationTarget) {
  89703. this._teleportationTarget.getChildren()[0].isVisible = true;
  89704. }
  89705. }
  89706. };
  89707. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89708. this._teleportActive = false;
  89709. if (this._teleportationInitialized) {
  89710. this._teleportationTarget.isVisible = false;
  89711. if (this._isDefaultTeleportationTarget) {
  89712. this._teleportationTarget.getChildren()[0].isVisible = false;
  89713. }
  89714. }
  89715. };
  89716. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89717. var _this = this;
  89718. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89719. return;
  89720. }
  89721. if (right) {
  89722. this._rotationAngle++;
  89723. }
  89724. else {
  89725. this._rotationAngle--;
  89726. }
  89727. this.currentVRCamera.animations = [];
  89728. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89729. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89730. var animationRotationKeys = [];
  89731. animationRotationKeys.push({
  89732. frame: 0,
  89733. value: this.currentVRCamera.rotationQuaternion
  89734. });
  89735. animationRotationKeys.push({
  89736. frame: 6,
  89737. value: target
  89738. });
  89739. animationRotation.setKeys(animationRotationKeys);
  89740. animationRotation.setEasingFunction(this._circleEase);
  89741. this.currentVRCamera.animations.push(animationRotation);
  89742. this._postProcessMove.animations = [];
  89743. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89744. var vignetteWeightKeys = [];
  89745. vignetteWeightKeys.push({
  89746. frame: 0,
  89747. value: 0
  89748. });
  89749. vignetteWeightKeys.push({
  89750. frame: 3,
  89751. value: 4
  89752. });
  89753. vignetteWeightKeys.push({
  89754. frame: 6,
  89755. value: 0
  89756. });
  89757. animationPP.setKeys(vignetteWeightKeys);
  89758. animationPP.setEasingFunction(this._circleEase);
  89759. this._postProcessMove.animations.push(animationPP);
  89760. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89761. var vignetteStretchKeys = [];
  89762. vignetteStretchKeys.push({
  89763. frame: 0,
  89764. value: 0
  89765. });
  89766. vignetteStretchKeys.push({
  89767. frame: 3,
  89768. value: 10
  89769. });
  89770. vignetteStretchKeys.push({
  89771. frame: 6,
  89772. value: 0
  89773. });
  89774. animationPP2.setKeys(vignetteStretchKeys);
  89775. animationPP2.setEasingFunction(this._circleEase);
  89776. this._postProcessMove.animations.push(animationPP2);
  89777. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89778. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89779. this._postProcessMove.samples = 4;
  89780. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89781. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89782. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89783. });
  89784. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89785. };
  89786. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89787. if (hit.pickedPoint) {
  89788. if (gazer._teleportationRequestInitiated) {
  89789. this._displayTeleportationTarget();
  89790. this._haloCenter.copyFrom(hit.pickedPoint);
  89791. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89792. }
  89793. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89794. if (pickNormal) {
  89795. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89796. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89797. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89798. }
  89799. this._teleportationTarget.position.y += 0.1;
  89800. }
  89801. };
  89802. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89803. var _this = this;
  89804. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89805. return;
  89806. }
  89807. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89808. // offset of the headset from the anchor.
  89809. if (this.webVRCamera.leftCamera) {
  89810. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89811. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89812. location.subtractToRef(this._workingVector, this._workingVector);
  89813. }
  89814. else {
  89815. this._workingVector.copyFrom(location);
  89816. }
  89817. // Add height to account for user's height offset
  89818. if (this.isInVRMode) {
  89819. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89820. }
  89821. else {
  89822. this._workingVector.y += this._defaultHeight;
  89823. }
  89824. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89825. // Create animation from the camera's position to the new location
  89826. this.currentVRCamera.animations = [];
  89827. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89828. var animationCameraTeleportationKeys = [{
  89829. frame: 0,
  89830. value: this.currentVRCamera.position
  89831. },
  89832. {
  89833. frame: 11,
  89834. value: this._workingVector
  89835. }
  89836. ];
  89837. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89838. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89839. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89840. this._postProcessMove.animations = [];
  89841. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89842. var vignetteWeightKeys = [];
  89843. vignetteWeightKeys.push({
  89844. frame: 0,
  89845. value: 0
  89846. });
  89847. vignetteWeightKeys.push({
  89848. frame: 5,
  89849. value: 8
  89850. });
  89851. vignetteWeightKeys.push({
  89852. frame: 11,
  89853. value: 0
  89854. });
  89855. animationPP.setKeys(vignetteWeightKeys);
  89856. this._postProcessMove.animations.push(animationPP);
  89857. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89858. var vignetteStretchKeys = [];
  89859. vignetteStretchKeys.push({
  89860. frame: 0,
  89861. value: 0
  89862. });
  89863. vignetteStretchKeys.push({
  89864. frame: 5,
  89865. value: 10
  89866. });
  89867. vignetteStretchKeys.push({
  89868. frame: 11,
  89869. value: 0
  89870. });
  89871. animationPP2.setKeys(vignetteStretchKeys);
  89872. this._postProcessMove.animations.push(animationPP2);
  89873. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89874. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89875. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89876. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89877. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89878. });
  89879. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89880. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89881. });
  89882. this._hideTeleportationTarget();
  89883. };
  89884. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89885. if (normal) {
  89886. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89887. if (angle < Math.PI / 2) {
  89888. normal.scaleInPlace(-1);
  89889. }
  89890. }
  89891. return normal;
  89892. };
  89893. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89894. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89895. return;
  89896. }
  89897. var ray = gazer._getForwardRay(this._rayLength);
  89898. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89899. if (hit) {
  89900. // Populate the contrllers mesh that can be used for drag/drop
  89901. if (gazer._laserPointer) {
  89902. hit.originMesh = gazer._laserPointer.parent;
  89903. }
  89904. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89905. }
  89906. gazer._currentHit = hit;
  89907. // Moving the gazeTracker on the mesh face targetted
  89908. if (hit && hit.pickedPoint) {
  89909. if (this._displayGaze) {
  89910. var multiplier = 1;
  89911. gazer._gazeTracker.isVisible = true;
  89912. if (gazer._isActionableMesh) {
  89913. multiplier = 3;
  89914. }
  89915. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89916. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89917. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89918. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89919. // To avoid z-fighting
  89920. var deltaFighting = 0.002;
  89921. if (pickNormal) {
  89922. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89923. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89924. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89925. }
  89926. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89927. if (gazer._gazeTracker.position.x < 0) {
  89928. gazer._gazeTracker.position.x += deltaFighting;
  89929. }
  89930. else {
  89931. gazer._gazeTracker.position.x -= deltaFighting;
  89932. }
  89933. if (gazer._gazeTracker.position.y < 0) {
  89934. gazer._gazeTracker.position.y += deltaFighting;
  89935. }
  89936. else {
  89937. gazer._gazeTracker.position.y -= deltaFighting;
  89938. }
  89939. if (gazer._gazeTracker.position.z < 0) {
  89940. gazer._gazeTracker.position.z += deltaFighting;
  89941. }
  89942. else {
  89943. gazer._gazeTracker.position.z -= deltaFighting;
  89944. }
  89945. }
  89946. // Changing the size of the laser pointer based on the distance from the targetted point
  89947. gazer._updatePointerDistance(hit.distance);
  89948. }
  89949. else {
  89950. gazer._updatePointerDistance();
  89951. gazer._gazeTracker.isVisible = false;
  89952. }
  89953. if (hit && hit.pickedMesh) {
  89954. // The object selected is the floor, we're in a teleportation scenario
  89955. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89956. // Moving the teleportation area to this targetted point
  89957. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89958. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89959. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89960. }
  89961. gazer._currentMeshSelected = null;
  89962. if (gazer._teleportationRequestInitiated) {
  89963. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89964. }
  89965. return;
  89966. }
  89967. // If not, we're in a selection scenario
  89968. //this._teleportationAllowed = false;
  89969. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89970. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89971. this.onNewMeshPicked.notifyObservers(hit);
  89972. gazer._currentMeshSelected = hit.pickedMesh;
  89973. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89974. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89975. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89976. gazer._isActionableMesh = true;
  89977. }
  89978. else {
  89979. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89980. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89981. gazer._isActionableMesh = false;
  89982. }
  89983. try {
  89984. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89985. }
  89986. catch (err) {
  89987. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89988. }
  89989. }
  89990. else {
  89991. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89992. gazer._currentMeshSelected = null;
  89993. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89994. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89995. }
  89996. }
  89997. }
  89998. else {
  89999. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  90000. gazer._currentMeshSelected = null;
  90001. //this._teleportationAllowed = false;
  90002. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90003. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90004. }
  90005. };
  90006. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  90007. if (mesh) {
  90008. this.onSelectedMeshUnselected.notifyObservers(mesh);
  90009. }
  90010. };
  90011. /**
  90012. * Sets the color of the laser ray from the vr controllers.
  90013. * @param color new color for the ray.
  90014. */
  90015. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  90016. if (this.leftController) {
  90017. this.leftController._setLaserPointerColor(color);
  90018. }
  90019. if (this.rightController) {
  90020. this.rightController._setLaserPointerColor(color);
  90021. }
  90022. };
  90023. /**
  90024. * Sets the color of the ray from the vr headsets gaze.
  90025. * @param color new color for the ray.
  90026. */
  90027. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  90028. if (!this._cameraGazer._gazeTracker.material) {
  90029. return;
  90030. }
  90031. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  90032. if (this.leftController) {
  90033. this.leftController._gazeTracker.material.emissiveColor = color;
  90034. }
  90035. if (this.rightController) {
  90036. this.rightController._gazeTracker.material.emissiveColor = color;
  90037. }
  90038. };
  90039. /**
  90040. * Exits VR and disposes of the vr experience helper
  90041. */
  90042. VRExperienceHelper.prototype.dispose = function () {
  90043. if (this.isInVRMode) {
  90044. this.exitVR();
  90045. }
  90046. if (this._postProcessMove) {
  90047. this._postProcessMove.dispose();
  90048. }
  90049. if (this._webVRCamera) {
  90050. this._webVRCamera.dispose();
  90051. }
  90052. if (this._vrDeviceOrientationCamera) {
  90053. this._vrDeviceOrientationCamera.dispose();
  90054. }
  90055. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  90056. document.body.removeChild(this._btnVR);
  90057. }
  90058. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  90059. this._deviceOrientationCamera.dispose();
  90060. }
  90061. if (this._cameraGazer) {
  90062. this._cameraGazer.dispose();
  90063. }
  90064. if (this.leftController) {
  90065. this.leftController.dispose();
  90066. }
  90067. if (this.rightController) {
  90068. this.rightController.dispose();
  90069. }
  90070. if (this._teleportationTarget) {
  90071. this._teleportationTarget.dispose();
  90072. }
  90073. this._floorMeshesCollection = [];
  90074. document.removeEventListener("keydown", this._onKeyDown);
  90075. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90076. window.removeEventListener("resize", this._onResize);
  90077. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  90078. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  90079. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  90080. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  90081. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  90082. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  90083. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  90084. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90085. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  90086. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  90087. this._scene.unregisterBeforeRender(this.beforeRender);
  90088. };
  90089. /**
  90090. * Gets the name of the VRExperienceHelper class
  90091. * @returns "VRExperienceHelper"
  90092. */
  90093. VRExperienceHelper.prototype.getClassName = function () {
  90094. return "VRExperienceHelper";
  90095. };
  90096. return VRExperienceHelper;
  90097. }());
  90098. BABYLON.VRExperienceHelper = VRExperienceHelper;
  90099. })(BABYLON || (BABYLON = {}));
  90100. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  90101. // Mainly based on these 2 articles :
  90102. // 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
  90103. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  90104. var BABYLON;
  90105. (function (BABYLON) {
  90106. /**
  90107. * Defines the potential axis of a Joystick
  90108. */
  90109. var JoystickAxis;
  90110. (function (JoystickAxis) {
  90111. /** X axis */
  90112. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  90113. /** Y axis */
  90114. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  90115. /** Z axis */
  90116. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  90117. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  90118. /**
  90119. * Class used to define virtual joystick (used in touch mode)
  90120. */
  90121. var VirtualJoystick = /** @class */ (function () {
  90122. /**
  90123. * Creates a new virtual joystick
  90124. * @param leftJoystick defines that the joystick is for left hand (false by default)
  90125. */
  90126. function VirtualJoystick(leftJoystick) {
  90127. var _this = this;
  90128. if (leftJoystick) {
  90129. this._leftJoystick = true;
  90130. }
  90131. else {
  90132. this._leftJoystick = false;
  90133. }
  90134. VirtualJoystick._globalJoystickIndex++;
  90135. // By default left & right arrow keys are moving the X
  90136. // and up & down keys are moving the Y
  90137. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90138. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90139. this.reverseLeftRight = false;
  90140. this.reverseUpDown = false;
  90141. // collections of pointers
  90142. this._touches = new BABYLON.StringDictionary();
  90143. this.deltaPosition = BABYLON.Vector3.Zero();
  90144. this._joystickSensibility = 25;
  90145. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  90146. this._onResize = function (evt) {
  90147. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  90148. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  90149. if (VirtualJoystick.vjCanvas) {
  90150. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  90151. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  90152. }
  90153. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  90154. };
  90155. // injecting a canvas element on top of the canvas 3D game
  90156. if (!VirtualJoystick.vjCanvas) {
  90157. window.addEventListener("resize", this._onResize, false);
  90158. VirtualJoystick.vjCanvas = document.createElement("canvas");
  90159. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  90160. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  90161. VirtualJoystick.vjCanvas.width = window.innerWidth;
  90162. VirtualJoystick.vjCanvas.height = window.innerHeight;
  90163. VirtualJoystick.vjCanvas.style.width = "100%";
  90164. VirtualJoystick.vjCanvas.style.height = "100%";
  90165. VirtualJoystick.vjCanvas.style.position = "absolute";
  90166. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  90167. VirtualJoystick.vjCanvas.style.top = "0px";
  90168. VirtualJoystick.vjCanvas.style.left = "0px";
  90169. VirtualJoystick.vjCanvas.style.zIndex = "5";
  90170. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  90171. // Support for jQuery PEP polyfill
  90172. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  90173. var context = VirtualJoystick.vjCanvas.getContext('2d');
  90174. if (!context) {
  90175. throw new Error("Unable to create canvas for virtual joystick");
  90176. }
  90177. VirtualJoystick.vjCanvasContext = context;
  90178. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  90179. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90180. document.body.appendChild(VirtualJoystick.vjCanvas);
  90181. }
  90182. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  90183. this.pressed = false;
  90184. // default joystick color
  90185. this._joystickColor = "cyan";
  90186. this._joystickPointerID = -1;
  90187. // current joystick position
  90188. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  90189. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  90190. // origin joystick position
  90191. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  90192. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  90193. this._onPointerDownHandlerRef = function (evt) {
  90194. _this._onPointerDown(evt);
  90195. };
  90196. this._onPointerMoveHandlerRef = function (evt) {
  90197. _this._onPointerMove(evt);
  90198. };
  90199. this._onPointerUpHandlerRef = function (evt) {
  90200. _this._onPointerUp(evt);
  90201. };
  90202. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  90203. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  90204. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  90205. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  90206. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  90207. evt.preventDefault(); // Disables system menu
  90208. }, false);
  90209. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90210. }
  90211. /**
  90212. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  90213. * @param newJoystickSensibility defines the new sensibility
  90214. */
  90215. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  90216. this._joystickSensibility = newJoystickSensibility;
  90217. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  90218. };
  90219. VirtualJoystick.prototype._onPointerDown = function (e) {
  90220. var positionOnScreenCondition;
  90221. e.preventDefault();
  90222. if (this._leftJoystick === true) {
  90223. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  90224. }
  90225. else {
  90226. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  90227. }
  90228. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  90229. // First contact will be dedicated to the virtual joystick
  90230. this._joystickPointerID = e.pointerId;
  90231. this._joystickPointerStartPos.x = e.clientX;
  90232. this._joystickPointerStartPos.y = e.clientY;
  90233. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  90234. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  90235. this._deltaJoystickVector.x = 0;
  90236. this._deltaJoystickVector.y = 0;
  90237. this.pressed = true;
  90238. this._touches.add(e.pointerId.toString(), e);
  90239. }
  90240. else {
  90241. // You can only trigger the action buttons with a joystick declared
  90242. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  90243. this._action();
  90244. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  90245. }
  90246. }
  90247. };
  90248. VirtualJoystick.prototype._onPointerMove = function (e) {
  90249. // If the current pointer is the one associated to the joystick (first touch contact)
  90250. if (this._joystickPointerID == e.pointerId) {
  90251. this._joystickPointerPos.x = e.clientX;
  90252. this._joystickPointerPos.y = e.clientY;
  90253. this._deltaJoystickVector = this._joystickPointerPos.clone();
  90254. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  90255. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  90256. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  90257. switch (this._axisTargetedByLeftAndRight) {
  90258. case JoystickAxis.X:
  90259. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  90260. break;
  90261. case JoystickAxis.Y:
  90262. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  90263. break;
  90264. case JoystickAxis.Z:
  90265. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  90266. break;
  90267. }
  90268. var directionUpDown = this.reverseUpDown ? 1 : -1;
  90269. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  90270. switch (this._axisTargetedByUpAndDown) {
  90271. case JoystickAxis.X:
  90272. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  90273. break;
  90274. case JoystickAxis.Y:
  90275. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  90276. break;
  90277. case JoystickAxis.Z:
  90278. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  90279. break;
  90280. }
  90281. }
  90282. else {
  90283. var data = this._touches.get(e.pointerId.toString());
  90284. if (data) {
  90285. data.x = e.clientX;
  90286. data.y = e.clientY;
  90287. }
  90288. }
  90289. };
  90290. VirtualJoystick.prototype._onPointerUp = function (e) {
  90291. if (this._joystickPointerID == e.pointerId) {
  90292. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  90293. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  90294. this._joystickPointerID = -1;
  90295. this.pressed = false;
  90296. }
  90297. else {
  90298. var touch = this._touches.get(e.pointerId.toString());
  90299. if (touch) {
  90300. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90301. }
  90302. }
  90303. this._deltaJoystickVector.x = 0;
  90304. this._deltaJoystickVector.y = 0;
  90305. this._touches.remove(e.pointerId.toString());
  90306. };
  90307. /**
  90308. * Change the color of the virtual joystick
  90309. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  90310. */
  90311. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  90312. this._joystickColor = newColor;
  90313. };
  90314. /**
  90315. * Defines a callback to call when the joystick is touched
  90316. * @param action defines the callback
  90317. */
  90318. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  90319. this._action = action;
  90320. };
  90321. /**
  90322. * Defines which axis you'd like to control for left & right
  90323. * @param axis defines the axis to use
  90324. */
  90325. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  90326. switch (axis) {
  90327. case JoystickAxis.X:
  90328. case JoystickAxis.Y:
  90329. case JoystickAxis.Z:
  90330. this._axisTargetedByLeftAndRight = axis;
  90331. break;
  90332. default:
  90333. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90334. break;
  90335. }
  90336. };
  90337. /**
  90338. * Defines which axis you'd like to control for up & down
  90339. * @param axis defines the axis to use
  90340. */
  90341. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  90342. switch (axis) {
  90343. case JoystickAxis.X:
  90344. case JoystickAxis.Y:
  90345. case JoystickAxis.Z:
  90346. this._axisTargetedByUpAndDown = axis;
  90347. break;
  90348. default:
  90349. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90350. break;
  90351. }
  90352. };
  90353. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  90354. var _this = this;
  90355. if (this.pressed) {
  90356. this._touches.forEach(function (key, touch) {
  90357. if (touch.pointerId === _this._joystickPointerID) {
  90358. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  90359. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  90360. VirtualJoystick.vjCanvasContext.beginPath();
  90361. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90362. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90363. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  90364. VirtualJoystick.vjCanvasContext.stroke();
  90365. VirtualJoystick.vjCanvasContext.closePath();
  90366. VirtualJoystick.vjCanvasContext.beginPath();
  90367. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90368. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90369. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90370. VirtualJoystick.vjCanvasContext.stroke();
  90371. VirtualJoystick.vjCanvasContext.closePath();
  90372. VirtualJoystick.vjCanvasContext.beginPath();
  90373. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90374. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90375. VirtualJoystick.vjCanvasContext.stroke();
  90376. VirtualJoystick.vjCanvasContext.closePath();
  90377. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90378. }
  90379. else {
  90380. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90381. VirtualJoystick.vjCanvasContext.beginPath();
  90382. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90383. VirtualJoystick.vjCanvasContext.beginPath();
  90384. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90385. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90386. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90387. VirtualJoystick.vjCanvasContext.stroke();
  90388. VirtualJoystick.vjCanvasContext.closePath();
  90389. touch.prevX = touch.x;
  90390. touch.prevY = touch.y;
  90391. }
  90392. ;
  90393. });
  90394. }
  90395. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90396. };
  90397. /**
  90398. * Release internal HTML canvas
  90399. */
  90400. VirtualJoystick.prototype.releaseCanvas = function () {
  90401. if (VirtualJoystick.vjCanvas) {
  90402. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90403. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90404. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90405. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90406. window.removeEventListener("resize", this._onResize);
  90407. document.body.removeChild(VirtualJoystick.vjCanvas);
  90408. VirtualJoystick.vjCanvas = null;
  90409. }
  90410. };
  90411. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90412. VirtualJoystick._globalJoystickIndex = 0;
  90413. return VirtualJoystick;
  90414. }());
  90415. BABYLON.VirtualJoystick = VirtualJoystick;
  90416. })(BABYLON || (BABYLON = {}));
  90417. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90418. var BABYLON;
  90419. (function (BABYLON) {
  90420. // We're mainly based on the logic defined into the FreeCamera code
  90421. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90422. __extends(VirtualJoysticksCamera, _super);
  90423. function VirtualJoysticksCamera(name, position, scene) {
  90424. var _this = _super.call(this, name, position, scene) || this;
  90425. _this.inputs.addVirtualJoystick();
  90426. return _this;
  90427. }
  90428. VirtualJoysticksCamera.prototype.getClassName = function () {
  90429. return "VirtualJoysticksCamera";
  90430. };
  90431. return VirtualJoysticksCamera;
  90432. }(BABYLON.FreeCamera));
  90433. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90434. })(BABYLON || (BABYLON = {}));
  90435. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90436. var BABYLON;
  90437. (function (BABYLON) {
  90438. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90439. function FreeCameraVirtualJoystickInput() {
  90440. }
  90441. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90442. return this._leftjoystick;
  90443. };
  90444. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90445. return this._rightjoystick;
  90446. };
  90447. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90448. if (this._leftjoystick) {
  90449. var camera = this.camera;
  90450. var speed = camera._computeLocalCameraSpeed() * 50;
  90451. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90452. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90453. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90454. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90455. if (!this._leftjoystick.pressed) {
  90456. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90457. }
  90458. if (!this._rightjoystick.pressed) {
  90459. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90460. }
  90461. }
  90462. };
  90463. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90464. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90465. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90466. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90467. this._leftjoystick.setJoystickSensibility(0.15);
  90468. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90469. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90470. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90471. this._rightjoystick.reverseUpDown = true;
  90472. this._rightjoystick.setJoystickSensibility(0.05);
  90473. this._rightjoystick.setJoystickColor("yellow");
  90474. };
  90475. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90476. this._leftjoystick.releaseCanvas();
  90477. this._rightjoystick.releaseCanvas();
  90478. };
  90479. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90480. return "FreeCameraVirtualJoystickInput";
  90481. };
  90482. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90483. return "virtualJoystick";
  90484. };
  90485. return FreeCameraVirtualJoystickInput;
  90486. }());
  90487. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90488. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90489. })(BABYLON || (BABYLON = {}));
  90490. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90491. var BABYLON;
  90492. (function (BABYLON) {
  90493. var SimplificationSettings = /** @class */ (function () {
  90494. function SimplificationSettings(quality, distance, optimizeMesh) {
  90495. this.quality = quality;
  90496. this.distance = distance;
  90497. this.optimizeMesh = optimizeMesh;
  90498. }
  90499. return SimplificationSettings;
  90500. }());
  90501. BABYLON.SimplificationSettings = SimplificationSettings;
  90502. var SimplificationQueue = /** @class */ (function () {
  90503. function SimplificationQueue() {
  90504. this.running = false;
  90505. this._simplificationArray = [];
  90506. }
  90507. SimplificationQueue.prototype.addTask = function (task) {
  90508. this._simplificationArray.push(task);
  90509. };
  90510. SimplificationQueue.prototype.executeNext = function () {
  90511. var task = this._simplificationArray.pop();
  90512. if (task) {
  90513. this.running = true;
  90514. this.runSimplification(task);
  90515. }
  90516. else {
  90517. this.running = false;
  90518. }
  90519. };
  90520. SimplificationQueue.prototype.runSimplification = function (task) {
  90521. var _this = this;
  90522. if (task.parallelProcessing) {
  90523. //parallel simplifier
  90524. task.settings.forEach(function (setting) {
  90525. var simplifier = _this.getSimplifier(task);
  90526. simplifier.simplify(setting, function (newMesh) {
  90527. task.mesh.addLODLevel(setting.distance, newMesh);
  90528. newMesh.isVisible = true;
  90529. //check if it is the last
  90530. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90531. //all done, run the success callback.
  90532. task.successCallback();
  90533. }
  90534. _this.executeNext();
  90535. });
  90536. });
  90537. }
  90538. else {
  90539. //single simplifier.
  90540. var simplifier = this.getSimplifier(task);
  90541. var runDecimation = function (setting, callback) {
  90542. simplifier.simplify(setting, function (newMesh) {
  90543. task.mesh.addLODLevel(setting.distance, newMesh);
  90544. newMesh.isVisible = true;
  90545. //run the next quality level
  90546. callback();
  90547. });
  90548. };
  90549. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90550. runDecimation(task.settings[loop.index], function () {
  90551. loop.executeNext();
  90552. });
  90553. }, function () {
  90554. //execution ended, run the success callback.
  90555. if (task.successCallback) {
  90556. task.successCallback();
  90557. }
  90558. _this.executeNext();
  90559. });
  90560. }
  90561. };
  90562. SimplificationQueue.prototype.getSimplifier = function (task) {
  90563. switch (task.simplificationType) {
  90564. case SimplificationType.QUADRATIC:
  90565. default:
  90566. return new QuadraticErrorSimplification(task.mesh);
  90567. }
  90568. };
  90569. return SimplificationQueue;
  90570. }());
  90571. BABYLON.SimplificationQueue = SimplificationQueue;
  90572. /**
  90573. * The implemented types of simplification
  90574. * At the moment only Quadratic Error Decimation is implemented
  90575. */
  90576. var SimplificationType;
  90577. (function (SimplificationType) {
  90578. /** Quadratic error decimation */
  90579. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90580. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90581. var DecimationTriangle = /** @class */ (function () {
  90582. function DecimationTriangle(vertices) {
  90583. this.vertices = vertices;
  90584. this.error = new Array(4);
  90585. this.deleted = false;
  90586. this.isDirty = false;
  90587. this.deletePending = false;
  90588. this.borderFactor = 0;
  90589. }
  90590. return DecimationTriangle;
  90591. }());
  90592. BABYLON.DecimationTriangle = DecimationTriangle;
  90593. var DecimationVertex = /** @class */ (function () {
  90594. function DecimationVertex(position, id) {
  90595. this.position = position;
  90596. this.id = id;
  90597. this.isBorder = true;
  90598. this.q = new QuadraticMatrix();
  90599. this.triangleCount = 0;
  90600. this.triangleStart = 0;
  90601. this.originalOffsets = [];
  90602. }
  90603. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90604. this.position.copyFrom(newPosition);
  90605. };
  90606. return DecimationVertex;
  90607. }());
  90608. BABYLON.DecimationVertex = DecimationVertex;
  90609. var QuadraticMatrix = /** @class */ (function () {
  90610. function QuadraticMatrix(data) {
  90611. this.data = new Array(10);
  90612. for (var i = 0; i < 10; ++i) {
  90613. if (data && data[i]) {
  90614. this.data[i] = data[i];
  90615. }
  90616. else {
  90617. this.data[i] = 0;
  90618. }
  90619. }
  90620. }
  90621. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90622. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90623. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90624. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90625. return det;
  90626. };
  90627. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90628. for (var i = 0; i < 10; ++i) {
  90629. this.data[i] += matrix.data[i];
  90630. }
  90631. };
  90632. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90633. for (var i = 0; i < 10; ++i) {
  90634. this.data[i] += data[i];
  90635. }
  90636. };
  90637. QuadraticMatrix.prototype.add = function (matrix) {
  90638. var m = new QuadraticMatrix();
  90639. for (var i = 0; i < 10; ++i) {
  90640. m.data[i] = this.data[i] + matrix.data[i];
  90641. }
  90642. return m;
  90643. };
  90644. QuadraticMatrix.FromData = function (a, b, c, d) {
  90645. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90646. };
  90647. //returning an array to avoid garbage collection
  90648. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90649. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90650. };
  90651. return QuadraticMatrix;
  90652. }());
  90653. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90654. var Reference = /** @class */ (function () {
  90655. function Reference(vertexId, triangleId) {
  90656. this.vertexId = vertexId;
  90657. this.triangleId = triangleId;
  90658. }
  90659. return Reference;
  90660. }());
  90661. BABYLON.Reference = Reference;
  90662. /**
  90663. * An implementation of the Quadratic Error simplification algorithm.
  90664. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90665. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90666. * @author RaananW
  90667. */
  90668. var QuadraticErrorSimplification = /** @class */ (function () {
  90669. function QuadraticErrorSimplification(_mesh) {
  90670. this._mesh = _mesh;
  90671. this.syncIterations = 5000;
  90672. this.aggressiveness = 7;
  90673. this.decimationIterations = 100;
  90674. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90675. }
  90676. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90677. var _this = this;
  90678. this.initDecimatedMesh();
  90679. //iterating through the submeshes array, one after the other.
  90680. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90681. _this.initWithMesh(loop.index, function () {
  90682. _this.runDecimation(settings, loop.index, function () {
  90683. loop.executeNext();
  90684. });
  90685. }, settings.optimizeMesh);
  90686. }, function () {
  90687. setTimeout(function () {
  90688. successCallback(_this._reconstructedMesh);
  90689. }, 0);
  90690. });
  90691. };
  90692. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90693. var _this = this;
  90694. var targetCount = ~~(this.triangles.length * settings.quality);
  90695. var deletedTriangles = 0;
  90696. var triangleCount = this.triangles.length;
  90697. var iterationFunction = function (iteration, callback) {
  90698. setTimeout(function () {
  90699. if (iteration % 5 === 0) {
  90700. _this.updateMesh(iteration === 0);
  90701. }
  90702. for (var i = 0; i < _this.triangles.length; ++i) {
  90703. _this.triangles[i].isDirty = false;
  90704. }
  90705. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90706. var trianglesIterator = function (i) {
  90707. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90708. var t = _this.triangles[tIdx];
  90709. if (!t)
  90710. return;
  90711. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90712. return;
  90713. }
  90714. for (var j = 0; j < 3; ++j) {
  90715. if (t.error[j] < threshold) {
  90716. var deleted0 = [];
  90717. var deleted1 = [];
  90718. var v0 = t.vertices[j];
  90719. var v1 = t.vertices[(j + 1) % 3];
  90720. if (v0.isBorder || v1.isBorder)
  90721. continue;
  90722. var p = BABYLON.Vector3.Zero();
  90723. var n = BABYLON.Vector3.Zero();
  90724. var uv = BABYLON.Vector2.Zero();
  90725. var color = new BABYLON.Color4(0, 0, 0, 1);
  90726. _this.calculateError(v0, v1, p, n, uv, color);
  90727. var delTr = new Array();
  90728. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90729. continue;
  90730. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90731. continue;
  90732. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90733. continue;
  90734. var uniqueArray = new Array();
  90735. delTr.forEach(function (deletedT) {
  90736. if (uniqueArray.indexOf(deletedT) === -1) {
  90737. deletedT.deletePending = true;
  90738. uniqueArray.push(deletedT);
  90739. }
  90740. });
  90741. if (uniqueArray.length % 2 !== 0) {
  90742. continue;
  90743. }
  90744. v0.q = v1.q.add(v0.q);
  90745. v0.updatePosition(p);
  90746. var tStart = _this.references.length;
  90747. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90748. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90749. var tCount = _this.references.length - tStart;
  90750. if (tCount <= v0.triangleCount) {
  90751. if (tCount) {
  90752. for (var c = 0; c < tCount; c++) {
  90753. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90754. }
  90755. }
  90756. }
  90757. else {
  90758. v0.triangleStart = tStart;
  90759. }
  90760. v0.triangleCount = tCount;
  90761. break;
  90762. }
  90763. }
  90764. };
  90765. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90766. }, 0);
  90767. };
  90768. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90769. if (triangleCount - deletedTriangles <= targetCount)
  90770. loop.breakLoop();
  90771. else {
  90772. iterationFunction(loop.index, function () {
  90773. loop.executeNext();
  90774. });
  90775. }
  90776. }, function () {
  90777. setTimeout(function () {
  90778. //reconstruct this part of the mesh
  90779. _this.reconstructMesh(submeshIndex);
  90780. successCallback();
  90781. }, 0);
  90782. });
  90783. };
  90784. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90785. var _this = this;
  90786. this.vertices = [];
  90787. this.triangles = [];
  90788. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90789. var indices = this._mesh.getIndices();
  90790. var submesh = this._mesh.subMeshes[submeshIndex];
  90791. var findInVertices = function (positionToSearch) {
  90792. if (optimizeMesh) {
  90793. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90794. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90795. return _this.vertices[ii];
  90796. }
  90797. }
  90798. }
  90799. return null;
  90800. };
  90801. var vertexReferences = [];
  90802. var vertexInit = function (i) {
  90803. if (!positionData) {
  90804. return;
  90805. }
  90806. var offset = i + submesh.verticesStart;
  90807. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90808. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90809. vertex.originalOffsets.push(offset);
  90810. if (vertex.id === _this.vertices.length) {
  90811. _this.vertices.push(vertex);
  90812. }
  90813. vertexReferences.push(vertex.id);
  90814. };
  90815. //var totalVertices = mesh.getTotalVertices();
  90816. var totalVertices = submesh.verticesCount;
  90817. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90818. var indicesInit = function (i) {
  90819. if (!indices) {
  90820. return;
  90821. }
  90822. var offset = (submesh.indexStart / 3) + i;
  90823. var pos = (offset * 3);
  90824. var i0 = indices[pos + 0];
  90825. var i1 = indices[pos + 1];
  90826. var i2 = indices[pos + 2];
  90827. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90828. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90829. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90830. var triangle = new DecimationTriangle([v0, v1, v2]);
  90831. triangle.originalOffset = pos;
  90832. _this.triangles.push(triangle);
  90833. };
  90834. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90835. _this.init(callback);
  90836. });
  90837. });
  90838. };
  90839. QuadraticErrorSimplification.prototype.init = function (callback) {
  90840. var _this = this;
  90841. var triangleInit1 = function (i) {
  90842. var t = _this.triangles[i];
  90843. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90844. for (var j = 0; j < 3; j++) {
  90845. 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))));
  90846. }
  90847. };
  90848. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90849. var triangleInit2 = function (i) {
  90850. var t = _this.triangles[i];
  90851. for (var j = 0; j < 3; ++j) {
  90852. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90853. }
  90854. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90855. };
  90856. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90857. callback();
  90858. });
  90859. });
  90860. };
  90861. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90862. var newTriangles = [];
  90863. var i;
  90864. for (i = 0; i < this.vertices.length; ++i) {
  90865. this.vertices[i].triangleCount = 0;
  90866. }
  90867. var t;
  90868. var j;
  90869. for (i = 0; i < this.triangles.length; ++i) {
  90870. if (!this.triangles[i].deleted) {
  90871. t = this.triangles[i];
  90872. for (j = 0; j < 3; ++j) {
  90873. t.vertices[j].triangleCount = 1;
  90874. }
  90875. newTriangles.push(t);
  90876. }
  90877. }
  90878. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90879. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90880. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90881. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90882. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90883. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90884. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90885. var vertexCount = 0;
  90886. for (i = 0; i < this.vertices.length; ++i) {
  90887. var vertex = this.vertices[i];
  90888. vertex.id = vertexCount;
  90889. if (vertex.triangleCount) {
  90890. vertex.originalOffsets.forEach(function (originalOffset) {
  90891. if (!normalData) {
  90892. return;
  90893. }
  90894. newPositionData.push(vertex.position.x);
  90895. newPositionData.push(vertex.position.y);
  90896. newPositionData.push(vertex.position.z);
  90897. newNormalData.push(normalData[originalOffset * 3]);
  90898. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90899. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90900. if (uvs && uvs.length) {
  90901. newUVsData.push(uvs[(originalOffset * 2)]);
  90902. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90903. }
  90904. else if (colorsData && colorsData.length) {
  90905. newColorsData.push(colorsData[(originalOffset * 4)]);
  90906. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90907. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90908. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90909. }
  90910. ++vertexCount;
  90911. });
  90912. }
  90913. }
  90914. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90915. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90916. var submeshesArray = this._reconstructedMesh.subMeshes;
  90917. this._reconstructedMesh.subMeshes = [];
  90918. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90919. var originalIndices = this._mesh.getIndices();
  90920. for (i = 0; i < newTriangles.length; ++i) {
  90921. t = newTriangles[i]; //now get the new referencing point for each vertex
  90922. [0, 1, 2].forEach(function (idx) {
  90923. var id = originalIndices[t.originalOffset + idx];
  90924. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90925. if (offset < 0)
  90926. offset = 0;
  90927. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90928. });
  90929. }
  90930. //overwriting the old vertex buffers and indices.
  90931. this._reconstructedMesh.setIndices(newIndicesArray);
  90932. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90933. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90934. if (newUVsData.length > 0)
  90935. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90936. if (newColorsData.length > 0)
  90937. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90938. //create submesh
  90939. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90940. if (submeshIndex > 0) {
  90941. this._reconstructedMesh.subMeshes = [];
  90942. submeshesArray.forEach(function (submesh) {
  90943. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90944. });
  90945. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90946. }
  90947. };
  90948. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90949. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90950. this._reconstructedMesh.material = this._mesh.material;
  90951. this._reconstructedMesh.parent = this._mesh.parent;
  90952. this._reconstructedMesh.isVisible = false;
  90953. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90954. };
  90955. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90956. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90957. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90958. if (t.deleted)
  90959. continue;
  90960. var s = this.references[vertex1.triangleStart + i].vertexId;
  90961. var v1 = t.vertices[(s + 1) % 3];
  90962. var v2 = t.vertices[(s + 2) % 3];
  90963. if ((v1 === vertex2 || v2 === vertex2)) {
  90964. deletedArray[i] = true;
  90965. delTr.push(t);
  90966. continue;
  90967. }
  90968. var d1 = v1.position.subtract(point);
  90969. d1 = d1.normalize();
  90970. var d2 = v2.position.subtract(point);
  90971. d2 = d2.normalize();
  90972. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90973. return true;
  90974. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90975. deletedArray[i] = false;
  90976. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90977. return true;
  90978. }
  90979. return false;
  90980. };
  90981. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90982. var newDeleted = deletedTriangles;
  90983. for (var i = 0; i < vertex.triangleCount; ++i) {
  90984. var ref = this.references[vertex.triangleStart + i];
  90985. var t = this.triangles[ref.triangleId];
  90986. if (t.deleted)
  90987. continue;
  90988. if (deletedArray[i] && t.deletePending) {
  90989. t.deleted = true;
  90990. newDeleted++;
  90991. continue;
  90992. }
  90993. t.vertices[ref.vertexId] = origVertex;
  90994. t.isDirty = true;
  90995. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90996. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90997. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90998. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90999. this.references.push(ref);
  91000. }
  91001. return newDeleted;
  91002. };
  91003. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  91004. for (var i = 0; i < this.vertices.length; ++i) {
  91005. var vCount = [];
  91006. var vId = [];
  91007. var v = this.vertices[i];
  91008. var j;
  91009. for (j = 0; j < v.triangleCount; ++j) {
  91010. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  91011. for (var ii = 0; ii < 3; ii++) {
  91012. var ofs = 0;
  91013. var vv = triangle.vertices[ii];
  91014. while (ofs < vCount.length) {
  91015. if (vId[ofs] === vv.id)
  91016. break;
  91017. ++ofs;
  91018. }
  91019. if (ofs === vCount.length) {
  91020. vCount.push(1);
  91021. vId.push(vv.id);
  91022. }
  91023. else {
  91024. vCount[ofs]++;
  91025. }
  91026. }
  91027. }
  91028. for (j = 0; j < vCount.length; ++j) {
  91029. if (vCount[j] === 1) {
  91030. this.vertices[vId[j]].isBorder = true;
  91031. }
  91032. else {
  91033. this.vertices[vId[j]].isBorder = false;
  91034. }
  91035. }
  91036. }
  91037. };
  91038. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  91039. if (identifyBorders === void 0) { identifyBorders = false; }
  91040. var i;
  91041. if (!identifyBorders) {
  91042. var newTrianglesVector = [];
  91043. for (i = 0; i < this.triangles.length; ++i) {
  91044. if (!this.triangles[i].deleted) {
  91045. newTrianglesVector.push(this.triangles[i]);
  91046. }
  91047. }
  91048. this.triangles = newTrianglesVector;
  91049. }
  91050. for (i = 0; i < this.vertices.length; ++i) {
  91051. this.vertices[i].triangleCount = 0;
  91052. this.vertices[i].triangleStart = 0;
  91053. }
  91054. var t;
  91055. var j;
  91056. var v;
  91057. for (i = 0; i < this.triangles.length; ++i) {
  91058. t = this.triangles[i];
  91059. for (j = 0; j < 3; ++j) {
  91060. v = t.vertices[j];
  91061. v.triangleCount++;
  91062. }
  91063. }
  91064. var tStart = 0;
  91065. for (i = 0; i < this.vertices.length; ++i) {
  91066. this.vertices[i].triangleStart = tStart;
  91067. tStart += this.vertices[i].triangleCount;
  91068. this.vertices[i].triangleCount = 0;
  91069. }
  91070. var newReferences = new Array(this.triangles.length * 3);
  91071. for (i = 0; i < this.triangles.length; ++i) {
  91072. t = this.triangles[i];
  91073. for (j = 0; j < 3; ++j) {
  91074. v = t.vertices[j];
  91075. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  91076. v.triangleCount++;
  91077. }
  91078. }
  91079. this.references = newReferences;
  91080. if (identifyBorders) {
  91081. this.identifyBorder();
  91082. }
  91083. };
  91084. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  91085. var x = point.x;
  91086. var y = point.y;
  91087. var z = point.z;
  91088. 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
  91089. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  91090. };
  91091. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  91092. var q = vertex1.q.add(vertex2.q);
  91093. var border = vertex1.isBorder && vertex2.isBorder;
  91094. var error = 0;
  91095. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  91096. if (qDet !== 0 && !border) {
  91097. if (!pointResult) {
  91098. pointResult = BABYLON.Vector3.Zero();
  91099. }
  91100. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  91101. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  91102. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  91103. error = this.vertexError(q, pointResult);
  91104. }
  91105. else {
  91106. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  91107. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  91108. var error1 = this.vertexError(q, vertex1.position);
  91109. var error2 = this.vertexError(q, vertex2.position);
  91110. var error3 = this.vertexError(q, p3);
  91111. error = Math.min(error1, error2, error3);
  91112. if (error === error1) {
  91113. if (pointResult) {
  91114. pointResult.copyFrom(vertex1.position);
  91115. }
  91116. }
  91117. else if (error === error2) {
  91118. if (pointResult) {
  91119. pointResult.copyFrom(vertex2.position);
  91120. }
  91121. }
  91122. else {
  91123. if (pointResult) {
  91124. pointResult.copyFrom(p3);
  91125. }
  91126. }
  91127. }
  91128. return error;
  91129. };
  91130. return QuadraticErrorSimplification;
  91131. }());
  91132. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  91133. })(BABYLON || (BABYLON = {}));
  91134. //# sourceMappingURL=babylon.meshSimplification.js.map
  91135. var BABYLON;
  91136. (function (BABYLON) {
  91137. var MeshLODLevel = /** @class */ (function () {
  91138. function MeshLODLevel(distance, mesh) {
  91139. this.distance = distance;
  91140. this.mesh = mesh;
  91141. }
  91142. return MeshLODLevel;
  91143. }());
  91144. BABYLON.MeshLODLevel = MeshLODLevel;
  91145. })(BABYLON || (BABYLON = {}));
  91146. //# sourceMappingURL=babylon.meshLODLevel.js.map
  91147. var BABYLON;
  91148. (function (BABYLON) {
  91149. /**
  91150. * Defines the root class used to create scene optimization to use with SceneOptimizer
  91151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91152. */
  91153. var SceneOptimization = /** @class */ (function () {
  91154. /**
  91155. * Creates the SceneOptimization object
  91156. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91157. * @param desc defines the description associated with the optimization
  91158. */
  91159. function SceneOptimization(
  91160. /**
  91161. * Defines the priority of this optimization (0 by default which means first in the list)
  91162. */
  91163. priority) {
  91164. if (priority === void 0) { priority = 0; }
  91165. this.priority = priority;
  91166. }
  91167. /**
  91168. * Gets a string describing the action executed by the current optimization
  91169. * @returns description string
  91170. */
  91171. SceneOptimization.prototype.getDescription = function () {
  91172. return "";
  91173. };
  91174. /**
  91175. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91176. * @param scene defines the current scene where to apply this optimization
  91177. * @param optimizer defines the current optimizer
  91178. * @returns true if everything that can be done was applied
  91179. */
  91180. SceneOptimization.prototype.apply = function (scene, optimizer) {
  91181. return true;
  91182. };
  91183. ;
  91184. return SceneOptimization;
  91185. }());
  91186. BABYLON.SceneOptimization = SceneOptimization;
  91187. /**
  91188. * Defines an optimization used to reduce the size of render target textures
  91189. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91190. */
  91191. var TextureOptimization = /** @class */ (function (_super) {
  91192. __extends(TextureOptimization, _super);
  91193. /**
  91194. * Creates the TextureOptimization object
  91195. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91196. * @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
  91197. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  91198. */
  91199. function TextureOptimization(
  91200. /**
  91201. * Defines the priority of this optimization (0 by default which means first in the list)
  91202. */
  91203. priority,
  91204. /**
  91205. * 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
  91206. */
  91207. maximumSize,
  91208. /**
  91209. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  91210. */
  91211. step) {
  91212. if (priority === void 0) { priority = 0; }
  91213. if (maximumSize === void 0) { maximumSize = 1024; }
  91214. if (step === void 0) { step = 0.5; }
  91215. var _this = _super.call(this, priority) || this;
  91216. _this.priority = priority;
  91217. _this.maximumSize = maximumSize;
  91218. _this.step = step;
  91219. return _this;
  91220. }
  91221. /**
  91222. * Gets a string describing the action executed by the current optimization
  91223. * @returns description string
  91224. */
  91225. TextureOptimization.prototype.getDescription = function () {
  91226. return "Reducing render target texture size to " + this.maximumSize;
  91227. };
  91228. /**
  91229. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91230. * @param scene defines the current scene where to apply this optimization
  91231. * @param optimizer defines the current optimizer
  91232. * @returns true if everything that can be done was applied
  91233. */
  91234. TextureOptimization.prototype.apply = function (scene, optimizer) {
  91235. var allDone = true;
  91236. for (var index = 0; index < scene.textures.length; index++) {
  91237. var texture = scene.textures[index];
  91238. if (!texture.canRescale || texture.getContext) {
  91239. continue;
  91240. }
  91241. var currentSize = texture.getSize();
  91242. var maxDimension = Math.max(currentSize.width, currentSize.height);
  91243. if (maxDimension > this.maximumSize) {
  91244. texture.scale(this.step);
  91245. allDone = false;
  91246. }
  91247. }
  91248. return allDone;
  91249. };
  91250. return TextureOptimization;
  91251. }(SceneOptimization));
  91252. BABYLON.TextureOptimization = TextureOptimization;
  91253. /**
  91254. * Defines an optimization used to increase or decrease the rendering resolution
  91255. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91256. */
  91257. var HardwareScalingOptimization = /** @class */ (function (_super) {
  91258. __extends(HardwareScalingOptimization, _super);
  91259. /**
  91260. * Creates the HardwareScalingOptimization object
  91261. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91262. * @param maximumScale defines the maximum scale to use (2 by default)
  91263. * @param step defines the step to use between two passes (0.5 by default)
  91264. */
  91265. function HardwareScalingOptimization(
  91266. /**
  91267. * Defines the priority of this optimization (0 by default which means first in the list)
  91268. */
  91269. priority,
  91270. /**
  91271. * Defines the maximum scale to use (2 by default)
  91272. */
  91273. maximumScale,
  91274. /**
  91275. * Defines the step to use between two passes (0.5 by default)
  91276. */
  91277. step) {
  91278. if (priority === void 0) { priority = 0; }
  91279. if (maximumScale === void 0) { maximumScale = 2; }
  91280. if (step === void 0) { step = 0.25; }
  91281. var _this = _super.call(this, priority) || this;
  91282. _this.priority = priority;
  91283. _this.maximumScale = maximumScale;
  91284. _this.step = step;
  91285. _this._currentScale = -1;
  91286. _this._directionOffset = 1;
  91287. return _this;
  91288. }
  91289. /**
  91290. * Gets a string describing the action executed by the current optimization
  91291. * @return description string
  91292. */
  91293. HardwareScalingOptimization.prototype.getDescription = function () {
  91294. return "Setting hardware scaling level to " + this._currentScale;
  91295. };
  91296. /**
  91297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91298. * @param scene defines the current scene where to apply this optimization
  91299. * @param optimizer defines the current optimizer
  91300. * @returns true if everything that can be done was applied
  91301. */
  91302. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  91303. if (this._currentScale === -1) {
  91304. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  91305. if (this._currentScale > this.maximumScale) {
  91306. this._directionOffset = -1;
  91307. }
  91308. }
  91309. this._currentScale += this._directionOffset * this.step;
  91310. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  91311. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  91312. };
  91313. ;
  91314. return HardwareScalingOptimization;
  91315. }(SceneOptimization));
  91316. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  91317. /**
  91318. * Defines an optimization used to remove shadows
  91319. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91320. */
  91321. var ShadowsOptimization = /** @class */ (function (_super) {
  91322. __extends(ShadowsOptimization, _super);
  91323. function ShadowsOptimization() {
  91324. return _super !== null && _super.apply(this, arguments) || this;
  91325. }
  91326. /**
  91327. * Gets a string describing the action executed by the current optimization
  91328. * @return description string
  91329. */
  91330. ShadowsOptimization.prototype.getDescription = function () {
  91331. return "Turning shadows on/off";
  91332. };
  91333. /**
  91334. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91335. * @param scene defines the current scene where to apply this optimization
  91336. * @param optimizer defines the current optimizer
  91337. * @returns true if everything that can be done was applied
  91338. */
  91339. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  91340. scene.shadowsEnabled = optimizer.isInImprovementMode;
  91341. return true;
  91342. };
  91343. ;
  91344. return ShadowsOptimization;
  91345. }(SceneOptimization));
  91346. BABYLON.ShadowsOptimization = ShadowsOptimization;
  91347. /**
  91348. * Defines an optimization used to turn post-processes off
  91349. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91350. */
  91351. var PostProcessesOptimization = /** @class */ (function (_super) {
  91352. __extends(PostProcessesOptimization, _super);
  91353. function PostProcessesOptimization() {
  91354. return _super !== null && _super.apply(this, arguments) || this;
  91355. }
  91356. /**
  91357. * Gets a string describing the action executed by the current optimization
  91358. * @return description string
  91359. */
  91360. PostProcessesOptimization.prototype.getDescription = function () {
  91361. return "Turning post-processes on/off";
  91362. };
  91363. /**
  91364. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91365. * @param scene defines the current scene where to apply this optimization
  91366. * @param optimizer defines the current optimizer
  91367. * @returns true if everything that can be done was applied
  91368. */
  91369. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91370. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91371. return true;
  91372. };
  91373. ;
  91374. return PostProcessesOptimization;
  91375. }(SceneOptimization));
  91376. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91377. /**
  91378. * Defines an optimization used to turn lens flares off
  91379. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91380. */
  91381. var LensFlaresOptimization = /** @class */ (function (_super) {
  91382. __extends(LensFlaresOptimization, _super);
  91383. function LensFlaresOptimization() {
  91384. return _super !== null && _super.apply(this, arguments) || this;
  91385. }
  91386. /**
  91387. * Gets a string describing the action executed by the current optimization
  91388. * @return description string
  91389. */
  91390. LensFlaresOptimization.prototype.getDescription = function () {
  91391. return "Turning lens flares on/off";
  91392. };
  91393. /**
  91394. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91395. * @param scene defines the current scene where to apply this optimization
  91396. * @param optimizer defines the current optimizer
  91397. * @returns true if everything that can be done was applied
  91398. */
  91399. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91400. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91401. return true;
  91402. };
  91403. ;
  91404. return LensFlaresOptimization;
  91405. }(SceneOptimization));
  91406. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91407. /**
  91408. * Defines an optimization based on user defined callback.
  91409. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91410. */
  91411. var CustomOptimization = /** @class */ (function (_super) {
  91412. __extends(CustomOptimization, _super);
  91413. function CustomOptimization() {
  91414. return _super !== null && _super.apply(this, arguments) || this;
  91415. }
  91416. /**
  91417. * Gets a string describing the action executed by the current optimization
  91418. * @returns description string
  91419. */
  91420. CustomOptimization.prototype.getDescription = function () {
  91421. if (this.onGetDescription) {
  91422. return this.onGetDescription();
  91423. }
  91424. return "Running user defined callback";
  91425. };
  91426. /**
  91427. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91428. * @param scene defines the current scene where to apply this optimization
  91429. * @param optimizer defines the current optimizer
  91430. * @returns true if everything that can be done was applied
  91431. */
  91432. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91433. if (this.onApply) {
  91434. return this.onApply(scene, optimizer);
  91435. }
  91436. return true;
  91437. };
  91438. ;
  91439. return CustomOptimization;
  91440. }(SceneOptimization));
  91441. BABYLON.CustomOptimization = CustomOptimization;
  91442. /**
  91443. * Defines an optimization used to turn particles off
  91444. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91445. */
  91446. var ParticlesOptimization = /** @class */ (function (_super) {
  91447. __extends(ParticlesOptimization, _super);
  91448. function ParticlesOptimization() {
  91449. return _super !== null && _super.apply(this, arguments) || this;
  91450. }
  91451. /**
  91452. * Gets a string describing the action executed by the current optimization
  91453. * @return description string
  91454. */
  91455. ParticlesOptimization.prototype.getDescription = function () {
  91456. return "Turning particles on/off";
  91457. };
  91458. /**
  91459. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91460. * @param scene defines the current scene where to apply this optimization
  91461. * @param optimizer defines the current optimizer
  91462. * @returns true if everything that can be done was applied
  91463. */
  91464. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91465. scene.particlesEnabled = optimizer.isInImprovementMode;
  91466. return true;
  91467. };
  91468. ;
  91469. return ParticlesOptimization;
  91470. }(SceneOptimization));
  91471. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91472. /**
  91473. * Defines an optimization used to turn render targets off
  91474. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91475. */
  91476. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91477. __extends(RenderTargetsOptimization, _super);
  91478. function RenderTargetsOptimization() {
  91479. return _super !== null && _super.apply(this, arguments) || this;
  91480. }
  91481. /**
  91482. * Gets a string describing the action executed by the current optimization
  91483. * @return description string
  91484. */
  91485. RenderTargetsOptimization.prototype.getDescription = function () {
  91486. return "Turning render targets off";
  91487. };
  91488. /**
  91489. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91490. * @param scene defines the current scene where to apply this optimization
  91491. * @param optimizer defines the current optimizer
  91492. * @returns true if everything that can be done was applied
  91493. */
  91494. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91495. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91496. return true;
  91497. };
  91498. ;
  91499. return RenderTargetsOptimization;
  91500. }(SceneOptimization));
  91501. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91502. /**
  91503. * Defines an optimization used to merge meshes with compatible materials
  91504. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91505. */
  91506. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91507. __extends(MergeMeshesOptimization, _super);
  91508. function MergeMeshesOptimization() {
  91509. var _this = _super !== null && _super.apply(this, arguments) || this;
  91510. _this._canBeMerged = function (abstractMesh) {
  91511. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91512. return false;
  91513. }
  91514. var mesh = abstractMesh;
  91515. if (!mesh.isVisible || !mesh.isEnabled()) {
  91516. return false;
  91517. }
  91518. if (mesh.instances.length > 0) {
  91519. return false;
  91520. }
  91521. if (mesh.skeleton || mesh.hasLODLevels) {
  91522. return false;
  91523. }
  91524. if (mesh.parent) {
  91525. return false;
  91526. }
  91527. return true;
  91528. };
  91529. return _this;
  91530. }
  91531. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91532. /**
  91533. * Gets or sets a boolean which defines if optimization octree has to be updated
  91534. */
  91535. get: function () {
  91536. return MergeMeshesOptimization._UpdateSelectionTree;
  91537. },
  91538. /**
  91539. * Gets or sets a boolean which defines if optimization octree has to be updated
  91540. */
  91541. set: function (value) {
  91542. MergeMeshesOptimization._UpdateSelectionTree = value;
  91543. },
  91544. enumerable: true,
  91545. configurable: true
  91546. });
  91547. /**
  91548. * Gets a string describing the action executed by the current optimization
  91549. * @return description string
  91550. */
  91551. MergeMeshesOptimization.prototype.getDescription = function () {
  91552. return "Merging similar meshes together";
  91553. };
  91554. /**
  91555. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91556. * @param scene defines the current scene where to apply this optimization
  91557. * @param optimizer defines the current optimizer
  91558. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91559. * @returns true if everything that can be done was applied
  91560. */
  91561. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91562. var globalPool = scene.meshes.slice(0);
  91563. var globalLength = globalPool.length;
  91564. for (var index = 0; index < globalLength; index++) {
  91565. var currentPool = new Array();
  91566. var current = globalPool[index];
  91567. // Checks
  91568. if (!this._canBeMerged(current)) {
  91569. continue;
  91570. }
  91571. currentPool.push(current);
  91572. // Find compatible meshes
  91573. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91574. var otherMesh = globalPool[subIndex];
  91575. if (!this._canBeMerged(otherMesh)) {
  91576. continue;
  91577. }
  91578. if (otherMesh.material !== current.material) {
  91579. continue;
  91580. }
  91581. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91582. continue;
  91583. }
  91584. currentPool.push(otherMesh);
  91585. globalLength--;
  91586. globalPool.splice(subIndex, 1);
  91587. subIndex--;
  91588. }
  91589. if (currentPool.length < 2) {
  91590. continue;
  91591. }
  91592. // Merge meshes
  91593. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91594. }
  91595. if (updateSelectionTree != undefined) {
  91596. if (updateSelectionTree) {
  91597. scene.createOrUpdateSelectionOctree();
  91598. }
  91599. }
  91600. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91601. scene.createOrUpdateSelectionOctree();
  91602. }
  91603. return true;
  91604. };
  91605. ;
  91606. MergeMeshesOptimization._UpdateSelectionTree = false;
  91607. return MergeMeshesOptimization;
  91608. }(SceneOptimization));
  91609. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91610. /**
  91611. * Defines a list of options used by SceneOptimizer
  91612. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91613. */
  91614. var SceneOptimizerOptions = /** @class */ (function () {
  91615. /**
  91616. * Creates a new list of options used by SceneOptimizer
  91617. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91618. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91619. */
  91620. function SceneOptimizerOptions(
  91621. /**
  91622. * Defines the target frame rate to reach (60 by default)
  91623. */
  91624. targetFrameRate,
  91625. /**
  91626. * Defines the interval between two checkes (2000ms by default)
  91627. */
  91628. trackerDuration) {
  91629. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91630. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91631. this.targetFrameRate = targetFrameRate;
  91632. this.trackerDuration = trackerDuration;
  91633. /**
  91634. * Gets the list of optimizations to apply
  91635. */
  91636. this.optimizations = new Array();
  91637. }
  91638. /**
  91639. * Add a new optimization
  91640. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91641. * @returns the current SceneOptimizerOptions
  91642. */
  91643. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91644. this.optimizations.push(optimization);
  91645. return this;
  91646. };
  91647. /**
  91648. * Add a new custom optimization
  91649. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91650. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91651. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91652. * @returns the current SceneOptimizerOptions
  91653. */
  91654. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91655. if (priority === void 0) { priority = 0; }
  91656. var optimization = new CustomOptimization(priority);
  91657. optimization.onApply = onApply;
  91658. optimization.onGetDescription = onGetDescription;
  91659. this.optimizations.push(optimization);
  91660. return this;
  91661. };
  91662. /**
  91663. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91664. * @param targetFrameRate defines the target frame rate (60 by default)
  91665. * @returns a SceneOptimizerOptions object
  91666. */
  91667. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91668. var result = new SceneOptimizerOptions(targetFrameRate);
  91669. var priority = 0;
  91670. result.addOptimization(new MergeMeshesOptimization(priority));
  91671. result.addOptimization(new ShadowsOptimization(priority));
  91672. result.addOptimization(new LensFlaresOptimization(priority));
  91673. // Next priority
  91674. priority++;
  91675. result.addOptimization(new PostProcessesOptimization(priority));
  91676. result.addOptimization(new ParticlesOptimization(priority));
  91677. // Next priority
  91678. priority++;
  91679. result.addOptimization(new TextureOptimization(priority, 1024));
  91680. return result;
  91681. };
  91682. /**
  91683. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91684. * @param targetFrameRate defines the target frame rate (60 by default)
  91685. * @returns a SceneOptimizerOptions object
  91686. */
  91687. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91688. var result = new SceneOptimizerOptions(targetFrameRate);
  91689. var priority = 0;
  91690. result.addOptimization(new MergeMeshesOptimization(priority));
  91691. result.addOptimization(new ShadowsOptimization(priority));
  91692. result.addOptimization(new LensFlaresOptimization(priority));
  91693. // Next priority
  91694. priority++;
  91695. result.addOptimization(new PostProcessesOptimization(priority));
  91696. result.addOptimization(new ParticlesOptimization(priority));
  91697. // Next priority
  91698. priority++;
  91699. result.addOptimization(new TextureOptimization(priority, 512));
  91700. // Next priority
  91701. priority++;
  91702. result.addOptimization(new RenderTargetsOptimization(priority));
  91703. // Next priority
  91704. priority++;
  91705. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91706. return result;
  91707. };
  91708. /**
  91709. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91710. * @param targetFrameRate defines the target frame rate (60 by default)
  91711. * @returns a SceneOptimizerOptions object
  91712. */
  91713. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91714. var result = new SceneOptimizerOptions(targetFrameRate);
  91715. var priority = 0;
  91716. result.addOptimization(new MergeMeshesOptimization(priority));
  91717. result.addOptimization(new ShadowsOptimization(priority));
  91718. result.addOptimization(new LensFlaresOptimization(priority));
  91719. // Next priority
  91720. priority++;
  91721. result.addOptimization(new PostProcessesOptimization(priority));
  91722. result.addOptimization(new ParticlesOptimization(priority));
  91723. // Next priority
  91724. priority++;
  91725. result.addOptimization(new TextureOptimization(priority, 256));
  91726. // Next priority
  91727. priority++;
  91728. result.addOptimization(new RenderTargetsOptimization(priority));
  91729. // Next priority
  91730. priority++;
  91731. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91732. return result;
  91733. };
  91734. return SceneOptimizerOptions;
  91735. }());
  91736. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91737. /**
  91738. * Class used to run optimizations in order to reach a target frame rate
  91739. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91740. */
  91741. var SceneOptimizer = /** @class */ (function () {
  91742. /**
  91743. * Creates a new SceneOptimizer
  91744. * @param scene defines the scene to work on
  91745. * @param options defines the options to use with the SceneOptimizer
  91746. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91747. * @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)
  91748. */
  91749. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91750. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91751. if (improvementMode === void 0) { improvementMode = false; }
  91752. var _this = this;
  91753. this._isRunning = false;
  91754. this._currentPriorityLevel = 0;
  91755. this._targetFrameRate = 60;
  91756. this._trackerDuration = 2000;
  91757. this._currentFrameRate = 0;
  91758. this._improvementMode = false;
  91759. /**
  91760. * Defines an observable called when the optimizer reaches the target frame rate
  91761. */
  91762. this.onSuccessObservable = new BABYLON.Observable();
  91763. /**
  91764. * Defines an observable called when the optimizer enables an optimization
  91765. */
  91766. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91767. /**
  91768. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91769. */
  91770. this.onFailureObservable = new BABYLON.Observable();
  91771. if (!options) {
  91772. this._options = new SceneOptimizerOptions();
  91773. }
  91774. else {
  91775. this._options = options;
  91776. }
  91777. if (this._options.targetFrameRate) {
  91778. this._targetFrameRate = this._options.targetFrameRate;
  91779. }
  91780. if (this._options.trackerDuration) {
  91781. this._trackerDuration = this._options.trackerDuration;
  91782. }
  91783. if (autoGeneratePriorities) {
  91784. var priority = 0;
  91785. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91786. var optim = _a[_i];
  91787. optim.priority = priority++;
  91788. }
  91789. }
  91790. this._improvementMode = improvementMode;
  91791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91792. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91793. _this._sceneDisposeObserver = null;
  91794. _this.dispose();
  91795. });
  91796. }
  91797. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91798. /**
  91799. * Gets a boolean indicating if the optimizer is in improvement mode
  91800. */
  91801. get: function () {
  91802. return this._improvementMode;
  91803. },
  91804. enumerable: true,
  91805. configurable: true
  91806. });
  91807. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91808. /**
  91809. * Gets the current priority level (0 at start)
  91810. */
  91811. get: function () {
  91812. return this._currentPriorityLevel;
  91813. },
  91814. enumerable: true,
  91815. configurable: true
  91816. });
  91817. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91818. /**
  91819. * Gets the current frame rate checked by the SceneOptimizer
  91820. */
  91821. get: function () {
  91822. return this._currentFrameRate;
  91823. },
  91824. enumerable: true,
  91825. configurable: true
  91826. });
  91827. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91828. /**
  91829. * Gets or sets the current target frame rate (60 by default)
  91830. */
  91831. get: function () {
  91832. return this._targetFrameRate;
  91833. },
  91834. /**
  91835. * Gets or sets the current target frame rate (60 by default)
  91836. */
  91837. set: function (value) {
  91838. this._targetFrameRate = value;
  91839. },
  91840. enumerable: true,
  91841. configurable: true
  91842. });
  91843. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91844. /**
  91845. * Gets or sets the current interval between two checks (every 2000ms by default)
  91846. */
  91847. get: function () {
  91848. return this._trackerDuration;
  91849. },
  91850. /**
  91851. * Gets or sets the current interval between two checks (every 2000ms by default)
  91852. */
  91853. set: function (value) {
  91854. this._trackerDuration = value;
  91855. },
  91856. enumerable: true,
  91857. configurable: true
  91858. });
  91859. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91860. /**
  91861. * Gets the list of active optimizations
  91862. */
  91863. get: function () {
  91864. return this._options.optimizations;
  91865. },
  91866. enumerable: true,
  91867. configurable: true
  91868. });
  91869. /**
  91870. * Stops the current optimizer
  91871. */
  91872. SceneOptimizer.prototype.stop = function () {
  91873. this._isRunning = false;
  91874. };
  91875. /**
  91876. * Reset the optimizer to initial step (current priority level = 0)
  91877. */
  91878. SceneOptimizer.prototype.reset = function () {
  91879. this._currentPriorityLevel = 0;
  91880. };
  91881. /**
  91882. * Start the optimizer. By default it will try to reach a specific framerate
  91883. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91884. */
  91885. SceneOptimizer.prototype.start = function () {
  91886. var _this = this;
  91887. if (this._isRunning) {
  91888. return;
  91889. }
  91890. this._isRunning = true;
  91891. // Let's wait for the scene to be ready before running our check
  91892. this._scene.executeWhenReady(function () {
  91893. setTimeout(function () {
  91894. _this._checkCurrentState();
  91895. }, _this._trackerDuration);
  91896. });
  91897. };
  91898. SceneOptimizer.prototype._checkCurrentState = function () {
  91899. var _this = this;
  91900. if (!this._isRunning) {
  91901. return;
  91902. }
  91903. var scene = this._scene;
  91904. var options = this._options;
  91905. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91906. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91907. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91908. this._isRunning = false;
  91909. this.onSuccessObservable.notifyObservers(this);
  91910. return;
  91911. }
  91912. // Apply current level of optimizations
  91913. var allDone = true;
  91914. var noOptimizationApplied = true;
  91915. for (var index = 0; index < options.optimizations.length; index++) {
  91916. var optimization = options.optimizations[index];
  91917. if (optimization.priority === this._currentPriorityLevel) {
  91918. noOptimizationApplied = false;
  91919. allDone = allDone && optimization.apply(scene, this);
  91920. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91921. }
  91922. }
  91923. // If no optimization was applied, this is a failure :(
  91924. if (noOptimizationApplied) {
  91925. this._isRunning = false;
  91926. this.onFailureObservable.notifyObservers(this);
  91927. return;
  91928. }
  91929. // If all optimizations were done, move to next level
  91930. if (allDone) {
  91931. this._currentPriorityLevel++;
  91932. }
  91933. // Let's the system running for a specific amount of time before checking FPS
  91934. scene.executeWhenReady(function () {
  91935. setTimeout(function () {
  91936. _this._checkCurrentState();
  91937. }, _this._trackerDuration);
  91938. });
  91939. };
  91940. /**
  91941. * Release all resources
  91942. */
  91943. SceneOptimizer.prototype.dispose = function () {
  91944. this.stop();
  91945. this.onSuccessObservable.clear();
  91946. this.onFailureObservable.clear();
  91947. this.onNewOptimizationAppliedObservable.clear();
  91948. if (this._sceneDisposeObserver) {
  91949. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91950. }
  91951. };
  91952. /**
  91953. * Helper function to create a SceneOptimizer with one single line of code
  91954. * @param scene defines the scene to work on
  91955. * @param options defines the options to use with the SceneOptimizer
  91956. * @param onSuccess defines a callback to call on success
  91957. * @param onFailure defines a callback to call on failure
  91958. * @returns the new SceneOptimizer object
  91959. */
  91960. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91961. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91962. if (onSuccess) {
  91963. optimizer.onSuccessObservable.add(function () {
  91964. onSuccess();
  91965. });
  91966. }
  91967. if (onFailure) {
  91968. optimizer.onFailureObservable.add(function () {
  91969. onFailure();
  91970. });
  91971. }
  91972. optimizer.start();
  91973. return optimizer;
  91974. };
  91975. return SceneOptimizer;
  91976. }());
  91977. BABYLON.SceneOptimizer = SceneOptimizer;
  91978. })(BABYLON || (BABYLON = {}));
  91979. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91980. var BABYLON;
  91981. (function (BABYLON) {
  91982. var OutlineRenderer = /** @class */ (function () {
  91983. function OutlineRenderer(scene) {
  91984. this.zOffset = 1;
  91985. this._scene = scene;
  91986. }
  91987. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91988. var _this = this;
  91989. if (useOverlay === void 0) { useOverlay = false; }
  91990. var scene = this._scene;
  91991. var engine = this._scene.getEngine();
  91992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91993. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91994. return;
  91995. }
  91996. var mesh = subMesh.getRenderingMesh();
  91997. var material = subMesh.getMaterial();
  91998. if (!material || !scene.activeCamera) {
  91999. return;
  92000. }
  92001. engine.enableEffect(this._effect);
  92002. // Logarithmic depth
  92003. if (material.useLogarithmicDepth) {
  92004. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  92005. }
  92006. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  92007. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  92008. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  92009. // Bones
  92010. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92011. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92012. }
  92013. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  92014. // Alpha test
  92015. if (material && material.needAlphaTesting()) {
  92016. var alphaTexture = material.getAlphaTestTexture();
  92017. if (alphaTexture) {
  92018. this._effect.setTexture("diffuseSampler", alphaTexture);
  92019. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  92020. }
  92021. }
  92022. engine.setZOffset(-this.zOffset);
  92023. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  92024. engine.setZOffset(0);
  92025. };
  92026. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  92027. var defines = [];
  92028. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  92029. var mesh = subMesh.getMesh();
  92030. var material = subMesh.getMaterial();
  92031. if (material) {
  92032. // Alpha test
  92033. if (material.needAlphaTesting()) {
  92034. defines.push("#define ALPHATEST");
  92035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92036. attribs.push(BABYLON.VertexBuffer.UVKind);
  92037. defines.push("#define UV1");
  92038. }
  92039. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  92040. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92041. defines.push("#define UV2");
  92042. }
  92043. }
  92044. //Logarithmic depth
  92045. if (material.useLogarithmicDepth) {
  92046. defines.push("#define LOGARITHMICDEPTH");
  92047. }
  92048. }
  92049. // Bones
  92050. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92051. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92052. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92053. if (mesh.numBoneInfluencers > 4) {
  92054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92056. }
  92057. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92058. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  92059. }
  92060. else {
  92061. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92062. }
  92063. // Instances
  92064. if (useInstances) {
  92065. defines.push("#define INSTANCES");
  92066. attribs.push("world0");
  92067. attribs.push("world1");
  92068. attribs.push("world2");
  92069. attribs.push("world3");
  92070. }
  92071. // Get correct effect
  92072. var join = defines.join("\n");
  92073. if (this._cachedDefines !== join) {
  92074. this._cachedDefines = join;
  92075. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  92076. }
  92077. return this._effect.isReady();
  92078. };
  92079. return OutlineRenderer;
  92080. }());
  92081. BABYLON.OutlineRenderer = OutlineRenderer;
  92082. })(BABYLON || (BABYLON = {}));
  92083. //# sourceMappingURL=babylon.outlineRenderer.js.map
  92084. var BABYLON;
  92085. (function (BABYLON) {
  92086. var FaceAdjacencies = /** @class */ (function () {
  92087. function FaceAdjacencies() {
  92088. this.edges = new Array();
  92089. this.edgesConnectedCount = 0;
  92090. }
  92091. return FaceAdjacencies;
  92092. }());
  92093. var EdgesRenderer = /** @class */ (function () {
  92094. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  92095. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  92096. if (epsilon === void 0) { epsilon = 0.95; }
  92097. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  92098. this.edgesWidthScalerForOrthographic = 1000.0;
  92099. this.edgesWidthScalerForPerspective = 50.0;
  92100. this._linesPositions = new Array();
  92101. this._linesNormals = new Array();
  92102. this._linesIndices = new Array();
  92103. this._buffers = {};
  92104. this._checkVerticesInsteadOfIndices = false;
  92105. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  92106. this.isEnabled = true;
  92107. this._source = source;
  92108. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  92109. this._epsilon = epsilon;
  92110. this._prepareRessources();
  92111. this._generateEdgesLines();
  92112. }
  92113. EdgesRenderer.prototype._prepareRessources = function () {
  92114. if (this._lineShader) {
  92115. return;
  92116. }
  92117. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  92118. attributes: ["position", "normal"],
  92119. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  92120. });
  92121. this._lineShader.disableDepthWrite = true;
  92122. this._lineShader.backFaceCulling = false;
  92123. };
  92124. EdgesRenderer.prototype._rebuild = function () {
  92125. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  92126. if (buffer) {
  92127. buffer._rebuild();
  92128. }
  92129. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  92130. if (buffer) {
  92131. buffer._rebuild();
  92132. }
  92133. var scene = this._source.getScene();
  92134. var engine = scene.getEngine();
  92135. this._ib = engine.createIndexBuffer(this._linesIndices);
  92136. };
  92137. EdgesRenderer.prototype.dispose = function () {
  92138. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  92139. if (buffer) {
  92140. buffer.dispose();
  92141. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  92142. }
  92143. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  92144. if (buffer) {
  92145. buffer.dispose();
  92146. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  92147. }
  92148. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  92149. this._lineShader.dispose();
  92150. };
  92151. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  92152. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  92153. return 0;
  92154. }
  92155. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  92156. return 1;
  92157. }
  92158. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  92159. return 2;
  92160. }
  92161. return -1;
  92162. };
  92163. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  92164. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  92165. return 0;
  92166. }
  92167. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  92168. return 1;
  92169. }
  92170. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  92171. return 2;
  92172. }
  92173. return -1;
  92174. };
  92175. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  92176. var needToCreateLine;
  92177. if (edge === undefined) {
  92178. needToCreateLine = true;
  92179. }
  92180. else {
  92181. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  92182. needToCreateLine = dotProduct < this._epsilon;
  92183. }
  92184. if (needToCreateLine) {
  92185. var offset = this._linesPositions.length / 3;
  92186. var normal = p0.subtract(p1);
  92187. normal.normalize();
  92188. // Positions
  92189. this._linesPositions.push(p0.x);
  92190. this._linesPositions.push(p0.y);
  92191. this._linesPositions.push(p0.z);
  92192. this._linesPositions.push(p0.x);
  92193. this._linesPositions.push(p0.y);
  92194. this._linesPositions.push(p0.z);
  92195. this._linesPositions.push(p1.x);
  92196. this._linesPositions.push(p1.y);
  92197. this._linesPositions.push(p1.z);
  92198. this._linesPositions.push(p1.x);
  92199. this._linesPositions.push(p1.y);
  92200. this._linesPositions.push(p1.z);
  92201. // Normals
  92202. this._linesNormals.push(p1.x);
  92203. this._linesNormals.push(p1.y);
  92204. this._linesNormals.push(p1.z);
  92205. this._linesNormals.push(-1);
  92206. this._linesNormals.push(p1.x);
  92207. this._linesNormals.push(p1.y);
  92208. this._linesNormals.push(p1.z);
  92209. this._linesNormals.push(1);
  92210. this._linesNormals.push(p0.x);
  92211. this._linesNormals.push(p0.y);
  92212. this._linesNormals.push(p0.z);
  92213. this._linesNormals.push(-1);
  92214. this._linesNormals.push(p0.x);
  92215. this._linesNormals.push(p0.y);
  92216. this._linesNormals.push(p0.z);
  92217. this._linesNormals.push(1);
  92218. // Indices
  92219. this._linesIndices.push(offset);
  92220. this._linesIndices.push(offset + 1);
  92221. this._linesIndices.push(offset + 2);
  92222. this._linesIndices.push(offset);
  92223. this._linesIndices.push(offset + 2);
  92224. this._linesIndices.push(offset + 3);
  92225. }
  92226. };
  92227. EdgesRenderer.prototype._generateEdgesLines = function () {
  92228. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92229. var indices = this._source.getIndices();
  92230. if (!indices || !positions) {
  92231. return;
  92232. }
  92233. // First let's find adjacencies
  92234. var adjacencies = new Array();
  92235. var faceNormals = new Array();
  92236. var index;
  92237. var faceAdjacencies;
  92238. // Prepare faces
  92239. for (index = 0; index < indices.length; index += 3) {
  92240. faceAdjacencies = new FaceAdjacencies();
  92241. var p0Index = indices[index];
  92242. var p1Index = indices[index + 1];
  92243. var p2Index = indices[index + 2];
  92244. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  92245. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  92246. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  92247. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  92248. faceNormal.normalize();
  92249. faceNormals.push(faceNormal);
  92250. adjacencies.push(faceAdjacencies);
  92251. }
  92252. // Scan
  92253. for (index = 0; index < adjacencies.length; index++) {
  92254. faceAdjacencies = adjacencies[index];
  92255. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  92256. var otherFaceAdjacencies = adjacencies[otherIndex];
  92257. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  92258. break;
  92259. }
  92260. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  92261. continue;
  92262. }
  92263. var otherP0 = indices[otherIndex * 3];
  92264. var otherP1 = indices[otherIndex * 3 + 1];
  92265. var otherP2 = indices[otherIndex * 3 + 2];
  92266. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  92267. var otherEdgeIndex = 0;
  92268. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  92269. continue;
  92270. }
  92271. switch (edgeIndex) {
  92272. case 0:
  92273. if (this._checkVerticesInsteadOfIndices) {
  92274. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92275. }
  92276. else {
  92277. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  92278. }
  92279. break;
  92280. case 1:
  92281. if (this._checkVerticesInsteadOfIndices) {
  92282. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92283. }
  92284. else {
  92285. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  92286. }
  92287. break;
  92288. case 2:
  92289. if (this._checkVerticesInsteadOfIndices) {
  92290. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92291. }
  92292. else {
  92293. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  92294. }
  92295. break;
  92296. }
  92297. if (otherEdgeIndex === -1) {
  92298. continue;
  92299. }
  92300. faceAdjacencies.edges[edgeIndex] = otherIndex;
  92301. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  92302. faceAdjacencies.edgesConnectedCount++;
  92303. otherFaceAdjacencies.edgesConnectedCount++;
  92304. if (faceAdjacencies.edgesConnectedCount === 3) {
  92305. break;
  92306. }
  92307. }
  92308. }
  92309. }
  92310. // Create lines
  92311. for (index = 0; index < adjacencies.length; index++) {
  92312. // 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
  92313. var current = adjacencies[index];
  92314. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  92315. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  92316. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  92317. }
  92318. // Merge into a single mesh
  92319. var engine = this._source.getScene().getEngine();
  92320. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  92321. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  92322. this._ib = engine.createIndexBuffer(this._linesIndices);
  92323. this._indicesCount = this._linesIndices.length;
  92324. };
  92325. EdgesRenderer.prototype.render = function () {
  92326. var scene = this._source.getScene();
  92327. if (!this._lineShader.isReady() || !scene.activeCamera) {
  92328. return;
  92329. }
  92330. var engine = scene.getEngine();
  92331. this._lineShader._preBind();
  92332. // VBOs
  92333. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  92334. scene.resetCachedMaterial();
  92335. this._lineShader.setColor4("color", this._source.edgesColor);
  92336. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  92337. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  92338. }
  92339. else {
  92340. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  92341. }
  92342. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  92343. this._lineShader.bind(this._source.getWorldMatrix());
  92344. // Draw order
  92345. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  92346. this._lineShader.unbind();
  92347. engine.setDepthWrite(true);
  92348. };
  92349. return EdgesRenderer;
  92350. }());
  92351. BABYLON.EdgesRenderer = EdgesRenderer;
  92352. })(BABYLON || (BABYLON = {}));
  92353. //# sourceMappingURL=babylon.edgesRenderer.js.map
  92354. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92355. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92356. s = arguments[i];
  92357. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92358. t[p] = s[p];
  92359. }
  92360. return t;
  92361. };
  92362. var BABYLON;
  92363. (function (BABYLON) {
  92364. /**
  92365. * The effect layer Helps adding post process effect blended with the main pass.
  92366. *
  92367. * This can be for instance use to generate glow or higlight effects on the scene.
  92368. *
  92369. * The effect layer class can not be used directly and is intented to inherited from to be
  92370. * customized per effects.
  92371. */
  92372. var EffectLayer = /** @class */ (function () {
  92373. /**
  92374. * Instantiates a new effect Layer and references it in the scene.
  92375. * @param name The name of the layer
  92376. * @param scene The scene to use the layer in
  92377. */
  92378. function EffectLayer(
  92379. /** The Friendly of the effect in the scene */
  92380. name, scene) {
  92381. this._vertexBuffers = {};
  92382. this._maxSize = 0;
  92383. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92384. this._shouldRender = true;
  92385. this._postProcesses = [];
  92386. this._textures = [];
  92387. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92388. /**
  92389. * The clear color of the texture used to generate the glow map.
  92390. */
  92391. this.neutralColor = new BABYLON.Color4();
  92392. /**
  92393. * Specifies wether the highlight layer is enabled or not.
  92394. */
  92395. this.isEnabled = true;
  92396. /**
  92397. * An event triggered when the effect layer has been disposed.
  92398. */
  92399. this.onDisposeObservable = new BABYLON.Observable();
  92400. /**
  92401. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92402. */
  92403. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92404. /**
  92405. * An event triggered when the generated texture is being merged in the scene.
  92406. */
  92407. this.onBeforeComposeObservable = new BABYLON.Observable();
  92408. /**
  92409. * An event triggered when the generated texture has been merged in the scene.
  92410. */
  92411. this.onAfterComposeObservable = new BABYLON.Observable();
  92412. /**
  92413. * An event triggered when the efffect layer changes its size.
  92414. */
  92415. this.onSizeChangedObservable = new BABYLON.Observable();
  92416. this.name = name;
  92417. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92418. this._engine = scene.getEngine();
  92419. this._maxSize = this._engine.getCaps().maxTextureSize;
  92420. this._scene.effectLayers.push(this);
  92421. // Generate Buffers
  92422. this._generateIndexBuffer();
  92423. this._genrateVertexBuffer();
  92424. }
  92425. Object.defineProperty(EffectLayer.prototype, "camera", {
  92426. /**
  92427. * Gets the camera attached to the layer.
  92428. */
  92429. get: function () {
  92430. return this._effectLayerOptions.camera;
  92431. },
  92432. enumerable: true,
  92433. configurable: true
  92434. });
  92435. /**
  92436. * Initializes the effect layer with the required options.
  92437. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92438. */
  92439. EffectLayer.prototype._init = function (options) {
  92440. // Adapt options
  92441. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92442. this._setMainTextureSize();
  92443. this._createMainTexture();
  92444. this._createTextureAndPostProcesses();
  92445. this._mergeEffect = this._createMergeEffect();
  92446. };
  92447. /**
  92448. * Generates the index buffer of the full screen quad blending to the main canvas.
  92449. */
  92450. EffectLayer.prototype._generateIndexBuffer = function () {
  92451. // Indices
  92452. var indices = [];
  92453. indices.push(0);
  92454. indices.push(1);
  92455. indices.push(2);
  92456. indices.push(0);
  92457. indices.push(2);
  92458. indices.push(3);
  92459. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92460. };
  92461. /**
  92462. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92463. */
  92464. EffectLayer.prototype._genrateVertexBuffer = function () {
  92465. // VBO
  92466. var vertices = [];
  92467. vertices.push(1, 1);
  92468. vertices.push(-1, 1);
  92469. vertices.push(-1, -1);
  92470. vertices.push(1, -1);
  92471. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92473. };
  92474. /**
  92475. * Sets the main texture desired size which is the closest power of two
  92476. * of the engine canvas size.
  92477. */
  92478. EffectLayer.prototype._setMainTextureSize = function () {
  92479. if (this._effectLayerOptions.mainTextureFixedSize) {
  92480. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92481. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92482. }
  92483. else {
  92484. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92485. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92486. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92487. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92488. }
  92489. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92490. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92491. };
  92492. /**
  92493. * Creates the main texture for the effect layer.
  92494. */
  92495. EffectLayer.prototype._createMainTexture = function () {
  92496. var _this = this;
  92497. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92498. width: this._mainTextureDesiredSize.width,
  92499. height: this._mainTextureDesiredSize.height
  92500. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92501. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92502. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92503. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92504. this._mainTexture.anisotropicFilteringLevel = 1;
  92505. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92506. this._mainTexture.renderParticles = false;
  92507. this._mainTexture.renderList = null;
  92508. this._mainTexture.ignoreCameraViewport = true;
  92509. // Custom render function
  92510. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92511. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92512. var index;
  92513. var engine = _this._scene.getEngine();
  92514. if (depthOnlySubMeshes.length) {
  92515. engine.setColorWrite(false);
  92516. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92517. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92518. }
  92519. engine.setColorWrite(true);
  92520. }
  92521. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92522. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92523. }
  92524. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92525. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92526. }
  92527. for (index = 0; index < transparentSubMeshes.length; index++) {
  92528. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92529. }
  92530. };
  92531. this._mainTexture.onClearObservable.add(function (engine) {
  92532. engine.clear(_this.neutralColor, true, true, true);
  92533. });
  92534. };
  92535. /**
  92536. * Checks for the readiness of the element composing the layer.
  92537. * @param subMesh the mesh to check for
  92538. * @param useInstances specify wether or not to use instances to render the mesh
  92539. * @param emissiveTexture the associated emissive texture used to generate the glow
  92540. * @return true if ready otherwise, false
  92541. */
  92542. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92543. var material = subMesh.getMaterial();
  92544. if (!material) {
  92545. return false;
  92546. }
  92547. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92548. return false;
  92549. }
  92550. var defines = [];
  92551. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92552. var mesh = subMesh.getMesh();
  92553. var uv1 = false;
  92554. var uv2 = false;
  92555. // Alpha test
  92556. if (material && material.needAlphaTesting()) {
  92557. var alphaTexture = material.getAlphaTestTexture();
  92558. if (alphaTexture) {
  92559. defines.push("#define ALPHATEST");
  92560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92561. alphaTexture.coordinatesIndex === 1) {
  92562. defines.push("#define DIFFUSEUV2");
  92563. uv2 = true;
  92564. }
  92565. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92566. defines.push("#define DIFFUSEUV1");
  92567. uv1 = true;
  92568. }
  92569. }
  92570. }
  92571. // Emissive
  92572. if (emissiveTexture) {
  92573. defines.push("#define EMISSIVE");
  92574. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92575. emissiveTexture.coordinatesIndex === 1) {
  92576. defines.push("#define EMISSIVEUV2");
  92577. uv2 = true;
  92578. }
  92579. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92580. defines.push("#define EMISSIVEUV1");
  92581. uv1 = true;
  92582. }
  92583. }
  92584. if (uv1) {
  92585. attribs.push(BABYLON.VertexBuffer.UVKind);
  92586. defines.push("#define UV1");
  92587. }
  92588. if (uv2) {
  92589. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92590. defines.push("#define UV2");
  92591. }
  92592. // Bones
  92593. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92594. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92595. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92596. if (mesh.numBoneInfluencers > 4) {
  92597. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92598. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92599. }
  92600. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92601. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92602. }
  92603. else {
  92604. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92605. }
  92606. // Morph targets
  92607. var manager = mesh.morphTargetManager;
  92608. var morphInfluencers = 0;
  92609. if (manager) {
  92610. if (manager.numInfluencers > 0) {
  92611. defines.push("#define MORPHTARGETS");
  92612. morphInfluencers = manager.numInfluencers;
  92613. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92614. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92615. }
  92616. }
  92617. // Instances
  92618. if (useInstances) {
  92619. defines.push("#define INSTANCES");
  92620. attribs.push("world0");
  92621. attribs.push("world1");
  92622. attribs.push("world2");
  92623. attribs.push("world3");
  92624. }
  92625. // Get correct effect
  92626. var join = defines.join("\n");
  92627. if (this._cachedDefines !== join) {
  92628. this._cachedDefines = join;
  92629. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92630. }
  92631. return this._effectLayerMapGenerationEffect.isReady();
  92632. };
  92633. /**
  92634. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92635. */
  92636. EffectLayer.prototype.render = function () {
  92637. var currentEffect = this._mergeEffect;
  92638. // Check
  92639. if (!currentEffect.isReady())
  92640. return;
  92641. for (var i = 0; i < this._postProcesses.length; i++) {
  92642. if (!this._postProcesses[i].isReady()) {
  92643. return;
  92644. }
  92645. }
  92646. var engine = this._scene.getEngine();
  92647. this.onBeforeComposeObservable.notifyObservers(this);
  92648. // Render
  92649. engine.enableEffect(currentEffect);
  92650. engine.setState(false);
  92651. // VBOs
  92652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92653. // Cache
  92654. var previousAlphaMode = engine.getAlphaMode();
  92655. // Go Blend.
  92656. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92657. // Blends the map on the main canvas.
  92658. this._internalRender(currentEffect);
  92659. // Restore Alpha
  92660. engine.setAlphaMode(previousAlphaMode);
  92661. this.onAfterComposeObservable.notifyObservers(this);
  92662. // Handle size changes.
  92663. var size = this._mainTexture.getSize();
  92664. this._setMainTextureSize();
  92665. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92666. // Recreate RTT and post processes on size change.
  92667. this.onSizeChangedObservable.notifyObservers(this);
  92668. this._disposeTextureAndPostProcesses();
  92669. this._createMainTexture();
  92670. this._createTextureAndPostProcesses();
  92671. }
  92672. };
  92673. /**
  92674. * Determine if a given mesh will be used in the current effect.
  92675. * @param mesh mesh to test
  92676. * @returns true if the mesh will be used
  92677. */
  92678. EffectLayer.prototype.hasMesh = function (mesh) {
  92679. return true;
  92680. };
  92681. /**
  92682. * Returns true if the layer contains information to display, otherwise false.
  92683. * @returns true if the glow layer should be rendered
  92684. */
  92685. EffectLayer.prototype.shouldRender = function () {
  92686. return this.isEnabled && this._shouldRender;
  92687. };
  92688. /**
  92689. * Returns true if the mesh should render, otherwise false.
  92690. * @param mesh The mesh to render
  92691. * @returns true if it should render otherwise false
  92692. */
  92693. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92694. return true;
  92695. };
  92696. /**
  92697. * Returns true if the mesh should render, otherwise false.
  92698. * @param mesh The mesh to render
  92699. * @returns true if it should render otherwise false
  92700. */
  92701. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92702. return true;
  92703. };
  92704. /**
  92705. * Renders the submesh passed in parameter to the generation map.
  92706. */
  92707. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92708. var _this = this;
  92709. if (!this.shouldRender()) {
  92710. return;
  92711. }
  92712. var material = subMesh.getMaterial();
  92713. var mesh = subMesh.getRenderingMesh();
  92714. var scene = this._scene;
  92715. var engine = scene.getEngine();
  92716. if (!material) {
  92717. return;
  92718. }
  92719. // Do not block in blend mode.
  92720. if (material.needAlphaBlendingForMesh(mesh)) {
  92721. return;
  92722. }
  92723. // Culling
  92724. engine.setState(material.backFaceCulling);
  92725. // Managing instances
  92726. var batch = mesh._getInstancesRenderList(subMesh._id);
  92727. if (batch.mustReturn) {
  92728. return;
  92729. }
  92730. // Early Exit per mesh
  92731. if (!this._shouldRenderMesh(mesh)) {
  92732. return;
  92733. }
  92734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92735. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92736. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92737. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92738. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92739. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92740. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92741. // Alpha test
  92742. if (material && material.needAlphaTesting()) {
  92743. var alphaTexture = material.getAlphaTestTexture();
  92744. if (alphaTexture) {
  92745. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92746. var textureMatrix = alphaTexture.getTextureMatrix();
  92747. if (textureMatrix) {
  92748. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92749. }
  92750. }
  92751. }
  92752. // Glow emissive only
  92753. if (this._emissiveTextureAndColor.texture) {
  92754. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92755. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92756. }
  92757. // Bones
  92758. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92759. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92760. }
  92761. // Morph targets
  92762. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92763. // Draw
  92764. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92765. }
  92766. else {
  92767. // Need to reset refresh rate of the shadowMap
  92768. this._mainTexture.resetRefreshCounter();
  92769. }
  92770. };
  92771. /**
  92772. * Rebuild the required buffers.
  92773. * @hidden Internal use only.
  92774. */
  92775. EffectLayer.prototype._rebuild = function () {
  92776. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92777. if (vb) {
  92778. vb._rebuild();
  92779. }
  92780. this._generateIndexBuffer();
  92781. };
  92782. /**
  92783. * Dispose only the render target textures and post process.
  92784. */
  92785. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92786. this._mainTexture.dispose();
  92787. for (var i = 0; i < this._postProcesses.length; i++) {
  92788. if (this._postProcesses[i]) {
  92789. this._postProcesses[i].dispose();
  92790. }
  92791. }
  92792. this._postProcesses = [];
  92793. for (var i = 0; i < this._textures.length; i++) {
  92794. if (this._textures[i]) {
  92795. this._textures[i].dispose();
  92796. }
  92797. }
  92798. this._textures = [];
  92799. };
  92800. /**
  92801. * Dispose the highlight layer and free resources.
  92802. */
  92803. EffectLayer.prototype.dispose = function () {
  92804. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92805. if (vertexBuffer) {
  92806. vertexBuffer.dispose();
  92807. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92808. }
  92809. if (this._indexBuffer) {
  92810. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92811. this._indexBuffer = null;
  92812. }
  92813. // Clean textures and post processes
  92814. this._disposeTextureAndPostProcesses();
  92815. // Remove from scene
  92816. var index = this._scene.effectLayers.indexOf(this, 0);
  92817. if (index > -1) {
  92818. this._scene.effectLayers.splice(index, 1);
  92819. }
  92820. // Callback
  92821. this.onDisposeObservable.notifyObservers(this);
  92822. this.onDisposeObservable.clear();
  92823. this.onBeforeRenderMainTextureObservable.clear();
  92824. this.onBeforeComposeObservable.clear();
  92825. this.onAfterComposeObservable.clear();
  92826. this.onSizeChangedObservable.clear();
  92827. };
  92828. /**
  92829. * Gets the class name of the effect layer
  92830. * @returns the string with the class name of the effect layer
  92831. */
  92832. EffectLayer.prototype.getClassName = function () {
  92833. return "EffectLayer";
  92834. };
  92835. /**
  92836. * Creates an effect layer from parsed effect layer data
  92837. * @param parsedEffectLayer defines effect layer data
  92838. * @param scene defines the current scene
  92839. * @param rootUrl defines the root URL containing the effect layer information
  92840. * @returns a parsed effect Layer
  92841. */
  92842. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92843. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92844. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92845. };
  92846. __decorate([
  92847. BABYLON.serialize()
  92848. ], EffectLayer.prototype, "name", void 0);
  92849. __decorate([
  92850. BABYLON.serializeAsColor4()
  92851. ], EffectLayer.prototype, "neutralColor", void 0);
  92852. __decorate([
  92853. BABYLON.serialize()
  92854. ], EffectLayer.prototype, "isEnabled", void 0);
  92855. __decorate([
  92856. BABYLON.serializeAsCameraReference()
  92857. ], EffectLayer.prototype, "camera", null);
  92858. return EffectLayer;
  92859. }());
  92860. BABYLON.EffectLayer = EffectLayer;
  92861. })(BABYLON || (BABYLON = {}));
  92862. //# sourceMappingURL=babylon.effectLayer.js.map
  92863. var BABYLON;
  92864. (function (BABYLON) {
  92865. /**
  92866. * Special Glow Blur post process only blurring the alpha channel
  92867. * It enforces keeping the most luminous color in the color channel.
  92868. */
  92869. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92870. __extends(GlowBlurPostProcess, _super);
  92871. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92873. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92874. _this.direction = direction;
  92875. _this.kernel = kernel;
  92876. _this.onApplyObservable.add(function (effect) {
  92877. effect.setFloat2("screenSize", _this.width, _this.height);
  92878. effect.setVector2("direction", _this.direction);
  92879. effect.setFloat("blurWidth", _this.kernel);
  92880. });
  92881. return _this;
  92882. }
  92883. return GlowBlurPostProcess;
  92884. }(BABYLON.PostProcess));
  92885. /**
  92886. * The highlight layer Helps adding a glow effect around a mesh.
  92887. *
  92888. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92889. * glowy meshes to your scene.
  92890. *
  92891. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92892. */
  92893. var HighlightLayer = /** @class */ (function (_super) {
  92894. __extends(HighlightLayer, _super);
  92895. /**
  92896. * Instantiates a new highlight Layer and references it to the scene..
  92897. * @param name The name of the layer
  92898. * @param scene The scene to use the layer in
  92899. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92900. */
  92901. function HighlightLayer(name, scene, options) {
  92902. var _this = _super.call(this, name, scene) || this;
  92903. _this.name = name;
  92904. /**
  92905. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92906. */
  92907. _this.innerGlow = true;
  92908. /**
  92909. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92910. */
  92911. _this.outerGlow = true;
  92912. /**
  92913. * An event triggered when the highlight layer is being blurred.
  92914. */
  92915. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92916. /**
  92917. * An event triggered when the highlight layer has been blurred.
  92918. */
  92919. _this.onAfterBlurObservable = new BABYLON.Observable();
  92920. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92921. _this._meshes = {};
  92922. _this._excludedMeshes = {};
  92923. _this.neutralColor = HighlightLayer.NeutralColor;
  92924. // Warn on stencil
  92925. if (!_this._engine.isStencilEnable) {
  92926. 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 }");
  92927. }
  92928. // Adapt options
  92929. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92930. // Initialize the layer
  92931. _this._init({
  92932. alphaBlendingMode: _this._options.alphaBlendingMode,
  92933. camera: _this._options.camera,
  92934. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92935. mainTextureRatio: _this._options.mainTextureRatio
  92936. });
  92937. // Do not render as long as no meshes have been added
  92938. _this._shouldRender = false;
  92939. return _this;
  92940. }
  92941. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92942. /**
  92943. * Gets the horizontal size of the blur.
  92944. */
  92945. get: function () {
  92946. return this._horizontalBlurPostprocess.kernel;
  92947. },
  92948. /**
  92949. * Specifies the horizontal size of the blur.
  92950. */
  92951. set: function (value) {
  92952. this._horizontalBlurPostprocess.kernel = value;
  92953. },
  92954. enumerable: true,
  92955. configurable: true
  92956. });
  92957. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92958. /**
  92959. * Gets the vertical size of the blur.
  92960. */
  92961. get: function () {
  92962. return this._verticalBlurPostprocess.kernel;
  92963. },
  92964. /**
  92965. * Specifies the vertical size of the blur.
  92966. */
  92967. set: function (value) {
  92968. this._verticalBlurPostprocess.kernel = value;
  92969. },
  92970. enumerable: true,
  92971. configurable: true
  92972. });
  92973. /**
  92974. * Get the effect name of the layer.
  92975. * @return The effect name
  92976. */
  92977. HighlightLayer.prototype.getEffectName = function () {
  92978. return HighlightLayer.EffectName;
  92979. };
  92980. /**
  92981. * Create the merge effect. This is the shader use to blit the information back
  92982. * to the main canvas at the end of the scene rendering.
  92983. */
  92984. HighlightLayer.prototype._createMergeEffect = function () {
  92985. // Effect
  92986. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92987. };
  92988. /**
  92989. * Creates the render target textures and post processes used in the highlight layer.
  92990. */
  92991. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92992. var _this = this;
  92993. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92994. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92995. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92996. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92997. var textureType = 0;
  92998. if (this._engine.getCaps().textureHalfFloatRender) {
  92999. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93000. }
  93001. else {
  93002. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93003. }
  93004. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  93005. width: blurTextureWidth,
  93006. height: blurTextureHeight
  93007. }, this._scene, false, true, textureType);
  93008. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93009. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93010. this._blurTexture.anisotropicFilteringLevel = 16;
  93011. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  93012. this._blurTexture.renderParticles = false;
  93013. this._blurTexture.ignoreCameraViewport = true;
  93014. this._textures = [this._blurTexture];
  93015. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  93016. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93017. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  93018. effect.setTexture("textureSampler", _this._mainTexture);
  93019. });
  93020. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93021. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  93022. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  93023. });
  93024. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93025. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  93026. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  93027. });
  93028. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  93029. }
  93030. else {
  93031. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  93032. width: blurTextureWidth,
  93033. height: blurTextureHeight
  93034. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93035. this._horizontalBlurPostprocess.width = blurTextureWidth;
  93036. this._horizontalBlurPostprocess.height = blurTextureHeight;
  93037. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  93038. effect.setTexture("textureSampler", _this._mainTexture);
  93039. });
  93040. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  93041. width: blurTextureWidth,
  93042. height: blurTextureHeight
  93043. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93044. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  93045. }
  93046. this._mainTexture.onAfterUnbindObservable.add(function () {
  93047. _this.onBeforeBlurObservable.notifyObservers(_this);
  93048. var internalTexture = _this._blurTexture.getInternalTexture();
  93049. if (internalTexture) {
  93050. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  93051. }
  93052. _this.onAfterBlurObservable.notifyObservers(_this);
  93053. });
  93054. // Prevent autoClear.
  93055. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93056. };
  93057. /**
  93058. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93059. */
  93060. HighlightLayer.prototype.needStencil = function () {
  93061. return true;
  93062. };
  93063. /**
  93064. * Checks for the readiness of the element composing the layer.
  93065. * @param subMesh the mesh to check for
  93066. * @param useInstances specify wether or not to use instances to render the mesh
  93067. * @param emissiveTexture the associated emissive texture used to generate the glow
  93068. * @return true if ready otherwise, false
  93069. */
  93070. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  93071. var material = subMesh.getMaterial();
  93072. var mesh = subMesh.getRenderingMesh();
  93073. if (!material || !mesh || !this._meshes) {
  93074. return false;
  93075. }
  93076. var emissiveTexture = null;
  93077. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  93078. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  93079. emissiveTexture = material.emissiveTexture;
  93080. }
  93081. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93082. };
  93083. /**
  93084. * Implementation specific of rendering the generating effect on the main canvas.
  93085. * @param effect The effect used to render through
  93086. */
  93087. HighlightLayer.prototype._internalRender = function (effect) {
  93088. // Texture
  93089. effect.setTexture("textureSampler", this._blurTexture);
  93090. // Cache
  93091. var engine = this._engine;
  93092. var previousStencilBuffer = engine.getStencilBuffer();
  93093. var previousStencilFunction = engine.getStencilFunction();
  93094. var previousStencilMask = engine.getStencilMask();
  93095. var previousStencilOperationPass = engine.getStencilOperationPass();
  93096. var previousStencilOperationFail = engine.getStencilOperationFail();
  93097. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  93098. var previousStencilReference = engine.getStencilFunctionReference();
  93099. // Stencil operations
  93100. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  93101. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  93102. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  93103. // Draw order
  93104. engine.setStencilMask(0x00);
  93105. engine.setStencilBuffer(true);
  93106. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  93107. // 2 passes inner outer
  93108. if (this.outerGlow) {
  93109. effect.setFloat("offset", 0);
  93110. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  93111. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93112. }
  93113. if (this.innerGlow) {
  93114. effect.setFloat("offset", 1);
  93115. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  93116. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93117. }
  93118. // Restore Cache
  93119. engine.setStencilFunction(previousStencilFunction);
  93120. engine.setStencilMask(previousStencilMask);
  93121. engine.setStencilBuffer(previousStencilBuffer);
  93122. engine.setStencilOperationPass(previousStencilOperationPass);
  93123. engine.setStencilOperationFail(previousStencilOperationFail);
  93124. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  93125. engine.setStencilFunctionReference(previousStencilReference);
  93126. };
  93127. /**
  93128. * Returns true if the layer contains information to display, otherwise false.
  93129. */
  93130. HighlightLayer.prototype.shouldRender = function () {
  93131. if (_super.prototype.shouldRender.call(this)) {
  93132. return this._meshes ? true : false;
  93133. }
  93134. return false;
  93135. };
  93136. /**
  93137. * Returns true if the mesh should render, otherwise false.
  93138. * @param mesh The mesh to render
  93139. * @returns true if it should render otherwise false
  93140. */
  93141. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  93142. // Excluded Mesh
  93143. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  93144. return false;
  93145. }
  93146. ;
  93147. return true;
  93148. };
  93149. /**
  93150. * Sets the required values for both the emissive texture and and the main color.
  93151. */
  93152. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93153. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  93154. if (highlightLayerMesh) {
  93155. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  93156. }
  93157. else {
  93158. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93159. }
  93160. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  93161. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93162. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  93163. }
  93164. else {
  93165. this._emissiveTextureAndColor.texture = null;
  93166. }
  93167. };
  93168. /**
  93169. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  93170. * @param mesh The mesh to exclude from the highlight layer
  93171. */
  93172. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  93173. if (!this._excludedMeshes) {
  93174. return;
  93175. }
  93176. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  93177. if (!meshExcluded) {
  93178. this._excludedMeshes[mesh.uniqueId] = {
  93179. mesh: mesh,
  93180. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  93181. mesh.getEngine().setStencilBuffer(false);
  93182. }),
  93183. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  93184. mesh.getEngine().setStencilBuffer(true);
  93185. }),
  93186. };
  93187. }
  93188. };
  93189. /**
  93190. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  93191. * @param mesh The mesh to highlight
  93192. */
  93193. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  93194. if (!this._excludedMeshes) {
  93195. return;
  93196. }
  93197. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  93198. if (meshExcluded) {
  93199. if (meshExcluded.beforeRender) {
  93200. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  93201. }
  93202. if (meshExcluded.afterRender) {
  93203. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  93204. }
  93205. }
  93206. this._excludedMeshes[mesh.uniqueId] = null;
  93207. };
  93208. /**
  93209. * Determine if a given mesh will be highlighted by the current HighlightLayer
  93210. * @param mesh mesh to test
  93211. * @returns true if the mesh will be highlighted by the current HighlightLayer
  93212. */
  93213. HighlightLayer.prototype.hasMesh = function (mesh) {
  93214. if (!this._meshes) {
  93215. return false;
  93216. }
  93217. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  93218. };
  93219. /**
  93220. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  93221. * @param mesh The mesh to highlight
  93222. * @param color The color of the highlight
  93223. * @param glowEmissiveOnly Extract the glow from the emissive texture
  93224. */
  93225. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  93226. var _this = this;
  93227. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  93228. if (!this._meshes) {
  93229. return;
  93230. }
  93231. var meshHighlight = this._meshes[mesh.uniqueId];
  93232. if (meshHighlight) {
  93233. meshHighlight.color = color;
  93234. }
  93235. else {
  93236. this._meshes[mesh.uniqueId] = {
  93237. mesh: mesh,
  93238. color: color,
  93239. // Lambda required for capture due to Observable this context
  93240. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  93241. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  93242. _this._defaultStencilReference(mesh);
  93243. }
  93244. else {
  93245. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  93246. }
  93247. }),
  93248. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  93249. glowEmissiveOnly: glowEmissiveOnly
  93250. };
  93251. }
  93252. this._shouldRender = true;
  93253. };
  93254. /**
  93255. * Remove a mesh from the highlight layer in order to make it stop glowing.
  93256. * @param mesh The mesh to highlight
  93257. */
  93258. HighlightLayer.prototype.removeMesh = function (mesh) {
  93259. if (!this._meshes) {
  93260. return;
  93261. }
  93262. var meshHighlight = this._meshes[mesh.uniqueId];
  93263. if (meshHighlight) {
  93264. if (meshHighlight.observerHighlight) {
  93265. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93266. }
  93267. if (meshHighlight.observerDefault) {
  93268. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93269. }
  93270. delete this._meshes[mesh.uniqueId];
  93271. }
  93272. this._shouldRender = false;
  93273. for (var meshHighlightToCheck in this._meshes) {
  93274. if (this._meshes[meshHighlightToCheck]) {
  93275. this._shouldRender = true;
  93276. break;
  93277. }
  93278. }
  93279. };
  93280. /**
  93281. * Force the stencil to the normal expected value for none glowing parts
  93282. */
  93283. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  93284. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  93285. };
  93286. /**
  93287. * Free any resources and references associated to a mesh.
  93288. * Internal use
  93289. * @param mesh The mesh to free.
  93290. */
  93291. HighlightLayer.prototype._disposeMesh = function (mesh) {
  93292. this.removeMesh(mesh);
  93293. this.removeExcludedMesh(mesh);
  93294. };
  93295. /**
  93296. * Dispose the highlight layer and free resources.
  93297. */
  93298. HighlightLayer.prototype.dispose = function () {
  93299. if (this._meshes) {
  93300. // Clean mesh references
  93301. for (var id in this._meshes) {
  93302. var meshHighlight = this._meshes[id];
  93303. if (meshHighlight && meshHighlight.mesh) {
  93304. if (meshHighlight.observerHighlight) {
  93305. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93306. }
  93307. if (meshHighlight.observerDefault) {
  93308. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93309. }
  93310. }
  93311. }
  93312. this._meshes = null;
  93313. }
  93314. if (this._excludedMeshes) {
  93315. for (var id in this._excludedMeshes) {
  93316. var meshHighlight = this._excludedMeshes[id];
  93317. if (meshHighlight) {
  93318. if (meshHighlight.beforeRender) {
  93319. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  93320. }
  93321. if (meshHighlight.afterRender) {
  93322. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  93323. }
  93324. }
  93325. }
  93326. this._excludedMeshes = null;
  93327. }
  93328. _super.prototype.dispose.call(this);
  93329. };
  93330. /**
  93331. * Gets the class name of the effect layer
  93332. * @returns the string with the class name of the effect layer
  93333. */
  93334. HighlightLayer.prototype.getClassName = function () {
  93335. return "HighlightLayer";
  93336. };
  93337. /**
  93338. * Serializes this Highlight layer
  93339. * @returns a serialized Highlight layer object
  93340. */
  93341. HighlightLayer.prototype.serialize = function () {
  93342. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93343. serializationObject.customType = "BABYLON.HighlightLayer";
  93344. // Highlighted meshes
  93345. serializationObject.meshes = [];
  93346. if (this._meshes) {
  93347. for (var m in this._meshes) {
  93348. var mesh = this._meshes[m];
  93349. if (mesh) {
  93350. serializationObject.meshes.push({
  93351. glowEmissiveOnly: mesh.glowEmissiveOnly,
  93352. color: mesh.color.asArray(),
  93353. meshId: mesh.mesh.id
  93354. });
  93355. }
  93356. }
  93357. }
  93358. // Excluded meshes
  93359. serializationObject.excludedMeshes = [];
  93360. if (this._excludedMeshes) {
  93361. for (var e in this._excludedMeshes) {
  93362. var excludedMesh = this._excludedMeshes[e];
  93363. if (excludedMesh) {
  93364. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  93365. }
  93366. }
  93367. }
  93368. return serializationObject;
  93369. };
  93370. /**
  93371. * Creates a Highlight layer from parsed Highlight layer data
  93372. * @param parsedHightlightLayer defines the Highlight layer data
  93373. * @param scene defines the current scene
  93374. * @param rootUrl defines the root URL containing the Highlight layer information
  93375. * @returns a parsed Highlight layer
  93376. */
  93377. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93378. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93379. var index;
  93380. // Excluded meshes
  93381. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93382. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93383. if (mesh) {
  93384. hl.addExcludedMesh(mesh);
  93385. }
  93386. }
  93387. // Included meshes
  93388. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93389. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93390. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93391. if (mesh) {
  93392. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93393. }
  93394. }
  93395. return hl;
  93396. };
  93397. /**
  93398. * Effect Name of the highlight layer.
  93399. */
  93400. HighlightLayer.EffectName = "HighlightLayer";
  93401. /**
  93402. * The neutral color used during the preparation of the glow effect.
  93403. * This is black by default as the blend operation is a blend operation.
  93404. */
  93405. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93406. /**
  93407. * Stencil value used for glowing meshes.
  93408. */
  93409. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93410. /**
  93411. * Stencil value used for the other meshes in the scene.
  93412. */
  93413. HighlightLayer.NormalMeshStencilReference = 0x01;
  93414. __decorate([
  93415. BABYLON.serialize()
  93416. ], HighlightLayer.prototype, "innerGlow", void 0);
  93417. __decorate([
  93418. BABYLON.serialize()
  93419. ], HighlightLayer.prototype, "outerGlow", void 0);
  93420. __decorate([
  93421. BABYLON.serialize()
  93422. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93423. __decorate([
  93424. BABYLON.serialize()
  93425. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93426. __decorate([
  93427. BABYLON.serialize("options")
  93428. ], HighlightLayer.prototype, "_options", void 0);
  93429. return HighlightLayer;
  93430. }(BABYLON.EffectLayer));
  93431. BABYLON.HighlightLayer = HighlightLayer;
  93432. })(BABYLON || (BABYLON = {}));
  93433. //# sourceMappingURL=babylon.highlightLayer.js.map
  93434. var BABYLON;
  93435. (function (BABYLON) {
  93436. /**
  93437. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93438. *
  93439. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93440. * glowy meshes to your scene.
  93441. *
  93442. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93443. */
  93444. var GlowLayer = /** @class */ (function (_super) {
  93445. __extends(GlowLayer, _super);
  93446. /**
  93447. * Instantiates a new glow Layer and references it to the scene.
  93448. * @param name The name of the layer
  93449. * @param scene The scene to use the layer in
  93450. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93451. */
  93452. function GlowLayer(name, scene, options) {
  93453. var _this = _super.call(this, name, scene) || this;
  93454. _this._intensity = 1.0;
  93455. _this._includedOnlyMeshes = [];
  93456. _this._excludedMeshes = [];
  93457. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93458. // Adapt options
  93459. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93460. // Initialize the layer
  93461. _this._init({
  93462. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93463. camera: _this._options.camera,
  93464. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93465. mainTextureRatio: _this._options.mainTextureRatio
  93466. });
  93467. return _this;
  93468. }
  93469. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93470. /**
  93471. * Gets the kernel size of the blur.
  93472. */
  93473. get: function () {
  93474. return this._horizontalBlurPostprocess1.kernel;
  93475. },
  93476. /**
  93477. * Sets the kernel size of the blur.
  93478. */
  93479. set: function (value) {
  93480. this._horizontalBlurPostprocess1.kernel = value;
  93481. this._verticalBlurPostprocess1.kernel = value;
  93482. this._horizontalBlurPostprocess2.kernel = value;
  93483. this._verticalBlurPostprocess2.kernel = value;
  93484. },
  93485. enumerable: true,
  93486. configurable: true
  93487. });
  93488. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93489. /**
  93490. * Gets the glow intensity.
  93491. */
  93492. get: function () {
  93493. return this._intensity;
  93494. },
  93495. /**
  93496. * Sets the glow intensity.
  93497. */
  93498. set: function (value) {
  93499. this._intensity = value;
  93500. },
  93501. enumerable: true,
  93502. configurable: true
  93503. });
  93504. /**
  93505. * Get the effect name of the layer.
  93506. * @return The effect name
  93507. */
  93508. GlowLayer.prototype.getEffectName = function () {
  93509. return GlowLayer.EffectName;
  93510. };
  93511. /**
  93512. * Create the merge effect. This is the shader use to blit the information back
  93513. * to the main canvas at the end of the scene rendering.
  93514. */
  93515. GlowLayer.prototype._createMergeEffect = function () {
  93516. // Effect
  93517. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93518. };
  93519. /**
  93520. * Creates the render target textures and post processes used in the glow layer.
  93521. */
  93522. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93523. var _this = this;
  93524. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93525. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93526. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93527. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93528. var textureType = 0;
  93529. if (this._engine.getCaps().textureHalfFloatRender) {
  93530. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93531. }
  93532. else {
  93533. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93534. }
  93535. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93536. width: blurTextureWidth,
  93537. height: blurTextureHeight
  93538. }, this._scene, false, true, textureType);
  93539. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93540. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93541. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93542. this._blurTexture1.renderParticles = false;
  93543. this._blurTexture1.ignoreCameraViewport = true;
  93544. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93545. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93546. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93547. width: blurTextureWidth2,
  93548. height: blurTextureHeight2
  93549. }, this._scene, false, true, textureType);
  93550. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93551. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93552. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93553. this._blurTexture2.renderParticles = false;
  93554. this._blurTexture2.ignoreCameraViewport = true;
  93555. this._textures = [this._blurTexture1, this._blurTexture2];
  93556. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93557. width: blurTextureWidth,
  93558. height: blurTextureHeight
  93559. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93560. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93561. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93562. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93563. effect.setTexture("textureSampler", _this._mainTexture);
  93564. });
  93565. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93566. width: blurTextureWidth,
  93567. height: blurTextureHeight
  93568. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93569. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93570. width: blurTextureWidth2,
  93571. height: blurTextureHeight2
  93572. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93573. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93574. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93575. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93576. effect.setTexture("textureSampler", _this._blurTexture1);
  93577. });
  93578. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93579. width: blurTextureWidth2,
  93580. height: blurTextureHeight2
  93581. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93582. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93583. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93584. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93585. this._mainTexture.samples = this._options.mainTextureSamples;
  93586. this._mainTexture.onAfterUnbindObservable.add(function () {
  93587. var internalTexture = _this._blurTexture1.getInternalTexture();
  93588. if (internalTexture) {
  93589. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93590. internalTexture = _this._blurTexture2.getInternalTexture();
  93591. if (internalTexture) {
  93592. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93593. }
  93594. }
  93595. });
  93596. // Prevent autoClear.
  93597. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93598. };
  93599. /**
  93600. * Checks for the readiness of the element composing the layer.
  93601. * @param subMesh the mesh to check for
  93602. * @param useInstances specify wether or not to use instances to render the mesh
  93603. * @param emissiveTexture the associated emissive texture used to generate the glow
  93604. * @return true if ready otherwise, false
  93605. */
  93606. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93607. var material = subMesh.getMaterial();
  93608. var mesh = subMesh.getRenderingMesh();
  93609. if (!material || !mesh) {
  93610. return false;
  93611. }
  93612. var emissiveTexture = material.emissiveTexture;
  93613. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93614. };
  93615. /**
  93616. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93617. */
  93618. GlowLayer.prototype.needStencil = function () {
  93619. return false;
  93620. };
  93621. /**
  93622. * Implementation specific of rendering the generating effect on the main canvas.
  93623. * @param effect The effect used to render through
  93624. */
  93625. GlowLayer.prototype._internalRender = function (effect) {
  93626. // Texture
  93627. effect.setTexture("textureSampler", this._blurTexture1);
  93628. effect.setTexture("textureSampler2", this._blurTexture2);
  93629. effect.setFloat("offset", this._intensity);
  93630. // Cache
  93631. var engine = this._engine;
  93632. var previousStencilBuffer = engine.getStencilBuffer();
  93633. // Draw order
  93634. engine.setStencilBuffer(false);
  93635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93636. // Draw order
  93637. engine.setStencilBuffer(previousStencilBuffer);
  93638. };
  93639. /**
  93640. * Sets the required values for both the emissive texture and and the main color.
  93641. */
  93642. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93643. var textureLevel = 1.0;
  93644. if (this.customEmissiveTextureSelector) {
  93645. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93646. }
  93647. else {
  93648. if (material) {
  93649. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93650. if (this._emissiveTextureAndColor.texture) {
  93651. textureLevel = this._emissiveTextureAndColor.texture.level;
  93652. }
  93653. }
  93654. else {
  93655. this._emissiveTextureAndColor.texture = null;
  93656. }
  93657. }
  93658. if (this.customEmissiveColorSelector) {
  93659. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93660. }
  93661. else {
  93662. if (material.emissiveColor) {
  93663. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93664. }
  93665. else {
  93666. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93667. }
  93668. }
  93669. };
  93670. /**
  93671. * Returns true if the mesh should render, otherwise false.
  93672. * @param mesh The mesh to render
  93673. * @returns true if it should render otherwise false
  93674. */
  93675. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93676. return this.hasMesh(mesh);
  93677. };
  93678. /**
  93679. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93680. * @param mesh The mesh to exclude from the glow layer
  93681. */
  93682. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93683. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93684. this._excludedMeshes.push(mesh.uniqueId);
  93685. }
  93686. };
  93687. /**
  93688. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93689. * @param mesh The mesh to remove
  93690. */
  93691. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93692. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93693. if (index !== -1) {
  93694. this._excludedMeshes.splice(index, 1);
  93695. }
  93696. };
  93697. /**
  93698. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93699. * @param mesh The mesh to include in the glow layer
  93700. */
  93701. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93702. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93703. this._includedOnlyMeshes.push(mesh.uniqueId);
  93704. }
  93705. };
  93706. /**
  93707. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93708. * @param mesh The mesh to remove
  93709. */
  93710. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93711. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93712. if (index !== -1) {
  93713. this._includedOnlyMeshes.splice(index, 1);
  93714. }
  93715. };
  93716. /**
  93717. * Determine if a given mesh will be used in the glow layer
  93718. * @param mesh The mesh to test
  93719. * @returns true if the mesh will be highlighted by the current glow layer
  93720. */
  93721. GlowLayer.prototype.hasMesh = function (mesh) {
  93722. // Included Mesh
  93723. if (this._includedOnlyMeshes.length) {
  93724. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93725. }
  93726. ;
  93727. // Excluded Mesh
  93728. if (this._excludedMeshes.length) {
  93729. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93730. }
  93731. ;
  93732. return true;
  93733. };
  93734. /**
  93735. * Free any resources and references associated to a mesh.
  93736. * Internal use
  93737. * @param mesh The mesh to free.
  93738. */
  93739. GlowLayer.prototype._disposeMesh = function (mesh) {
  93740. this.removeIncludedOnlyMesh(mesh);
  93741. this.removeExcludedMesh(mesh);
  93742. };
  93743. /**
  93744. * Gets the class name of the effect layer
  93745. * @returns the string with the class name of the effect layer
  93746. */
  93747. GlowLayer.prototype.getClassName = function () {
  93748. return "GlowLayer";
  93749. };
  93750. /**
  93751. * Serializes this glow layer
  93752. * @returns a serialized glow layer object
  93753. */
  93754. GlowLayer.prototype.serialize = function () {
  93755. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93756. serializationObject.customType = "BABYLON.GlowLayer";
  93757. var index;
  93758. // Included meshes
  93759. serializationObject.includedMeshes = [];
  93760. if (this._includedOnlyMeshes.length) {
  93761. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93762. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93763. if (mesh) {
  93764. serializationObject.includedMeshes.push(mesh.id);
  93765. }
  93766. }
  93767. }
  93768. // Excluded meshes
  93769. serializationObject.excludedMeshes = [];
  93770. if (this._excludedMeshes.length) {
  93771. for (index = 0; index < this._excludedMeshes.length; index++) {
  93772. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93773. if (mesh) {
  93774. serializationObject.excludedMeshes.push(mesh.id);
  93775. }
  93776. }
  93777. }
  93778. return serializationObject;
  93779. };
  93780. /**
  93781. * Creates a Glow Layer from parsed glow layer data
  93782. * @param parsedGlowLayer defines glow layer data
  93783. * @param scene defines the current scene
  93784. * @param rootUrl defines the root URL containing the glow layer information
  93785. * @returns a parsed Glow Layer
  93786. */
  93787. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93788. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93789. var index;
  93790. // Excluded meshes
  93791. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93792. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93793. if (mesh) {
  93794. gl.addExcludedMesh(mesh);
  93795. }
  93796. }
  93797. // Included meshes
  93798. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93799. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93800. if (mesh) {
  93801. gl.addIncludedOnlyMesh(mesh);
  93802. }
  93803. }
  93804. return gl;
  93805. };
  93806. /**
  93807. * Effect Name of the layer.
  93808. */
  93809. GlowLayer.EffectName = "GlowLayer";
  93810. /**
  93811. * The default blur kernel size used for the glow.
  93812. */
  93813. GlowLayer.DefaultBlurKernelSize = 32;
  93814. /**
  93815. * The default texture size ratio used for the glow.
  93816. */
  93817. GlowLayer.DefaultTextureRatio = 0.5;
  93818. __decorate([
  93819. BABYLON.serialize()
  93820. ], GlowLayer.prototype, "blurKernelSize", null);
  93821. __decorate([
  93822. BABYLON.serialize()
  93823. ], GlowLayer.prototype, "intensity", null);
  93824. __decorate([
  93825. BABYLON.serialize("options")
  93826. ], GlowLayer.prototype, "_options", void 0);
  93827. return GlowLayer;
  93828. }(BABYLON.EffectLayer));
  93829. BABYLON.GlowLayer = GlowLayer;
  93830. })(BABYLON || (BABYLON = {}));
  93831. //# sourceMappingURL=babylon.glowLayer.js.map
  93832. var BABYLON;
  93833. (function (BABYLON) {
  93834. /**
  93835. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93836. */
  93837. var AssetTaskState;
  93838. (function (AssetTaskState) {
  93839. /**
  93840. * Initialization
  93841. */
  93842. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93843. /**
  93844. * Running
  93845. */
  93846. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93847. /**
  93848. * Done
  93849. */
  93850. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93851. /**
  93852. * Error
  93853. */
  93854. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93855. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93856. /**
  93857. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93858. */
  93859. var AbstractAssetTask = /** @class */ (function () {
  93860. /**
  93861. * Creates a new {BABYLON.AssetsManager}
  93862. * @param name defines the name of the task
  93863. */
  93864. function AbstractAssetTask(
  93865. /**
  93866. * Task name
  93867. */ name) {
  93868. this.name = name;
  93869. this._isCompleted = false;
  93870. this._taskState = AssetTaskState.INIT;
  93871. }
  93872. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93873. /**
  93874. * Get if the task is completed
  93875. */
  93876. get: function () {
  93877. return this._isCompleted;
  93878. },
  93879. enumerable: true,
  93880. configurable: true
  93881. });
  93882. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93883. /**
  93884. * Gets the current state of the task
  93885. */
  93886. get: function () {
  93887. return this._taskState;
  93888. },
  93889. enumerable: true,
  93890. configurable: true
  93891. });
  93892. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93893. /**
  93894. * Gets the current error object (if task is in error)
  93895. */
  93896. get: function () {
  93897. return this._errorObject;
  93898. },
  93899. enumerable: true,
  93900. configurable: true
  93901. });
  93902. /**
  93903. * Internal only
  93904. * @hidden
  93905. */
  93906. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93907. if (this._errorObject) {
  93908. return;
  93909. }
  93910. this._errorObject = {
  93911. message: message,
  93912. exception: exception
  93913. };
  93914. };
  93915. /**
  93916. * Execute the current task
  93917. * @param scene defines the scene where you want your assets to be loaded
  93918. * @param onSuccess is a callback called when the task is successfully executed
  93919. * @param onError is a callback called if an error occurs
  93920. */
  93921. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93922. var _this = this;
  93923. this._taskState = AssetTaskState.RUNNING;
  93924. this.runTask(scene, function () {
  93925. _this.onDoneCallback(onSuccess, onError);
  93926. }, function (msg, exception) {
  93927. _this.onErrorCallback(onError, msg, exception);
  93928. });
  93929. };
  93930. /**
  93931. * Execute the current task
  93932. * @param scene defines the scene where you want your assets to be loaded
  93933. * @param onSuccess is a callback called when the task is successfully executed
  93934. * @param onError is a callback called if an error occurs
  93935. */
  93936. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93937. throw new Error("runTask is not implemented");
  93938. };
  93939. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93940. this._taskState = AssetTaskState.ERROR;
  93941. this._errorObject = {
  93942. message: message,
  93943. exception: exception
  93944. };
  93945. if (this.onError) {
  93946. this.onError(this, message, exception);
  93947. }
  93948. onError();
  93949. };
  93950. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93951. try {
  93952. this._taskState = AssetTaskState.DONE;
  93953. this._isCompleted = true;
  93954. if (this.onSuccess) {
  93955. this.onSuccess(this);
  93956. }
  93957. onSuccess();
  93958. }
  93959. catch (e) {
  93960. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93961. }
  93962. };
  93963. return AbstractAssetTask;
  93964. }());
  93965. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93966. /**
  93967. * Class used to share progress information about assets loading
  93968. */
  93969. var AssetsProgressEvent = /** @class */ (function () {
  93970. /**
  93971. * Creates a {BABYLON.AssetsProgressEvent}
  93972. * @param remainingCount defines the number of remaining tasks to process
  93973. * @param totalCount defines the total number of tasks
  93974. * @param task defines the task that was just processed
  93975. */
  93976. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93977. this.remainingCount = remainingCount;
  93978. this.totalCount = totalCount;
  93979. this.task = task;
  93980. }
  93981. return AssetsProgressEvent;
  93982. }());
  93983. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93984. /**
  93985. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93986. */
  93987. var MeshAssetTask = /** @class */ (function (_super) {
  93988. __extends(MeshAssetTask, _super);
  93989. /**
  93990. * Creates a new {BABYLON.MeshAssetTask}
  93991. * @param name defines the name of the task
  93992. * @param meshesNames defines the list of mesh's names you want to load
  93993. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93994. * @param sceneFilename defines the filename of the scene to load from
  93995. */
  93996. function MeshAssetTask(
  93997. /**
  93998. * Defines the name of the task
  93999. */
  94000. name,
  94001. /**
  94002. * Defines the list of mesh's names you want to load
  94003. */
  94004. meshesNames,
  94005. /**
  94006. * Defines the root url to use as a base to load your meshes and associated resources
  94007. */
  94008. rootUrl,
  94009. /**
  94010. * Defines the filename of the scene to load from
  94011. */
  94012. sceneFilename) {
  94013. var _this = _super.call(this, name) || this;
  94014. _this.name = name;
  94015. _this.meshesNames = meshesNames;
  94016. _this.rootUrl = rootUrl;
  94017. _this.sceneFilename = sceneFilename;
  94018. return _this;
  94019. }
  94020. /**
  94021. * Execute the current task
  94022. * @param scene defines the scene where you want your assets to be loaded
  94023. * @param onSuccess is a callback called when the task is successfully executed
  94024. * @param onError is a callback called if an error occurs
  94025. */
  94026. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94027. var _this = this;
  94028. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  94029. _this.loadedMeshes = meshes;
  94030. _this.loadedParticleSystems = particleSystems;
  94031. _this.loadedSkeletons = skeletons;
  94032. onSuccess();
  94033. }, null, function (scene, message, exception) {
  94034. onError(message, exception);
  94035. });
  94036. };
  94037. return MeshAssetTask;
  94038. }(AbstractAssetTask));
  94039. BABYLON.MeshAssetTask = MeshAssetTask;
  94040. /**
  94041. * Define a task used by {BABYLON.AssetsManager} to load text content
  94042. */
  94043. var TextFileAssetTask = /** @class */ (function (_super) {
  94044. __extends(TextFileAssetTask, _super);
  94045. /**
  94046. * Creates a new TextFileAssetTask object
  94047. * @param name defines the name of the task
  94048. * @param url defines the location of the file to load
  94049. */
  94050. function TextFileAssetTask(
  94051. /**
  94052. * Defines the name of the task
  94053. */
  94054. name,
  94055. /**
  94056. * Defines the location of the file to load
  94057. */
  94058. url) {
  94059. var _this = _super.call(this, name) || this;
  94060. _this.name = name;
  94061. _this.url = url;
  94062. return _this;
  94063. }
  94064. /**
  94065. * Execute the current task
  94066. * @param scene defines the scene where you want your assets to be loaded
  94067. * @param onSuccess is a callback called when the task is successfully executed
  94068. * @param onError is a callback called if an error occurs
  94069. */
  94070. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94071. var _this = this;
  94072. scene._loadFile(this.url, function (data) {
  94073. _this.text = data;
  94074. onSuccess();
  94075. }, undefined, false, false, function (request, exception) {
  94076. if (request) {
  94077. onError(request.status + " " + request.statusText, exception);
  94078. }
  94079. });
  94080. };
  94081. return TextFileAssetTask;
  94082. }(AbstractAssetTask));
  94083. BABYLON.TextFileAssetTask = TextFileAssetTask;
  94084. /**
  94085. * Define a task used by {BABYLON.AssetsManager} to load binary data
  94086. */
  94087. var BinaryFileAssetTask = /** @class */ (function (_super) {
  94088. __extends(BinaryFileAssetTask, _super);
  94089. /**
  94090. * Creates a new BinaryFileAssetTask object
  94091. * @param name defines the name of the new task
  94092. * @param url defines the location of the file to load
  94093. */
  94094. function BinaryFileAssetTask(
  94095. /**
  94096. * Defines the name of the task
  94097. */
  94098. name,
  94099. /**
  94100. * Defines the location of the file to load
  94101. */
  94102. url) {
  94103. var _this = _super.call(this, name) || this;
  94104. _this.name = name;
  94105. _this.url = url;
  94106. return _this;
  94107. }
  94108. /**
  94109. * Execute the current task
  94110. * @param scene defines the scene where you want your assets to be loaded
  94111. * @param onSuccess is a callback called when the task is successfully executed
  94112. * @param onError is a callback called if an error occurs
  94113. */
  94114. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94115. var _this = this;
  94116. scene._loadFile(this.url, function (data) {
  94117. _this.data = data;
  94118. onSuccess();
  94119. }, undefined, true, true, function (request, exception) {
  94120. if (request) {
  94121. onError(request.status + " " + request.statusText, exception);
  94122. }
  94123. });
  94124. };
  94125. return BinaryFileAssetTask;
  94126. }(AbstractAssetTask));
  94127. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  94128. /**
  94129. * Define a task used by {BABYLON.AssetsManager} to load images
  94130. */
  94131. var ImageAssetTask = /** @class */ (function (_super) {
  94132. __extends(ImageAssetTask, _super);
  94133. /**
  94134. * Creates a new ImageAssetTask
  94135. * @param name defines the name of the task
  94136. * @param url defines the location of the image to load
  94137. */
  94138. function ImageAssetTask(
  94139. /**
  94140. * Defines the name of the task
  94141. */
  94142. name,
  94143. /**
  94144. * Defines the location of the image to load
  94145. */
  94146. url) {
  94147. var _this = _super.call(this, name) || this;
  94148. _this.name = name;
  94149. _this.url = url;
  94150. return _this;
  94151. }
  94152. /**
  94153. * Execute the current task
  94154. * @param scene defines the scene where you want your assets to be loaded
  94155. * @param onSuccess is a callback called when the task is successfully executed
  94156. * @param onError is a callback called if an error occurs
  94157. */
  94158. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94159. var _this = this;
  94160. var img = new Image();
  94161. BABYLON.Tools.SetCorsBehavior(this.url, img);
  94162. img.onload = function () {
  94163. _this.image = img;
  94164. onSuccess();
  94165. };
  94166. img.onerror = function (err) {
  94167. onError("Error loading image", err);
  94168. };
  94169. img.src = this.url;
  94170. };
  94171. return ImageAssetTask;
  94172. }(AbstractAssetTask));
  94173. BABYLON.ImageAssetTask = ImageAssetTask;
  94174. /**
  94175. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  94176. */
  94177. var TextureAssetTask = /** @class */ (function (_super) {
  94178. __extends(TextureAssetTask, _super);
  94179. /**
  94180. * Creates a new TextureAssetTask object
  94181. * @param name defines the name of the task
  94182. * @param url defines the location of the file to load
  94183. * @param noMipmap defines if mipmap should not be generated (default is false)
  94184. * @param invertY defines if texture must be inverted on Y axis (default is false)
  94185. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  94186. */
  94187. function TextureAssetTask(
  94188. /**
  94189. * Defines the name of the task
  94190. */
  94191. name,
  94192. /**
  94193. * Defines the location of the file to load
  94194. */
  94195. url,
  94196. /**
  94197. * Defines if mipmap should not be generated (default is false)
  94198. */
  94199. noMipmap,
  94200. /**
  94201. * Defines if texture must be inverted on Y axis (default is false)
  94202. */
  94203. invertY,
  94204. /**
  94205. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  94206. */
  94207. samplingMode) {
  94208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94209. var _this = _super.call(this, name) || this;
  94210. _this.name = name;
  94211. _this.url = url;
  94212. _this.noMipmap = noMipmap;
  94213. _this.invertY = invertY;
  94214. _this.samplingMode = samplingMode;
  94215. return _this;
  94216. }
  94217. /**
  94218. * Execute the current task
  94219. * @param scene defines the scene where you want your assets to be loaded
  94220. * @param onSuccess is a callback called when the task is successfully executed
  94221. * @param onError is a callback called if an error occurs
  94222. */
  94223. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94224. var onload = function () {
  94225. onSuccess();
  94226. };
  94227. var onerror = function (message, exception) {
  94228. onError(message, exception);
  94229. };
  94230. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  94231. };
  94232. return TextureAssetTask;
  94233. }(AbstractAssetTask));
  94234. BABYLON.TextureAssetTask = TextureAssetTask;
  94235. /**
  94236. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  94237. */
  94238. var CubeTextureAssetTask = /** @class */ (function (_super) {
  94239. __extends(CubeTextureAssetTask, _super);
  94240. /**
  94241. * Creates a new CubeTextureAssetTask
  94242. * @param name defines the name of the task
  94243. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  94244. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  94245. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94246. * @param files defines the explicit list of files (undefined by default)
  94247. */
  94248. function CubeTextureAssetTask(
  94249. /**
  94250. * Defines the name of the task
  94251. */
  94252. name,
  94253. /**
  94254. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  94255. */
  94256. url,
  94257. /**
  94258. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  94259. */
  94260. extensions,
  94261. /**
  94262. * Defines if mipmaps should not be generated (default is false)
  94263. */
  94264. noMipmap,
  94265. /**
  94266. * Defines the explicit list of files (undefined by default)
  94267. */
  94268. files) {
  94269. var _this = _super.call(this, name) || this;
  94270. _this.name = name;
  94271. _this.url = url;
  94272. _this.extensions = extensions;
  94273. _this.noMipmap = noMipmap;
  94274. _this.files = files;
  94275. return _this;
  94276. }
  94277. /**
  94278. * Execute the current task
  94279. * @param scene defines the scene where you want your assets to be loaded
  94280. * @param onSuccess is a callback called when the task is successfully executed
  94281. * @param onError is a callback called if an error occurs
  94282. */
  94283. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94284. var onload = function () {
  94285. onSuccess();
  94286. };
  94287. var onerror = function (message, exception) {
  94288. onError(message, exception);
  94289. };
  94290. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  94291. };
  94292. return CubeTextureAssetTask;
  94293. }(AbstractAssetTask));
  94294. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  94295. /**
  94296. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  94297. */
  94298. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  94299. __extends(HDRCubeTextureAssetTask, _super);
  94300. /**
  94301. * Creates a new HDRCubeTextureAssetTask object
  94302. * @param name defines the name of the task
  94303. * @param url defines the location of the file to load
  94304. * @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.
  94305. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94306. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94307. * @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)
  94308. * @param reserved Internal use only
  94309. */
  94310. function HDRCubeTextureAssetTask(
  94311. /**
  94312. * Defines the name of the task
  94313. */
  94314. name,
  94315. /**
  94316. * Defines the location of the file to load
  94317. */
  94318. url,
  94319. /**
  94320. * Defines the desired size (the more it increases the longer the generation will be)
  94321. */
  94322. size,
  94323. /**
  94324. * Defines if mipmaps should not be generated (default is false)
  94325. */
  94326. noMipmap,
  94327. /**
  94328. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94329. */
  94330. generateHarmonics,
  94331. /**
  94332. * 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)
  94333. */
  94334. gammaSpace,
  94335. /**
  94336. * Internal Use Only
  94337. */
  94338. reserved) {
  94339. if (noMipmap === void 0) { noMipmap = false; }
  94340. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94341. if (gammaSpace === void 0) { gammaSpace = false; }
  94342. if (reserved === void 0) { reserved = false; }
  94343. var _this = _super.call(this, name) || this;
  94344. _this.name = name;
  94345. _this.url = url;
  94346. _this.size = size;
  94347. _this.noMipmap = noMipmap;
  94348. _this.generateHarmonics = generateHarmonics;
  94349. _this.gammaSpace = gammaSpace;
  94350. _this.reserved = reserved;
  94351. return _this;
  94352. }
  94353. /**
  94354. * Execute the current task
  94355. * @param scene defines the scene where you want your assets to be loaded
  94356. * @param onSuccess is a callback called when the task is successfully executed
  94357. * @param onError is a callback called if an error occurs
  94358. */
  94359. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94360. var onload = function () {
  94361. onSuccess();
  94362. };
  94363. var onerror = function (message, exception) {
  94364. onError(message, exception);
  94365. };
  94366. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  94367. };
  94368. return HDRCubeTextureAssetTask;
  94369. }(AbstractAssetTask));
  94370. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  94371. /**
  94372. * This class can be used to easily import assets into a scene
  94373. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  94374. */
  94375. var AssetsManager = /** @class */ (function () {
  94376. /**
  94377. * Creates a new AssetsManager
  94378. * @param scene defines the scene to work on
  94379. */
  94380. function AssetsManager(scene) {
  94381. this._isLoading = false;
  94382. this._tasks = new Array();
  94383. this._waitingTasksCount = 0;
  94384. this._totalTasksCount = 0;
  94385. /**
  94386. * Observable called when all tasks are processed
  94387. */
  94388. this.onTaskSuccessObservable = new BABYLON.Observable();
  94389. /**
  94390. * Observable called when a task had an error
  94391. */
  94392. this.onTaskErrorObservable = new BABYLON.Observable();
  94393. /**
  94394. * Observable called when a task is successful
  94395. */
  94396. this.onTasksDoneObservable = new BABYLON.Observable();
  94397. /**
  94398. * Observable called when a task is done (whatever the result is)
  94399. */
  94400. this.onProgressObservable = new BABYLON.Observable();
  94401. /**
  94402. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94403. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94404. */
  94405. this.useDefaultLoadingScreen = true;
  94406. this._scene = scene;
  94407. }
  94408. /**
  94409. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94410. * @param taskName defines the name of the new task
  94411. * @param meshesNames defines the name of meshes to load
  94412. * @param rootUrl defines the root url to use to locate files
  94413. * @param sceneFilename defines the filename of the scene file
  94414. * @returns a new {BABYLON.MeshAssetTask} object
  94415. */
  94416. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94417. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94418. this._tasks.push(task);
  94419. return task;
  94420. };
  94421. /**
  94422. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94423. * @param taskName defines the name of the new task
  94424. * @param url defines the url of the file to load
  94425. * @returns a new {BABYLON.TextFileAssetTask} object
  94426. */
  94427. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94428. var task = new TextFileAssetTask(taskName, url);
  94429. this._tasks.push(task);
  94430. return task;
  94431. };
  94432. /**
  94433. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94434. * @param taskName defines the name of the new task
  94435. * @param url defines the url of the file to load
  94436. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94437. */
  94438. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94439. var task = new BinaryFileAssetTask(taskName, url);
  94440. this._tasks.push(task);
  94441. return task;
  94442. };
  94443. /**
  94444. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94445. * @param taskName defines the name of the new task
  94446. * @param url defines the url of the file to load
  94447. * @returns a new {BABYLON.ImageAssetTask} object
  94448. */
  94449. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94450. var task = new ImageAssetTask(taskName, url);
  94451. this._tasks.push(task);
  94452. return task;
  94453. };
  94454. /**
  94455. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94456. * @param taskName defines the name of the new task
  94457. * @param url defines the url of the file to load
  94458. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94459. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94460. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94461. * @returns a new {BABYLON.TextureAssetTask} object
  94462. */
  94463. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94465. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94466. this._tasks.push(task);
  94467. return task;
  94468. };
  94469. /**
  94470. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94471. * @param taskName defines the name of the new task
  94472. * @param url defines the url of the file to load
  94473. * @param extensions defines the extension to use to load the cube map (can be null)
  94474. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94475. * @param files defines the list of files to load (can be null)
  94476. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94477. */
  94478. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94479. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94480. this._tasks.push(task);
  94481. return task;
  94482. };
  94483. /**
  94484. *
  94485. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94486. * @param taskName defines the name of the new task
  94487. * @param url defines the url of the file to load
  94488. * @param size defines the size you want for the cubemap (can be null)
  94489. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94490. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94491. * @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)
  94492. * @param reserved Internal use only
  94493. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94494. */
  94495. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94496. if (noMipmap === void 0) { noMipmap = false; }
  94497. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94498. if (gammaSpace === void 0) { gammaSpace = false; }
  94499. if (reserved === void 0) { reserved = false; }
  94500. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94501. this._tasks.push(task);
  94502. return task;
  94503. };
  94504. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94505. this._waitingTasksCount--;
  94506. try {
  94507. if (this.onProgress) {
  94508. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94509. }
  94510. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94511. }
  94512. catch (e) {
  94513. BABYLON.Tools.Error("Error running progress callbacks.");
  94514. console.log(e);
  94515. }
  94516. if (this._waitingTasksCount === 0) {
  94517. try {
  94518. if (this.onFinish) {
  94519. this.onFinish(this._tasks);
  94520. }
  94521. // Let's remove successfull tasks
  94522. var currentTasks = this._tasks.slice();
  94523. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94524. var task = currentTasks_1[_i];
  94525. if (task.taskState === AssetTaskState.DONE) {
  94526. var index = this._tasks.indexOf(task);
  94527. if (index > -1) {
  94528. this._tasks.splice(index, 1);
  94529. }
  94530. }
  94531. }
  94532. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94533. }
  94534. catch (e) {
  94535. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94536. console.log(e);
  94537. }
  94538. this._isLoading = false;
  94539. this._scene.getEngine().hideLoadingUI();
  94540. }
  94541. };
  94542. AssetsManager.prototype._runTask = function (task) {
  94543. var _this = this;
  94544. var done = function () {
  94545. try {
  94546. if (_this.onTaskSuccess) {
  94547. _this.onTaskSuccess(task);
  94548. }
  94549. _this.onTaskSuccessObservable.notifyObservers(task);
  94550. _this._decreaseWaitingTasksCount(task);
  94551. }
  94552. catch (e) {
  94553. error("Error executing task success callbacks", e);
  94554. }
  94555. };
  94556. var error = function (message, exception) {
  94557. task._setErrorObject(message, exception);
  94558. if (_this.onTaskError) {
  94559. _this.onTaskError(task);
  94560. }
  94561. _this.onTaskErrorObservable.notifyObservers(task);
  94562. _this._decreaseWaitingTasksCount(task);
  94563. };
  94564. task.run(this._scene, done, error);
  94565. };
  94566. /**
  94567. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94568. * @return the current instance of the {BABYLON.AssetsManager}
  94569. */
  94570. AssetsManager.prototype.reset = function () {
  94571. this._isLoading = false;
  94572. this._tasks = new Array();
  94573. return this;
  94574. };
  94575. /**
  94576. * Start the loading process
  94577. * @return the current instance of the {BABYLON.AssetsManager}
  94578. */
  94579. AssetsManager.prototype.load = function () {
  94580. if (this._isLoading) {
  94581. return this;
  94582. }
  94583. this._isLoading = true;
  94584. this._waitingTasksCount = this._tasks.length;
  94585. this._totalTasksCount = this._tasks.length;
  94586. if (this._waitingTasksCount === 0) {
  94587. this._isLoading = false;
  94588. if (this.onFinish) {
  94589. this.onFinish(this._tasks);
  94590. }
  94591. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94592. return this;
  94593. }
  94594. if (this.useDefaultLoadingScreen) {
  94595. this._scene.getEngine().displayLoadingUI();
  94596. }
  94597. for (var index = 0; index < this._tasks.length; index++) {
  94598. var task = this._tasks[index];
  94599. this._runTask(task);
  94600. }
  94601. return this;
  94602. };
  94603. return AssetsManager;
  94604. }());
  94605. BABYLON.AssetsManager = AssetsManager;
  94606. })(BABYLON || (BABYLON = {}));
  94607. //# sourceMappingURL=babylon.assetsManager.js.map
  94608. var BABYLON;
  94609. (function (BABYLON) {
  94610. var serializedGeometries = [];
  94611. var serializeGeometry = function (geometry, serializationGeometries) {
  94612. if (serializedGeometries[geometry.id]) {
  94613. return;
  94614. }
  94615. if (geometry.doNotSerialize) {
  94616. return;
  94617. }
  94618. if (geometry instanceof BABYLON.BoxGeometry) {
  94619. serializationGeometries.boxes.push(geometry.serialize());
  94620. }
  94621. else if (geometry instanceof BABYLON.SphereGeometry) {
  94622. serializationGeometries.spheres.push(geometry.serialize());
  94623. }
  94624. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94625. serializationGeometries.cylinders.push(geometry.serialize());
  94626. }
  94627. else if (geometry instanceof BABYLON.TorusGeometry) {
  94628. serializationGeometries.toruses.push(geometry.serialize());
  94629. }
  94630. else if (geometry instanceof BABYLON.GroundGeometry) {
  94631. serializationGeometries.grounds.push(geometry.serialize());
  94632. }
  94633. else if (geometry instanceof BABYLON.Plane) {
  94634. serializationGeometries.planes.push(geometry.serialize());
  94635. }
  94636. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94637. serializationGeometries.torusKnots.push(geometry.serialize());
  94638. }
  94639. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94640. throw new Error("Unknown primitive type");
  94641. }
  94642. else {
  94643. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94644. }
  94645. serializedGeometries[geometry.id] = true;
  94646. };
  94647. var serializeMesh = function (mesh, serializationScene) {
  94648. var serializationObject = {};
  94649. // Geometry
  94650. var geometry = mesh._geometry;
  94651. if (geometry) {
  94652. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94653. // 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
  94654. serializeGeometry(geometry, serializationScene.geometries);
  94655. }
  94656. }
  94657. // Custom
  94658. if (mesh.serialize) {
  94659. mesh.serialize(serializationObject);
  94660. }
  94661. return serializationObject;
  94662. };
  94663. var finalizeSingleMesh = function (mesh, serializationObject) {
  94664. //only works if the mesh is already loaded
  94665. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94666. //serialize material
  94667. if (mesh.material) {
  94668. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94669. serializationObject.materials = serializationObject.materials || [];
  94670. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94671. serializationObject.materials.push(mesh.material.serialize());
  94672. }
  94673. }
  94674. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94675. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94676. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94677. serializationObject.multiMaterials.push(mesh.material.serialize());
  94678. }
  94679. }
  94680. }
  94681. //serialize geometry
  94682. var geometry = mesh._geometry;
  94683. if (geometry) {
  94684. if (!serializationObject.geometries) {
  94685. serializationObject.geometries = {};
  94686. serializationObject.geometries.boxes = [];
  94687. serializationObject.geometries.spheres = [];
  94688. serializationObject.geometries.cylinders = [];
  94689. serializationObject.geometries.toruses = [];
  94690. serializationObject.geometries.grounds = [];
  94691. serializationObject.geometries.planes = [];
  94692. serializationObject.geometries.torusKnots = [];
  94693. serializationObject.geometries.vertexData = [];
  94694. }
  94695. serializeGeometry(geometry, serializationObject.geometries);
  94696. }
  94697. // Skeletons
  94698. if (mesh.skeleton) {
  94699. serializationObject.skeletons = serializationObject.skeletons || [];
  94700. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94701. }
  94702. //serialize the actual mesh
  94703. serializationObject.meshes = serializationObject.meshes || [];
  94704. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94705. }
  94706. };
  94707. var SceneSerializer = /** @class */ (function () {
  94708. function SceneSerializer() {
  94709. }
  94710. SceneSerializer.ClearCache = function () {
  94711. serializedGeometries = [];
  94712. };
  94713. SceneSerializer.Serialize = function (scene) {
  94714. var serializationObject = {};
  94715. SceneSerializer.ClearCache();
  94716. // Scene
  94717. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94718. serializationObject.autoClear = scene.autoClear;
  94719. serializationObject.clearColor = scene.clearColor.asArray();
  94720. serializationObject.ambientColor = scene.ambientColor.asArray();
  94721. serializationObject.gravity = scene.gravity.asArray();
  94722. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94723. serializationObject.workerCollisions = scene.workerCollisions;
  94724. // Fog
  94725. if (scene.fogMode && scene.fogMode !== 0) {
  94726. serializationObject.fogMode = scene.fogMode;
  94727. serializationObject.fogColor = scene.fogColor.asArray();
  94728. serializationObject.fogStart = scene.fogStart;
  94729. serializationObject.fogEnd = scene.fogEnd;
  94730. serializationObject.fogDensity = scene.fogDensity;
  94731. }
  94732. //Physics
  94733. if (scene.isPhysicsEnabled()) {
  94734. var physicEngine = scene.getPhysicsEngine();
  94735. if (physicEngine) {
  94736. serializationObject.physicsEnabled = true;
  94737. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94738. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94739. }
  94740. }
  94741. // Metadata
  94742. if (scene.metadata) {
  94743. serializationObject.metadata = scene.metadata;
  94744. }
  94745. // Morph targets
  94746. serializationObject.morphTargetManagers = [];
  94747. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94748. var abstractMesh = _a[_i];
  94749. var manager = abstractMesh.morphTargetManager;
  94750. if (manager) {
  94751. serializationObject.morphTargetManagers.push(manager.serialize());
  94752. }
  94753. }
  94754. // Lights
  94755. serializationObject.lights = [];
  94756. var index;
  94757. var light;
  94758. for (index = 0; index < scene.lights.length; index++) {
  94759. light = scene.lights[index];
  94760. if (!light.doNotSerialize) {
  94761. serializationObject.lights.push(light.serialize());
  94762. }
  94763. }
  94764. // Cameras
  94765. serializationObject.cameras = [];
  94766. for (index = 0; index < scene.cameras.length; index++) {
  94767. var camera = scene.cameras[index];
  94768. if (!camera.doNotSerialize) {
  94769. serializationObject.cameras.push(camera.serialize());
  94770. }
  94771. }
  94772. if (scene.activeCamera) {
  94773. serializationObject.activeCameraID = scene.activeCamera.id;
  94774. }
  94775. // Animations
  94776. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94777. // Materials
  94778. serializationObject.materials = [];
  94779. serializationObject.multiMaterials = [];
  94780. var material;
  94781. for (index = 0; index < scene.materials.length; index++) {
  94782. material = scene.materials[index];
  94783. if (!material.doNotSerialize) {
  94784. serializationObject.materials.push(material.serialize());
  94785. }
  94786. }
  94787. // MultiMaterials
  94788. serializationObject.multiMaterials = [];
  94789. for (index = 0; index < scene.multiMaterials.length; index++) {
  94790. var multiMaterial = scene.multiMaterials[index];
  94791. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94792. }
  94793. // Environment texture
  94794. if (scene.environmentTexture) {
  94795. serializationObject.environmentTexture = scene.environmentTexture.name;
  94796. }
  94797. // Skeletons
  94798. serializationObject.skeletons = [];
  94799. for (index = 0; index < scene.skeletons.length; index++) {
  94800. var skeleton = scene.skeletons[index];
  94801. if (!skeleton.doNotSerialize) {
  94802. serializationObject.skeletons.push(skeleton.serialize());
  94803. }
  94804. }
  94805. // Transform nodes
  94806. serializationObject.transformNodes = [];
  94807. for (index = 0; index < scene.transformNodes.length; index++) {
  94808. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94809. }
  94810. // Geometries
  94811. serializationObject.geometries = {};
  94812. serializationObject.geometries.boxes = [];
  94813. serializationObject.geometries.spheres = [];
  94814. serializationObject.geometries.cylinders = [];
  94815. serializationObject.geometries.toruses = [];
  94816. serializationObject.geometries.grounds = [];
  94817. serializationObject.geometries.planes = [];
  94818. serializationObject.geometries.torusKnots = [];
  94819. serializationObject.geometries.vertexData = [];
  94820. serializedGeometries = [];
  94821. var geometries = scene.getGeometries();
  94822. for (index = 0; index < geometries.length; index++) {
  94823. var geometry = geometries[index];
  94824. if (geometry.isReady()) {
  94825. serializeGeometry(geometry, serializationObject.geometries);
  94826. }
  94827. }
  94828. // Meshes
  94829. serializationObject.meshes = [];
  94830. for (index = 0; index < scene.meshes.length; index++) {
  94831. var abstractMesh = scene.meshes[index];
  94832. if (abstractMesh instanceof BABYLON.Mesh) {
  94833. var mesh = abstractMesh;
  94834. if (!mesh.doNotSerialize) {
  94835. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94836. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94837. }
  94838. }
  94839. }
  94840. }
  94841. // Particles Systems
  94842. serializationObject.particleSystems = [];
  94843. for (index = 0; index < scene.particleSystems.length; index++) {
  94844. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94845. }
  94846. // Lens flares
  94847. serializationObject.lensFlareSystems = [];
  94848. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94849. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94850. }
  94851. // Shadows
  94852. serializationObject.shadowGenerators = [];
  94853. for (index = 0; index < scene.lights.length; index++) {
  94854. light = scene.lights[index];
  94855. var shadowGenerator = light.getShadowGenerator();
  94856. if (shadowGenerator) {
  94857. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94858. }
  94859. }
  94860. // Action Manager
  94861. if (scene.actionManager) {
  94862. serializationObject.actions = scene.actionManager.serialize("scene");
  94863. }
  94864. // Audio
  94865. serializationObject.sounds = [];
  94866. for (index = 0; index < scene.soundTracks.length; index++) {
  94867. var soundtrack = scene.soundTracks[index];
  94868. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94869. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94870. }
  94871. }
  94872. // Effect layers
  94873. serializationObject.effectLayers = [];
  94874. for (index = 0; index < scene.effectLayers.length; index++) {
  94875. var layer = scene.effectLayers[index];
  94876. if (layer.serialize) {
  94877. serializationObject.effectLayers.push(layer.serialize());
  94878. }
  94879. }
  94880. return serializationObject;
  94881. };
  94882. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94883. if (withParents === void 0) { withParents = false; }
  94884. if (withChildren === void 0) { withChildren = false; }
  94885. var serializationObject = {};
  94886. SceneSerializer.ClearCache();
  94887. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94888. if (withParents || withChildren) {
  94889. //deliberate for loop! not for each, appended should be processed as well.
  94890. for (var i = 0; i < toSerialize.length; ++i) {
  94891. if (withChildren) {
  94892. toSerialize[i].getDescendants().forEach(function (node) {
  94893. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94894. toSerialize.push(node);
  94895. }
  94896. });
  94897. }
  94898. //make sure the array doesn't contain the object already
  94899. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94900. toSerialize.push(toSerialize[i].parent);
  94901. }
  94902. }
  94903. }
  94904. toSerialize.forEach(function (mesh) {
  94905. finalizeSingleMesh(mesh, serializationObject);
  94906. });
  94907. return serializationObject;
  94908. };
  94909. return SceneSerializer;
  94910. }());
  94911. BABYLON.SceneSerializer = SceneSerializer;
  94912. })(BABYLON || (BABYLON = {}));
  94913. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94914. var BABYLON;
  94915. (function (BABYLON) {
  94916. var ReflectionProbe = /** @class */ (function () {
  94917. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94918. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94919. var _this = this;
  94920. this.name = name;
  94921. this._viewMatrix = BABYLON.Matrix.Identity();
  94922. this._target = BABYLON.Vector3.Zero();
  94923. this._add = BABYLON.Vector3.Zero();
  94924. this._invertYAxis = false;
  94925. this.position = BABYLON.Vector3.Zero();
  94926. this._scene = scene;
  94927. this._scene.reflectionProbes.push(this);
  94928. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94929. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94930. switch (faceIndex) {
  94931. case 0:
  94932. _this._add.copyFromFloats(1, 0, 0);
  94933. break;
  94934. case 1:
  94935. _this._add.copyFromFloats(-1, 0, 0);
  94936. break;
  94937. case 2:
  94938. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94939. break;
  94940. case 3:
  94941. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94942. break;
  94943. case 4:
  94944. _this._add.copyFromFloats(0, 0, 1);
  94945. break;
  94946. case 5:
  94947. _this._add.copyFromFloats(0, 0, -1);
  94948. break;
  94949. }
  94950. if (_this._attachedMesh) {
  94951. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94952. }
  94953. _this.position.addToRef(_this._add, _this._target);
  94954. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94955. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94956. scene._forcedViewPosition = _this.position;
  94957. });
  94958. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94959. scene._forcedViewPosition = null;
  94960. scene.updateTransformMatrix(true);
  94961. });
  94962. if (scene.activeCamera) {
  94963. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94964. }
  94965. }
  94966. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94967. get: function () {
  94968. return this._renderTargetTexture.samples;
  94969. },
  94970. set: function (value) {
  94971. this._renderTargetTexture.samples = value;
  94972. },
  94973. enumerable: true,
  94974. configurable: true
  94975. });
  94976. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94977. get: function () {
  94978. return this._renderTargetTexture.refreshRate;
  94979. },
  94980. set: function (value) {
  94981. this._renderTargetTexture.refreshRate = value;
  94982. },
  94983. enumerable: true,
  94984. configurable: true
  94985. });
  94986. ReflectionProbe.prototype.getScene = function () {
  94987. return this._scene;
  94988. };
  94989. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94990. get: function () {
  94991. return this._renderTargetTexture;
  94992. },
  94993. enumerable: true,
  94994. configurable: true
  94995. });
  94996. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94997. get: function () {
  94998. return this._renderTargetTexture.renderList;
  94999. },
  95000. enumerable: true,
  95001. configurable: true
  95002. });
  95003. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  95004. this._attachedMesh = mesh;
  95005. };
  95006. /**
  95007. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  95008. *
  95009. * @param renderingGroupId The rendering group id corresponding to its index
  95010. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  95011. */
  95012. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  95013. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  95014. };
  95015. ReflectionProbe.prototype.dispose = function () {
  95016. var index = this._scene.reflectionProbes.indexOf(this);
  95017. if (index !== -1) {
  95018. // Remove from the scene if found
  95019. this._scene.reflectionProbes.splice(index, 1);
  95020. }
  95021. if (this._renderTargetTexture) {
  95022. this._renderTargetTexture.dispose();
  95023. this._renderTargetTexture = null;
  95024. }
  95025. };
  95026. return ReflectionProbe;
  95027. }());
  95028. BABYLON.ReflectionProbe = ReflectionProbe;
  95029. })(BABYLON || (BABYLON = {}));
  95030. //# sourceMappingURL=babylon.reflectionProbe.js.map
  95031. var BABYLON;
  95032. (function (BABYLON) {
  95033. var Layer = /** @class */ (function () {
  95034. function Layer(name, imgUrl, scene, isBackground, color) {
  95035. this.name = name;
  95036. this.scale = new BABYLON.Vector2(1, 1);
  95037. this.offset = new BABYLON.Vector2(0, 0);
  95038. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  95039. this.layerMask = 0x0FFFFFFF;
  95040. this._vertexBuffers = {};
  95041. // Events
  95042. /**
  95043. * An event triggered when the layer is disposed.
  95044. */
  95045. this.onDisposeObservable = new BABYLON.Observable();
  95046. /**
  95047. * An event triggered before rendering the scene
  95048. */
  95049. this.onBeforeRenderObservable = new BABYLON.Observable();
  95050. /**
  95051. * An event triggered after rendering the scene
  95052. */
  95053. this.onAfterRenderObservable = new BABYLON.Observable();
  95054. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  95055. this.isBackground = isBackground === undefined ? true : isBackground;
  95056. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  95057. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  95058. this._scene.layers.push(this);
  95059. var engine = this._scene.getEngine();
  95060. // VBO
  95061. var vertices = [];
  95062. vertices.push(1, 1);
  95063. vertices.push(-1, 1);
  95064. vertices.push(-1, -1);
  95065. vertices.push(1, -1);
  95066. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95068. this._createIndexBuffer();
  95069. // Effects
  95070. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  95071. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  95072. }
  95073. Object.defineProperty(Layer.prototype, "onDispose", {
  95074. set: function (callback) {
  95075. if (this._onDisposeObserver) {
  95076. this.onDisposeObservable.remove(this._onDisposeObserver);
  95077. }
  95078. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  95079. },
  95080. enumerable: true,
  95081. configurable: true
  95082. });
  95083. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  95084. set: function (callback) {
  95085. if (this._onBeforeRenderObserver) {
  95086. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  95087. }
  95088. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  95089. },
  95090. enumerable: true,
  95091. configurable: true
  95092. });
  95093. Object.defineProperty(Layer.prototype, "onAfterRender", {
  95094. set: function (callback) {
  95095. if (this._onAfterRenderObserver) {
  95096. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95097. }
  95098. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  95099. },
  95100. enumerable: true,
  95101. configurable: true
  95102. });
  95103. Layer.prototype._createIndexBuffer = function () {
  95104. var engine = this._scene.getEngine();
  95105. // Indices
  95106. var indices = [];
  95107. indices.push(0);
  95108. indices.push(1);
  95109. indices.push(2);
  95110. indices.push(0);
  95111. indices.push(2);
  95112. indices.push(3);
  95113. this._indexBuffer = engine.createIndexBuffer(indices);
  95114. };
  95115. Layer.prototype._rebuild = function () {
  95116. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95117. if (vb) {
  95118. vb._rebuild();
  95119. }
  95120. this._createIndexBuffer();
  95121. };
  95122. Layer.prototype.render = function () {
  95123. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  95124. // Check
  95125. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  95126. return;
  95127. var engine = this._scene.getEngine();
  95128. this.onBeforeRenderObservable.notifyObservers(this);
  95129. // Render
  95130. engine.enableEffect(currentEffect);
  95131. engine.setState(false);
  95132. // Texture
  95133. currentEffect.setTexture("textureSampler", this.texture);
  95134. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  95135. // Color
  95136. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  95137. // Scale / offset
  95138. currentEffect.setVector2("offset", this.offset);
  95139. currentEffect.setVector2("scale", this.scale);
  95140. // VBOs
  95141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95142. // Draw order
  95143. if (!this.alphaTest) {
  95144. engine.setAlphaMode(this.alphaBlendingMode);
  95145. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95146. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95147. }
  95148. else {
  95149. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95150. }
  95151. this.onAfterRenderObservable.notifyObservers(this);
  95152. };
  95153. Layer.prototype.dispose = function () {
  95154. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95155. if (vertexBuffer) {
  95156. vertexBuffer.dispose();
  95157. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95158. }
  95159. if (this._indexBuffer) {
  95160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95161. this._indexBuffer = null;
  95162. }
  95163. if (this.texture) {
  95164. this.texture.dispose();
  95165. this.texture = null;
  95166. }
  95167. // Remove from scene
  95168. var index = this._scene.layers.indexOf(this);
  95169. this._scene.layers.splice(index, 1);
  95170. // Callback
  95171. this.onDisposeObservable.notifyObservers(this);
  95172. this.onDisposeObservable.clear();
  95173. this.onAfterRenderObservable.clear();
  95174. this.onBeforeRenderObservable.clear();
  95175. };
  95176. return Layer;
  95177. }());
  95178. BABYLON.Layer = Layer;
  95179. })(BABYLON || (BABYLON = {}));
  95180. //# sourceMappingURL=babylon.layer.js.map
  95181. var BABYLON;
  95182. (function (BABYLON) {
  95183. var TextureTools = /** @class */ (function () {
  95184. function TextureTools() {
  95185. }
  95186. /**
  95187. * Uses the GPU to create a copy texture rescaled at a given size
  95188. * @param texture Texture to copy from
  95189. * @param width Desired width
  95190. * @param height Desired height
  95191. * @return Generated texture
  95192. */
  95193. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  95194. if (useBilinearMode === void 0) { useBilinearMode = true; }
  95195. var scene = texture.getScene();
  95196. var engine = scene.getEngine();
  95197. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  95198. rtt.wrapU = texture.wrapU;
  95199. rtt.wrapV = texture.wrapV;
  95200. rtt.uOffset = texture.uOffset;
  95201. rtt.vOffset = texture.vOffset;
  95202. rtt.uScale = texture.uScale;
  95203. rtt.vScale = texture.vScale;
  95204. rtt.uAng = texture.uAng;
  95205. rtt.vAng = texture.vAng;
  95206. rtt.wAng = texture.wAng;
  95207. rtt.coordinatesIndex = texture.coordinatesIndex;
  95208. rtt.level = texture.level;
  95209. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  95210. rtt._texture.isReady = false;
  95211. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95212. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95213. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95214. passPostProcess.getEffect().executeWhenCompiled(function () {
  95215. passPostProcess.onApply = function (effect) {
  95216. effect.setTexture("textureSampler", texture);
  95217. };
  95218. var internalTexture = rtt.getInternalTexture();
  95219. if (internalTexture) {
  95220. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  95221. engine.unBindFramebuffer(internalTexture);
  95222. rtt.disposeFramebufferObjects();
  95223. passPostProcess.dispose();
  95224. internalTexture.isReady = true;
  95225. }
  95226. });
  95227. return rtt;
  95228. };
  95229. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  95230. if (!scene._environmentBRDFTexture) {
  95231. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95232. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95233. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95234. scene._environmentBRDFTexture = texture;
  95235. }
  95236. return scene._environmentBRDFTexture;
  95237. };
  95238. 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=";
  95239. return TextureTools;
  95240. }());
  95241. BABYLON.TextureTools = TextureTools;
  95242. })(BABYLON || (BABYLON = {}));
  95243. //# sourceMappingURL=babylon.textureTools.js.map
  95244. var BABYLON;
  95245. (function (BABYLON) {
  95246. var FramingBehavior = /** @class */ (function () {
  95247. function FramingBehavior() {
  95248. this._mode = FramingBehavior.FitFrustumSidesMode;
  95249. this._radiusScale = 1.0;
  95250. this._positionScale = 0.5;
  95251. this._defaultElevation = 0.3;
  95252. this._elevationReturnTime = 1500;
  95253. this._elevationReturnWaitTime = 1000;
  95254. this._zoomStopsAnimation = false;
  95255. this._framingTime = 1500;
  95256. this._isPointerDown = false;
  95257. this._lastInteractionTime = -Infinity;
  95258. // Framing control
  95259. this._animatables = new Array();
  95260. this._betaIsAnimating = false;
  95261. }
  95262. Object.defineProperty(FramingBehavior.prototype, "name", {
  95263. get: function () {
  95264. return "Framing";
  95265. },
  95266. enumerable: true,
  95267. configurable: true
  95268. });
  95269. Object.defineProperty(FramingBehavior.prototype, "mode", {
  95270. /**
  95271. * Gets current mode used by the behavior.
  95272. */
  95273. get: function () {
  95274. return this._mode;
  95275. },
  95276. /**
  95277. * Sets the current mode used by the behavior
  95278. */
  95279. set: function (mode) {
  95280. this._mode = mode;
  95281. },
  95282. enumerable: true,
  95283. configurable: true
  95284. });
  95285. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  95286. /**
  95287. * Gets the scale applied to the radius
  95288. */
  95289. get: function () {
  95290. return this._radiusScale;
  95291. },
  95292. /**
  95293. * Sets the scale applied to the radius (1 by default)
  95294. */
  95295. set: function (radius) {
  95296. this._radiusScale = radius;
  95297. },
  95298. enumerable: true,
  95299. configurable: true
  95300. });
  95301. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  95302. /**
  95303. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95304. */
  95305. get: function () {
  95306. return this._positionScale;
  95307. },
  95308. /**
  95309. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95310. */
  95311. set: function (scale) {
  95312. this._positionScale = scale;
  95313. },
  95314. enumerable: true,
  95315. configurable: true
  95316. });
  95317. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  95318. /**
  95319. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95320. * behaviour is triggered, in radians.
  95321. */
  95322. get: function () {
  95323. return this._defaultElevation;
  95324. },
  95325. /**
  95326. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95327. * behaviour is triggered, in radians.
  95328. */
  95329. set: function (elevation) {
  95330. this._defaultElevation = elevation;
  95331. },
  95332. enumerable: true,
  95333. configurable: true
  95334. });
  95335. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  95336. /**
  95337. * Gets the time (in milliseconds) taken to return to the default beta position.
  95338. * Negative value indicates camera should not return to default.
  95339. */
  95340. get: function () {
  95341. return this._elevationReturnTime;
  95342. },
  95343. /**
  95344. * Sets the time (in milliseconds) taken to return to the default beta position.
  95345. * Negative value indicates camera should not return to default.
  95346. */
  95347. set: function (speed) {
  95348. this._elevationReturnTime = speed;
  95349. },
  95350. enumerable: true,
  95351. configurable: true
  95352. });
  95353. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  95354. /**
  95355. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95356. */
  95357. get: function () {
  95358. return this._elevationReturnWaitTime;
  95359. },
  95360. /**
  95361. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95362. */
  95363. set: function (time) {
  95364. this._elevationReturnWaitTime = time;
  95365. },
  95366. enumerable: true,
  95367. configurable: true
  95368. });
  95369. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  95370. /**
  95371. * Gets the flag that indicates if user zooming should stop animation.
  95372. */
  95373. get: function () {
  95374. return this._zoomStopsAnimation;
  95375. },
  95376. /**
  95377. * Sets the flag that indicates if user zooming should stop animation.
  95378. */
  95379. set: function (flag) {
  95380. this._zoomStopsAnimation = flag;
  95381. },
  95382. enumerable: true,
  95383. configurable: true
  95384. });
  95385. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95386. /**
  95387. * Gets the transition time when framing the mesh, in milliseconds
  95388. */
  95389. get: function () {
  95390. return this._framingTime;
  95391. },
  95392. /**
  95393. * Sets the transition time when framing the mesh, in milliseconds
  95394. */
  95395. set: function (time) {
  95396. this._framingTime = time;
  95397. },
  95398. enumerable: true,
  95399. configurable: true
  95400. });
  95401. FramingBehavior.prototype.init = function () {
  95402. // Do notihng
  95403. };
  95404. FramingBehavior.prototype.attach = function (camera) {
  95405. var _this = this;
  95406. this._attachedCamera = camera;
  95407. var scene = this._attachedCamera.getScene();
  95408. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95409. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95410. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95411. _this._isPointerDown = true;
  95412. return;
  95413. }
  95414. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95415. _this._isPointerDown = false;
  95416. }
  95417. });
  95418. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95419. if (mesh) {
  95420. _this.zoomOnMesh(mesh);
  95421. }
  95422. });
  95423. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95424. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95425. _this._applyUserInteraction();
  95426. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95427. // back to the default position after a given timeout
  95428. _this._maintainCameraAboveGround();
  95429. });
  95430. };
  95431. FramingBehavior.prototype.detach = function () {
  95432. if (!this._attachedCamera) {
  95433. return;
  95434. }
  95435. var scene = this._attachedCamera.getScene();
  95436. if (this._onPrePointerObservableObserver) {
  95437. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95438. }
  95439. if (this._onAfterCheckInputsObserver) {
  95440. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95441. }
  95442. if (this._onMeshTargetChangedObserver) {
  95443. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95444. }
  95445. this._attachedCamera = null;
  95446. };
  95447. /**
  95448. * Targets the given mesh and updates zoom level accordingly.
  95449. * @param mesh The mesh to target.
  95450. * @param radius Optional. If a cached radius position already exists, overrides default.
  95451. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95452. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95453. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95454. */
  95455. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95456. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95457. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95458. mesh.computeWorldMatrix(true);
  95459. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95460. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95461. };
  95462. /**
  95463. * Targets the given mesh with its children and updates zoom level accordingly.
  95464. * @param mesh The mesh to target.
  95465. * @param radius Optional. If a cached radius position already exists, overrides default.
  95466. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95467. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95468. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95469. */
  95470. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95471. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95472. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95473. mesh.computeWorldMatrix(true);
  95474. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95475. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95476. };
  95477. /**
  95478. * Targets the given meshes with their children and updates zoom level accordingly.
  95479. * @param meshes The mesh to target.
  95480. * @param radius Optional. If a cached radius position already exists, overrides default.
  95481. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95482. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95483. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95484. */
  95485. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95486. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95487. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95488. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95489. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95490. for (var i = 0; i < meshes.length; i++) {
  95491. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95492. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95493. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95494. }
  95495. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95496. };
  95497. /**
  95498. * Targets the given mesh and updates zoom level accordingly.
  95499. * @param mesh The mesh to target.
  95500. * @param radius Optional. If a cached radius position already exists, overrides default.
  95501. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95502. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95503. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95504. */
  95505. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95506. var _this = this;
  95507. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95508. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95509. var zoomTarget;
  95510. if (!this._attachedCamera) {
  95511. return;
  95512. }
  95513. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95514. var bottom = minimumWorld.y;
  95515. var top = maximumWorld.y;
  95516. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95517. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95518. if (focusOnOriginXZ) {
  95519. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95520. }
  95521. else {
  95522. var centerWorld = minimumWorld.add(radiusWorld);
  95523. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95524. }
  95525. if (!this._vectorTransition) {
  95526. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95527. }
  95528. this._betaIsAnimating = true;
  95529. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95530. if (animatable) {
  95531. this._animatables.push(animatable);
  95532. }
  95533. // sets the radius and lower radius bounds
  95534. // Small delta ensures camera is not always at lower zoom limit.
  95535. var radius = 0;
  95536. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95537. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95538. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95539. radius = position;
  95540. }
  95541. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95542. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95543. if (this._attachedCamera.lowerRadiusLimit === null) {
  95544. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95545. }
  95546. }
  95547. // Set sensibilities
  95548. var extend = maximumWorld.subtract(minimumWorld).length();
  95549. this._attachedCamera.panningSensibility = 5000 / extend;
  95550. this._attachedCamera.wheelPrecision = 100 / radius;
  95551. // transition to new radius
  95552. if (!this._radiusTransition) {
  95553. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95554. }
  95555. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95556. _this.stopAllAnimations();
  95557. if (onAnimationEnd) {
  95558. onAnimationEnd();
  95559. }
  95560. if (_this._attachedCamera) {
  95561. _this._attachedCamera.storeState();
  95562. }
  95563. });
  95564. if (animatable) {
  95565. this._animatables.push(animatable);
  95566. }
  95567. };
  95568. /**
  95569. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95570. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95571. * frustum width.
  95572. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95573. * to fully enclose the mesh in the viewing frustum.
  95574. */
  95575. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95576. var size = maximumWorld.subtract(minimumWorld);
  95577. var boxVectorGlobalDiagonal = size.length();
  95578. var frustumSlope = this._getFrustumSlope();
  95579. // Formula for setting distance
  95580. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95581. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95582. // Horizon distance
  95583. var radius = radiusWithoutFraming * this._radiusScale;
  95584. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95585. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95586. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95587. var camera = this._attachedCamera;
  95588. if (!camera) {
  95589. return 0;
  95590. }
  95591. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95592. // Don't exceed the requested limit
  95593. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95594. }
  95595. // Don't exceed the upper radius limit
  95596. if (camera.upperRadiusLimit) {
  95597. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95598. }
  95599. return distance;
  95600. };
  95601. /**
  95602. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95603. * is automatically returned to its default position (expected to be above ground plane).
  95604. */
  95605. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95606. var _this = this;
  95607. if (this._elevationReturnTime < 0) {
  95608. return;
  95609. }
  95610. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95611. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95612. var limitBeta = Math.PI * 0.5;
  95613. // Bring the camera back up if below the ground plane
  95614. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95615. this._betaIsAnimating = true;
  95616. //Transition to new position
  95617. this.stopAllAnimations();
  95618. if (!this._betaTransition) {
  95619. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95620. }
  95621. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95622. _this._clearAnimationLocks();
  95623. _this.stopAllAnimations();
  95624. });
  95625. if (animatabe) {
  95626. this._animatables.push(animatabe);
  95627. }
  95628. }
  95629. };
  95630. /**
  95631. * Returns the frustum slope based on the canvas ratio and camera FOV
  95632. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95633. */
  95634. FramingBehavior.prototype._getFrustumSlope = function () {
  95635. // Calculate the viewport ratio
  95636. // Aspect Ratio is Height/Width.
  95637. var camera = this._attachedCamera;
  95638. if (!camera) {
  95639. return BABYLON.Vector2.Zero();
  95640. }
  95641. var engine = camera.getScene().getEngine();
  95642. var aspectRatio = engine.getAspectRatio(camera);
  95643. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95644. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95645. var frustumSlopeY = Math.tan(camera.fov / 2);
  95646. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95647. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95648. // along the forward vector.
  95649. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95650. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95651. };
  95652. /**
  95653. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95654. */
  95655. FramingBehavior.prototype._clearAnimationLocks = function () {
  95656. this._betaIsAnimating = false;
  95657. };
  95658. /**
  95659. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95660. */
  95661. FramingBehavior.prototype._applyUserInteraction = function () {
  95662. if (this.isUserIsMoving) {
  95663. this._lastInteractionTime = BABYLON.Tools.Now;
  95664. this.stopAllAnimations();
  95665. this._clearAnimationLocks();
  95666. }
  95667. };
  95668. /**
  95669. * Stops and removes all animations that have been applied to the camera
  95670. */
  95671. FramingBehavior.prototype.stopAllAnimations = function () {
  95672. if (this._attachedCamera) {
  95673. this._attachedCamera.animations = [];
  95674. }
  95675. while (this._animatables.length) {
  95676. if (this._animatables[0]) {
  95677. this._animatables[0].onAnimationEnd = null;
  95678. this._animatables[0].stop();
  95679. }
  95680. this._animatables.shift();
  95681. }
  95682. };
  95683. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95684. /**
  95685. * Gets a value indicating if the user is moving the camera
  95686. */
  95687. get: function () {
  95688. if (!this._attachedCamera) {
  95689. return false;
  95690. }
  95691. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95692. this._attachedCamera.inertialBetaOffset !== 0 ||
  95693. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95694. this._attachedCamera.inertialPanningX !== 0 ||
  95695. this._attachedCamera.inertialPanningY !== 0 ||
  95696. this._isPointerDown;
  95697. },
  95698. enumerable: true,
  95699. configurable: true
  95700. });
  95701. /**
  95702. * The easing function used by animations
  95703. */
  95704. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95705. /**
  95706. * The easing mode used by animations
  95707. */
  95708. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95709. // Statics
  95710. /**
  95711. * The camera can move all the way towards the mesh.
  95712. */
  95713. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95714. /**
  95715. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95716. */
  95717. FramingBehavior.FitFrustumSidesMode = 1;
  95718. return FramingBehavior;
  95719. }());
  95720. BABYLON.FramingBehavior = FramingBehavior;
  95721. })(BABYLON || (BABYLON = {}));
  95722. //# sourceMappingURL=babylon.framingBehavior.js.map
  95723. var BABYLON;
  95724. (function (BABYLON) {
  95725. /**
  95726. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95727. */
  95728. var BouncingBehavior = /** @class */ (function () {
  95729. function BouncingBehavior() {
  95730. /**
  95731. * The duration of the animation, in milliseconds
  95732. */
  95733. this.transitionDuration = 450;
  95734. /**
  95735. * Length of the distance animated by the transition when lower radius is reached
  95736. */
  95737. this.lowerRadiusTransitionRange = 2;
  95738. /**
  95739. * Length of the distance animated by the transition when upper radius is reached
  95740. */
  95741. this.upperRadiusTransitionRange = -2;
  95742. this._autoTransitionRange = false;
  95743. // Animations
  95744. this._radiusIsAnimating = false;
  95745. this._radiusBounceTransition = null;
  95746. this._animatables = new Array();
  95747. }
  95748. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95749. get: function () {
  95750. return "Bouncing";
  95751. },
  95752. enumerable: true,
  95753. configurable: true
  95754. });
  95755. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95756. /**
  95757. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95758. */
  95759. get: function () {
  95760. return this._autoTransitionRange;
  95761. },
  95762. /**
  95763. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95764. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95765. */
  95766. set: function (value) {
  95767. var _this = this;
  95768. if (this._autoTransitionRange === value) {
  95769. return;
  95770. }
  95771. this._autoTransitionRange = value;
  95772. var camera = this._attachedCamera;
  95773. if (!camera) {
  95774. return;
  95775. }
  95776. if (value) {
  95777. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95778. if (!mesh) {
  95779. return;
  95780. }
  95781. mesh.computeWorldMatrix(true);
  95782. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95783. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95784. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95785. });
  95786. }
  95787. else if (this._onMeshTargetChangedObserver) {
  95788. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95789. }
  95790. },
  95791. enumerable: true,
  95792. configurable: true
  95793. });
  95794. BouncingBehavior.prototype.init = function () {
  95795. // Do notihng
  95796. };
  95797. BouncingBehavior.prototype.attach = function (camera) {
  95798. var _this = this;
  95799. this._attachedCamera = camera;
  95800. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95801. if (!_this._attachedCamera) {
  95802. return;
  95803. }
  95804. // Add the bounce animation to the lower radius limit
  95805. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95806. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95807. }
  95808. // Add the bounce animation to the upper radius limit
  95809. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95810. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95811. }
  95812. });
  95813. };
  95814. BouncingBehavior.prototype.detach = function () {
  95815. if (!this._attachedCamera) {
  95816. return;
  95817. }
  95818. if (this._onAfterCheckInputsObserver) {
  95819. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95820. }
  95821. if (this._onMeshTargetChangedObserver) {
  95822. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95823. }
  95824. this._attachedCamera = null;
  95825. };
  95826. /**
  95827. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95828. * @param radiusLimit The limit to check against.
  95829. * @return Bool to indicate if at limit.
  95830. */
  95831. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95832. if (!this._attachedCamera) {
  95833. return false;
  95834. }
  95835. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95836. return true;
  95837. }
  95838. return false;
  95839. };
  95840. /**
  95841. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95842. * @param radiusDelta The delta by which to animate to. Can be negative.
  95843. */
  95844. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95845. var _this = this;
  95846. if (!this._attachedCamera) {
  95847. return;
  95848. }
  95849. if (!this._radiusBounceTransition) {
  95850. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95851. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95852. }
  95853. // Prevent zoom until bounce has completed
  95854. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95855. this._attachedCamera.wheelPrecision = Infinity;
  95856. this._attachedCamera.inertialRadiusOffset = 0;
  95857. // Animate to the radius limit
  95858. this.stopAllAnimations();
  95859. this._radiusIsAnimating = true;
  95860. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95861. if (animatable) {
  95862. this._animatables.push(animatable);
  95863. }
  95864. };
  95865. /**
  95866. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95867. */
  95868. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95869. this._radiusIsAnimating = false;
  95870. if (this._attachedCamera) {
  95871. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95872. }
  95873. };
  95874. /**
  95875. * Stops and removes all animations that have been applied to the camera
  95876. */
  95877. BouncingBehavior.prototype.stopAllAnimations = function () {
  95878. if (this._attachedCamera) {
  95879. this._attachedCamera.animations = [];
  95880. }
  95881. while (this._animatables.length) {
  95882. this._animatables[0].onAnimationEnd = null;
  95883. this._animatables[0].stop();
  95884. this._animatables.shift();
  95885. }
  95886. };
  95887. /**
  95888. * The easing function used by animations
  95889. */
  95890. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95891. /**
  95892. * The easing mode used by animations
  95893. */
  95894. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95895. return BouncingBehavior;
  95896. }());
  95897. BABYLON.BouncingBehavior = BouncingBehavior;
  95898. })(BABYLON || (BABYLON = {}));
  95899. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95900. var BABYLON;
  95901. (function (BABYLON) {
  95902. var AutoRotationBehavior = /** @class */ (function () {
  95903. function AutoRotationBehavior() {
  95904. this._zoomStopsAnimation = false;
  95905. this._idleRotationSpeed = 0.05;
  95906. this._idleRotationWaitTime = 2000;
  95907. this._idleRotationSpinupTime = 2000;
  95908. this._isPointerDown = false;
  95909. this._lastFrameTime = null;
  95910. this._lastInteractionTime = -Infinity;
  95911. this._cameraRotationSpeed = 0;
  95912. this._lastFrameRadius = 0;
  95913. }
  95914. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95915. get: function () {
  95916. return "AutoRotation";
  95917. },
  95918. enumerable: true,
  95919. configurable: true
  95920. });
  95921. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95922. /**
  95923. * Gets the flag that indicates if user zooming should stop animation.
  95924. */
  95925. get: function () {
  95926. return this._zoomStopsAnimation;
  95927. },
  95928. /**
  95929. * Sets the flag that indicates if user zooming should stop animation.
  95930. */
  95931. set: function (flag) {
  95932. this._zoomStopsAnimation = flag;
  95933. },
  95934. enumerable: true,
  95935. configurable: true
  95936. });
  95937. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95938. /**
  95939. * Gets the default speed at which the camera rotates around the model.
  95940. */
  95941. get: function () {
  95942. return this._idleRotationSpeed;
  95943. },
  95944. /**
  95945. * Sets the default speed at which the camera rotates around the model.
  95946. */
  95947. set: function (speed) {
  95948. this._idleRotationSpeed = speed;
  95949. },
  95950. enumerable: true,
  95951. configurable: true
  95952. });
  95953. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95954. /**
  95955. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95956. */
  95957. get: function () {
  95958. return this._idleRotationWaitTime;
  95959. },
  95960. /**
  95961. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95962. */
  95963. set: function (time) {
  95964. this._idleRotationWaitTime = time;
  95965. },
  95966. enumerable: true,
  95967. configurable: true
  95968. });
  95969. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95970. /**
  95971. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95972. */
  95973. get: function () {
  95974. return this._idleRotationSpinupTime;
  95975. },
  95976. /**
  95977. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95978. */
  95979. set: function (time) {
  95980. this._idleRotationSpinupTime = time;
  95981. },
  95982. enumerable: true,
  95983. configurable: true
  95984. });
  95985. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95986. /**
  95987. * Gets a value indicating if the camera is currently rotating because of this behavior
  95988. */
  95989. get: function () {
  95990. return Math.abs(this._cameraRotationSpeed) > 0;
  95991. },
  95992. enumerable: true,
  95993. configurable: true
  95994. });
  95995. AutoRotationBehavior.prototype.init = function () {
  95996. // Do notihng
  95997. };
  95998. AutoRotationBehavior.prototype.attach = function (camera) {
  95999. var _this = this;
  96000. this._attachedCamera = camera;
  96001. var scene = this._attachedCamera.getScene();
  96002. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96003. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96004. _this._isPointerDown = true;
  96005. return;
  96006. }
  96007. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96008. _this._isPointerDown = false;
  96009. }
  96010. });
  96011. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96012. var now = BABYLON.Tools.Now;
  96013. var dt = 0;
  96014. if (_this._lastFrameTime != null) {
  96015. dt = now - _this._lastFrameTime;
  96016. }
  96017. _this._lastFrameTime = now;
  96018. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96019. _this._applyUserInteraction();
  96020. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  96021. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  96022. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  96023. // Step camera rotation by rotation speed
  96024. if (_this._attachedCamera) {
  96025. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  96026. }
  96027. });
  96028. };
  96029. AutoRotationBehavior.prototype.detach = function () {
  96030. if (!this._attachedCamera) {
  96031. return;
  96032. }
  96033. var scene = this._attachedCamera.getScene();
  96034. if (this._onPrePointerObservableObserver) {
  96035. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96036. }
  96037. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96038. this._attachedCamera = null;
  96039. };
  96040. /**
  96041. * Returns true if user is scrolling.
  96042. * @return true if user is scrolling.
  96043. */
  96044. AutoRotationBehavior.prototype._userIsZooming = function () {
  96045. if (!this._attachedCamera) {
  96046. return false;
  96047. }
  96048. return this._attachedCamera.inertialRadiusOffset !== 0;
  96049. };
  96050. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  96051. if (!this._attachedCamera) {
  96052. return false;
  96053. }
  96054. var zoomHasHitLimit = false;
  96055. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  96056. zoomHasHitLimit = true;
  96057. }
  96058. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  96059. this._lastFrameRadius = this._attachedCamera.radius;
  96060. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  96061. };
  96062. /**
  96063. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96064. */
  96065. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  96066. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  96067. this._lastInteractionTime = BABYLON.Tools.Now;
  96068. }
  96069. };
  96070. // Tools
  96071. AutoRotationBehavior.prototype._userIsMoving = function () {
  96072. if (!this._attachedCamera) {
  96073. return false;
  96074. }
  96075. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96076. this._attachedCamera.inertialBetaOffset !== 0 ||
  96077. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96078. this._attachedCamera.inertialPanningX !== 0 ||
  96079. this._attachedCamera.inertialPanningY !== 0 ||
  96080. this._isPointerDown;
  96081. };
  96082. return AutoRotationBehavior;
  96083. }());
  96084. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  96085. })(BABYLON || (BABYLON = {}));
  96086. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  96087. var BABYLON;
  96088. (function (BABYLON) {
  96089. /**
  96090. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  96091. */
  96092. var PointerDragBehavior = /** @class */ (function () {
  96093. /**
  96094. * Creates a pointer drag behavior that can be attached to a mesh
  96095. * @param options The drag axis or normal of the plane that will be dragged across. pointerObservableScene can be used to listen to drag events from another scene(eg. if the attached mesh is in an overlay scene).
  96096. */
  96097. function PointerDragBehavior(options) {
  96098. this.options = options;
  96099. this._draggingID = -1;
  96100. /**
  96101. * Fires each time the attached mesh is dragged with the pointer
  96102. */
  96103. this.onDragObservable = new BABYLON.Observable();
  96104. /**
  96105. * Fires each time a drag begins (eg. mouse down on mesh)
  96106. */
  96107. this.onDragStartObservable = new BABYLON.Observable();
  96108. /**
  96109. * Fires each time a drag ends (eg. mouse release after drag)
  96110. */
  96111. this.onDragEndObservable = new BABYLON.Observable();
  96112. /**
  96113. * If the attached mesh should be moved when dragged
  96114. */
  96115. this.moveAttached = true;
  96116. /**
  96117. * Mesh with the position where the drag plane should be placed
  96118. */
  96119. this._dragPlaneParent = null;
  96120. /**
  96121. * If the drag behavior will react to drag events
  96122. */
  96123. this.enabled = true;
  96124. var optionCount = 0;
  96125. if (options.dragAxis) {
  96126. optionCount++;
  96127. }
  96128. if (options.dragPlaneNormal) {
  96129. optionCount++;
  96130. }
  96131. if (optionCount > 1) {
  96132. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  96133. }
  96134. if (optionCount < 1) {
  96135. throw "At least one drag mode option must be specified";
  96136. }
  96137. }
  96138. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  96139. /**
  96140. * The name of the behavior
  96141. */
  96142. get: function () {
  96143. return "PointerDrag";
  96144. },
  96145. enumerable: true,
  96146. configurable: true
  96147. });
  96148. /**
  96149. * Initializes the behavior
  96150. */
  96151. PointerDragBehavior.prototype.init = function () { };
  96152. /**
  96153. * Attaches the drag behavior the passed in mesh
  96154. * @param ownerNode The mesh that will be dragged around once attached
  96155. */
  96156. PointerDragBehavior.prototype.attach = function (ownerNode) {
  96157. var _this = this;
  96158. this._scene = ownerNode.getScene();
  96159. if (!this.options.pointerObservableScene) {
  96160. this.options.pointerObservableScene = this._scene;
  96161. }
  96162. this._attachedNode = ownerNode;
  96163. // Initialize drag plane to not interfere with existing scene
  96164. if (!PointerDragBehavior._planeScene) {
  96165. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  96166. this._scene.getEngine().scenes.pop();
  96167. }
  96168. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  96169. // State of the drag
  96170. var dragging = false;
  96171. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  96172. var delta = new BABYLON.Vector3(0, 0, 0);
  96173. var pickPredicate = function (m) {
  96174. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  96175. };
  96176. this._pointerObserver = this.options.pointerObservableScene.onPrePointerObservable.add(function (pointerInfoPre, eventState) {
  96177. if (!_this.enabled) {
  96178. return;
  96179. }
  96180. // Check if attached mesh is picked
  96181. var pickInfo = pointerInfoPre.ray ? _this._scene.pickWithRay(pointerInfoPre.ray, pickPredicate) : _this._scene.pick(_this._scene.pointerX, _this._scene.pointerY, pickPredicate);
  96182. if (pickInfo) {
  96183. pickInfo.ray = pointerInfoPre.ray;
  96184. if (!pickInfo.ray) {
  96185. pickInfo.ray = _this.options.pointerObservableScene.createPickingRay(_this._scene.pointerX, _this._scene.pointerY, BABYLON.Matrix.Identity(), _this._scene.activeCamera);
  96186. }
  96187. if (pickInfo.hit && pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96188. pointerInfoPre.skipOnPointerObservable = true;
  96189. }
  96190. }
  96191. if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96192. if (!dragging && pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.ray) {
  96193. _this._updateDragPlanePosition(pickInfo.ray);
  96194. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  96195. if (pickedPoint) {
  96196. dragging = true;
  96197. _this._draggingID = pointerInfoPre.event.pointerId;
  96198. lastPosition.copyFrom(pickedPoint);
  96199. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  96200. }
  96201. }
  96202. }
  96203. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERUP) {
  96204. if (_this._draggingID == pointerInfoPre.event.pointerId) {
  96205. dragging = false;
  96206. _this._draggingID = -1;
  96207. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  96208. }
  96209. }
  96210. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96211. if (_this._draggingID == pointerInfoPre.event.pointerId && dragging && pickInfo && pickInfo.ray) {
  96212. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  96213. _this._updateDragPlanePosition(pickInfo.ray);
  96214. if (pickedPoint) {
  96215. // depending on the drag mode option drag accordingly
  96216. if (_this.options.dragAxis) {
  96217. //get the closest point on the dragaxis from the selected mesh to the picked point location
  96218. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  96219. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  96220. }
  96221. else {
  96222. pickedPoint.subtractToRef(lastPosition, delta);
  96223. }
  96224. if (_this.moveAttached) {
  96225. _this._attachedNode.position.addInPlace(delta);
  96226. }
  96227. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  96228. lastPosition.copyFrom(pickedPoint);
  96229. }
  96230. }
  96231. }
  96232. });
  96233. };
  96234. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  96235. var _this = this;
  96236. if (!ray) {
  96237. return null;
  96238. }
  96239. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  96240. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  96241. return pickResult.pickedPoint;
  96242. }
  96243. else {
  96244. return null;
  96245. }
  96246. };
  96247. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  96248. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  96249. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  96250. if (this.options.dragAxis) {
  96251. var camPos = ray.origin;
  96252. // Calculate plane normal in direction of camera but perpendicular to drag axis
  96253. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  96254. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  96255. // Get perpendicular line from direction to camera and drag axis
  96256. var lineA = pointB.subtract(pointA);
  96257. var lineB = pointC.subtract(pointA);
  96258. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  96259. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  96260. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  96261. this._dragPlane.position.copyFrom(pointA);
  96262. this._dragPlane.lookAt(pointA.add(norm));
  96263. }
  96264. else if (this.options.dragPlaneNormal) {
  96265. this._dragPlane.position.copyFrom(pointA);
  96266. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  96267. }
  96268. this._dragPlane.computeWorldMatrix(true);
  96269. };
  96270. /**
  96271. * Detaches the behavior from the mesh
  96272. */
  96273. PointerDragBehavior.prototype.detach = function () {
  96274. if (this._pointerObserver) {
  96275. this._scene.onPrePointerObservable.remove(this._pointerObserver);
  96276. }
  96277. };
  96278. return PointerDragBehavior;
  96279. }());
  96280. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96281. })(BABYLON || (BABYLON = {}));
  96282. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96283. var BABYLON;
  96284. (function (BABYLON) {
  96285. var NullEngineOptions = /** @class */ (function () {
  96286. function NullEngineOptions() {
  96287. this.renderWidth = 512;
  96288. this.renderHeight = 256;
  96289. this.textureSize = 512;
  96290. this.deterministicLockstep = false;
  96291. this.lockstepMaxSteps = 4;
  96292. }
  96293. return NullEngineOptions;
  96294. }());
  96295. BABYLON.NullEngineOptions = NullEngineOptions;
  96296. /**
  96297. * The null engine class provides support for headless version of babylon.js.
  96298. * This can be used in server side scenario or for testing purposes
  96299. */
  96300. var NullEngine = /** @class */ (function (_super) {
  96301. __extends(NullEngine, _super);
  96302. function NullEngine(options) {
  96303. if (options === void 0) { options = new NullEngineOptions(); }
  96304. var _this = _super.call(this, null) || this;
  96305. if (options.deterministicLockstep === undefined) {
  96306. options.deterministicLockstep = false;
  96307. }
  96308. if (options.lockstepMaxSteps === undefined) {
  96309. options.lockstepMaxSteps = 4;
  96310. }
  96311. _this._options = options;
  96312. // Init caps
  96313. // We consider we are on a webgl1 capable device
  96314. _this._caps = new BABYLON.EngineCapabilities();
  96315. _this._caps.maxTexturesImageUnits = 16;
  96316. _this._caps.maxVertexTextureImageUnits = 16;
  96317. _this._caps.maxTextureSize = 512;
  96318. _this._caps.maxCubemapTextureSize = 512;
  96319. _this._caps.maxRenderTextureSize = 512;
  96320. _this._caps.maxVertexAttribs = 16;
  96321. _this._caps.maxVaryingVectors = 16;
  96322. _this._caps.maxFragmentUniformVectors = 16;
  96323. _this._caps.maxVertexUniformVectors = 16;
  96324. // Extensions
  96325. _this._caps.standardDerivatives = false;
  96326. _this._caps.astc = null;
  96327. _this._caps.s3tc = null;
  96328. _this._caps.pvrtc = null;
  96329. _this._caps.etc1 = null;
  96330. _this._caps.etc2 = null;
  96331. _this._caps.textureAnisotropicFilterExtension = null;
  96332. _this._caps.maxAnisotropy = 0;
  96333. _this._caps.uintIndices = false;
  96334. _this._caps.fragmentDepthSupported = false;
  96335. _this._caps.highPrecisionShaderSupported = true;
  96336. _this._caps.colorBufferFloat = false;
  96337. _this._caps.textureFloat = false;
  96338. _this._caps.textureFloatLinearFiltering = false;
  96339. _this._caps.textureFloatRender = false;
  96340. _this._caps.textureHalfFloat = false;
  96341. _this._caps.textureHalfFloatLinearFiltering = false;
  96342. _this._caps.textureHalfFloatRender = false;
  96343. _this._caps.textureLOD = false;
  96344. _this._caps.drawBuffersExtension = false;
  96345. _this._caps.depthTextureExtension = false;
  96346. _this._caps.vertexArrayObject = false;
  96347. _this._caps.instancedArrays = false;
  96348. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  96349. // Wrappers
  96350. if (typeof URL === "undefined") {
  96351. URL = {
  96352. createObjectURL: function () { },
  96353. revokeObjectURL: function () { }
  96354. };
  96355. }
  96356. if (typeof Blob === "undefined") {
  96357. Blob = function () { };
  96358. }
  96359. return _this;
  96360. }
  96361. NullEngine.prototype.isDeterministicLockStep = function () {
  96362. return this._options.deterministicLockstep;
  96363. };
  96364. NullEngine.prototype.getLockstepMaxSteps = function () {
  96365. return this._options.lockstepMaxSteps;
  96366. };
  96367. NullEngine.prototype.getHardwareScalingLevel = function () {
  96368. return 1.0;
  96369. };
  96370. NullEngine.prototype.createVertexBuffer = function (vertices) {
  96371. return {
  96372. capacity: 0,
  96373. references: 1,
  96374. is32Bits: false
  96375. };
  96376. };
  96377. NullEngine.prototype.createIndexBuffer = function (indices) {
  96378. return {
  96379. capacity: 0,
  96380. references: 1,
  96381. is32Bits: false
  96382. };
  96383. };
  96384. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96385. if (stencil === void 0) { stencil = false; }
  96386. };
  96387. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96388. if (useScreen === void 0) { useScreen = false; }
  96389. if (!useScreen && this._currentRenderTarget) {
  96390. return this._currentRenderTarget.width;
  96391. }
  96392. return this._options.renderWidth;
  96393. };
  96394. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96395. if (useScreen === void 0) { useScreen = false; }
  96396. if (!useScreen && this._currentRenderTarget) {
  96397. return this._currentRenderTarget.height;
  96398. }
  96399. return this._options.renderHeight;
  96400. };
  96401. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96402. this._cachedViewport = viewport;
  96403. };
  96404. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96405. return {
  96406. transformFeedback: null,
  96407. __SPECTOR_rebuildProgram: null
  96408. };
  96409. };
  96410. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96411. return [];
  96412. };
  96413. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96414. return [];
  96415. };
  96416. NullEngine.prototype.bindSamplers = function (effect) {
  96417. this._currentEffect = null;
  96418. };
  96419. NullEngine.prototype.enableEffect = function (effect) {
  96420. this._currentEffect = effect;
  96421. if (effect.onBind) {
  96422. effect.onBind(effect);
  96423. }
  96424. effect.onBindObservable.notifyObservers(effect);
  96425. };
  96426. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96427. if (zOffset === void 0) { zOffset = 0; }
  96428. if (reverseSide === void 0) { reverseSide = false; }
  96429. };
  96430. NullEngine.prototype.setIntArray = function (uniform, array) {
  96431. };
  96432. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96433. };
  96434. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96435. };
  96436. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96437. };
  96438. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96439. };
  96440. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96441. };
  96442. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96443. };
  96444. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96445. };
  96446. NullEngine.prototype.setArray = function (uniform, array) {
  96447. };
  96448. NullEngine.prototype.setArray2 = function (uniform, array) {
  96449. };
  96450. NullEngine.prototype.setArray3 = function (uniform, array) {
  96451. };
  96452. NullEngine.prototype.setArray4 = function (uniform, array) {
  96453. };
  96454. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96455. };
  96456. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96457. };
  96458. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96459. };
  96460. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96461. };
  96462. NullEngine.prototype.setFloat = function (uniform, value) {
  96463. };
  96464. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96465. };
  96466. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96467. };
  96468. NullEngine.prototype.setBool = function (uniform, bool) {
  96469. };
  96470. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96471. };
  96472. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96473. };
  96474. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96475. };
  96476. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96477. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96478. if (this._alphaMode === mode) {
  96479. return;
  96480. }
  96481. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96482. if (!noDepthWriteChange) {
  96483. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96484. }
  96485. this._alphaMode = mode;
  96486. };
  96487. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96488. };
  96489. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96490. if (this.preventCacheWipeBetweenFrames) {
  96491. return;
  96492. }
  96493. this.resetTextureCache();
  96494. this._currentEffect = null;
  96495. if (bruteForce) {
  96496. this._currentProgram = null;
  96497. this._stencilState.reset();
  96498. this._depthCullingState.reset();
  96499. this._alphaState.reset();
  96500. }
  96501. this._cachedVertexBuffers = null;
  96502. this._cachedIndexBuffer = null;
  96503. this._cachedEffectForVertexBuffers = null;
  96504. };
  96505. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96506. };
  96507. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96508. };
  96509. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96510. };
  96511. NullEngine.prototype._createTexture = function () {
  96512. return {};
  96513. };
  96514. NullEngine.prototype._releaseTexture = function (texture) {
  96515. };
  96516. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96518. if (onLoad === void 0) { onLoad = null; }
  96519. if (onError === void 0) { onError = null; }
  96520. if (buffer === void 0) { buffer = null; }
  96521. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96522. var url = String(urlArg);
  96523. texture.url = url;
  96524. texture.generateMipMaps = !noMipmap;
  96525. texture.samplingMode = samplingMode;
  96526. texture.invertY = invertY;
  96527. texture.baseWidth = this._options.textureSize;
  96528. texture.baseHeight = this._options.textureSize;
  96529. texture.width = this._options.textureSize;
  96530. texture.height = this._options.textureSize;
  96531. if (format) {
  96532. texture.format = format;
  96533. }
  96534. texture.isReady = true;
  96535. if (onLoad) {
  96536. onLoad();
  96537. }
  96538. this._internalTexturesCache.push(texture);
  96539. return texture;
  96540. };
  96541. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96542. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96543. if (options !== undefined && typeof options === "object") {
  96544. fullOptions.generateMipMaps = options.generateMipMaps;
  96545. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96546. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96547. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96548. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96549. }
  96550. else {
  96551. fullOptions.generateMipMaps = options;
  96552. fullOptions.generateDepthBuffer = true;
  96553. fullOptions.generateStencilBuffer = false;
  96554. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96555. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96556. }
  96557. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96558. var width = size.width || size;
  96559. var height = size.height || size;
  96560. texture._depthStencilBuffer = {};
  96561. texture._framebuffer = {};
  96562. texture.baseWidth = width;
  96563. texture.baseHeight = height;
  96564. texture.width = width;
  96565. texture.height = height;
  96566. texture.isReady = true;
  96567. texture.samples = 1;
  96568. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96569. texture.samplingMode = fullOptions.samplingMode;
  96570. texture.type = fullOptions.type;
  96571. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96572. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96573. this._internalTexturesCache.push(texture);
  96574. return texture;
  96575. };
  96576. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96577. texture.samplingMode = samplingMode;
  96578. };
  96579. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96580. if (this._currentRenderTarget) {
  96581. this.unBindFramebuffer(this._currentRenderTarget);
  96582. }
  96583. this._currentRenderTarget = texture;
  96584. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96585. if (this._cachedViewport && !forceFullscreenViewport) {
  96586. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96587. }
  96588. };
  96589. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96590. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96591. this._currentRenderTarget = null;
  96592. if (onBeforeUnbind) {
  96593. if (texture._MSAAFramebuffer) {
  96594. this._currentFramebuffer = texture._framebuffer;
  96595. }
  96596. onBeforeUnbind();
  96597. }
  96598. this._currentFramebuffer = null;
  96599. };
  96600. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96601. var vbo = {
  96602. capacity: 1,
  96603. references: 1,
  96604. is32Bits: false
  96605. };
  96606. return vbo;
  96607. };
  96608. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96609. if (offset === void 0) { offset = 0; }
  96610. };
  96611. /**
  96612. * Updates a dynamic vertex buffer.
  96613. * @param vertexBuffer the vertex buffer to update
  96614. * @param data the data used to update the vertex buffer
  96615. * @param byteOffset the byte offset of the data (optional)
  96616. * @param byteLength the byte length of the data (optional)
  96617. */
  96618. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96619. };
  96620. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96621. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96622. this._boundTexturesCache[this._activeChannel] = texture;
  96623. }
  96624. };
  96625. NullEngine.prototype._bindTexture = function (channel, texture) {
  96626. if (channel < 0) {
  96627. return;
  96628. }
  96629. this._bindTextureDirectly(0, texture);
  96630. };
  96631. NullEngine.prototype._releaseBuffer = function (buffer) {
  96632. buffer.references--;
  96633. if (buffer.references === 0) {
  96634. return true;
  96635. }
  96636. return false;
  96637. };
  96638. NullEngine.prototype.releaseEffects = function () {
  96639. };
  96640. return NullEngine;
  96641. }(BABYLON.Engine));
  96642. BABYLON.NullEngine = NullEngine;
  96643. })(BABYLON || (BABYLON = {}));
  96644. //# sourceMappingURL=babylon.nullEngine.js.map
  96645. var BABYLON;
  96646. (function (BABYLON) {
  96647. /**
  96648. * This class can be used to get instrumentation data from a Babylon engine
  96649. */
  96650. var EngineInstrumentation = /** @class */ (function () {
  96651. function EngineInstrumentation(engine) {
  96652. this.engine = engine;
  96653. this._captureGPUFrameTime = false;
  96654. this._gpuFrameTime = new BABYLON.PerfCounter();
  96655. this._captureShaderCompilationTime = false;
  96656. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96657. // Observers
  96658. this._onBeginFrameObserver = null;
  96659. this._onEndFrameObserver = null;
  96660. this._onBeforeShaderCompilationObserver = null;
  96661. this._onAfterShaderCompilationObserver = null;
  96662. }
  96663. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96664. // Properties
  96665. /**
  96666. * Gets the perf counter used for GPU frame time
  96667. */
  96668. get: function () {
  96669. return this._gpuFrameTime;
  96670. },
  96671. enumerable: true,
  96672. configurable: true
  96673. });
  96674. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96675. /**
  96676. * Gets the GPU frame time capture status
  96677. */
  96678. get: function () {
  96679. return this._captureGPUFrameTime;
  96680. },
  96681. /**
  96682. * Enable or disable the GPU frame time capture
  96683. */
  96684. set: function (value) {
  96685. var _this = this;
  96686. if (value === this._captureGPUFrameTime) {
  96687. return;
  96688. }
  96689. this._captureGPUFrameTime = value;
  96690. if (value) {
  96691. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96692. if (!_this._gpuFrameTimeToken) {
  96693. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96694. }
  96695. });
  96696. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96697. if (!_this._gpuFrameTimeToken) {
  96698. return;
  96699. }
  96700. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96701. if (time > -1) {
  96702. _this._gpuFrameTimeToken = null;
  96703. _this._gpuFrameTime.fetchNewFrame();
  96704. _this._gpuFrameTime.addCount(time, true);
  96705. }
  96706. });
  96707. }
  96708. else {
  96709. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96710. this._onBeginFrameObserver = null;
  96711. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96712. this._onEndFrameObserver = null;
  96713. }
  96714. },
  96715. enumerable: true,
  96716. configurable: true
  96717. });
  96718. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96719. /**
  96720. * Gets the perf counter used for shader compilation time
  96721. */
  96722. get: function () {
  96723. return this._shaderCompilationTime;
  96724. },
  96725. enumerable: true,
  96726. configurable: true
  96727. });
  96728. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96729. /**
  96730. * Gets the shader compilation time capture status
  96731. */
  96732. get: function () {
  96733. return this._captureShaderCompilationTime;
  96734. },
  96735. /**
  96736. * Enable or disable the shader compilation time capture
  96737. */
  96738. set: function (value) {
  96739. var _this = this;
  96740. if (value === this._captureShaderCompilationTime) {
  96741. return;
  96742. }
  96743. this._captureShaderCompilationTime = value;
  96744. if (value) {
  96745. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96746. _this._shaderCompilationTime.fetchNewFrame();
  96747. _this._shaderCompilationTime.beginMonitoring();
  96748. });
  96749. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96750. _this._shaderCompilationTime.endMonitoring();
  96751. });
  96752. }
  96753. else {
  96754. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96755. this._onBeforeShaderCompilationObserver = null;
  96756. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96757. this._onAfterShaderCompilationObserver = null;
  96758. }
  96759. },
  96760. enumerable: true,
  96761. configurable: true
  96762. });
  96763. EngineInstrumentation.prototype.dispose = function () {
  96764. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96765. this._onBeginFrameObserver = null;
  96766. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96767. this._onEndFrameObserver = null;
  96768. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96769. this._onBeforeShaderCompilationObserver = null;
  96770. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96771. this._onAfterShaderCompilationObserver = null;
  96772. this.engine = null;
  96773. };
  96774. return EngineInstrumentation;
  96775. }());
  96776. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96777. })(BABYLON || (BABYLON = {}));
  96778. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96779. var BABYLON;
  96780. (function (BABYLON) {
  96781. /**
  96782. * This class can be used to get instrumentation data from a Babylon engine
  96783. */
  96784. var SceneInstrumentation = /** @class */ (function () {
  96785. function SceneInstrumentation(scene) {
  96786. var _this = this;
  96787. this.scene = scene;
  96788. this._captureActiveMeshesEvaluationTime = false;
  96789. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96790. this._captureRenderTargetsRenderTime = false;
  96791. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96792. this._captureFrameTime = false;
  96793. this._frameTime = new BABYLON.PerfCounter();
  96794. this._captureRenderTime = false;
  96795. this._renderTime = new BABYLON.PerfCounter();
  96796. this._captureInterFrameTime = false;
  96797. this._interFrameTime = new BABYLON.PerfCounter();
  96798. this._captureParticlesRenderTime = false;
  96799. this._particlesRenderTime = new BABYLON.PerfCounter();
  96800. this._captureSpritesRenderTime = false;
  96801. this._spritesRenderTime = new BABYLON.PerfCounter();
  96802. this._capturePhysicsTime = false;
  96803. this._physicsTime = new BABYLON.PerfCounter();
  96804. this._captureAnimationsTime = false;
  96805. this._animationsTime = new BABYLON.PerfCounter();
  96806. // Observers
  96807. this._onBeforeActiveMeshesEvaluationObserver = null;
  96808. this._onAfterActiveMeshesEvaluationObserver = null;
  96809. this._onBeforeRenderTargetsRenderObserver = null;
  96810. this._onAfterRenderTargetsRenderObserver = null;
  96811. this._onAfterRenderObserver = null;
  96812. this._onBeforeDrawPhaseObserver = null;
  96813. this._onAfterDrawPhaseObserver = null;
  96814. this._onBeforeAnimationsObserver = null;
  96815. this._onBeforeParticlesRenderingObserver = null;
  96816. this._onAfterParticlesRenderingObserver = null;
  96817. this._onBeforeSpritesRenderingObserver = null;
  96818. this._onAfterSpritesRenderingObserver = null;
  96819. this._onBeforePhysicsObserver = null;
  96820. this._onAfterPhysicsObserver = null;
  96821. this._onAfterAnimationsObserver = null;
  96822. // Before render
  96823. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96824. if (_this._captureActiveMeshesEvaluationTime) {
  96825. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96826. }
  96827. if (_this._captureRenderTargetsRenderTime) {
  96828. _this._renderTargetsRenderTime.fetchNewFrame();
  96829. }
  96830. if (_this._captureFrameTime) {
  96831. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96832. _this._frameTime.beginMonitoring();
  96833. }
  96834. if (_this._captureInterFrameTime) {
  96835. _this._interFrameTime.endMonitoring();
  96836. }
  96837. if (_this._captureParticlesRenderTime) {
  96838. _this._particlesRenderTime.fetchNewFrame();
  96839. }
  96840. if (_this._captureSpritesRenderTime) {
  96841. _this._spritesRenderTime.fetchNewFrame();
  96842. }
  96843. if (_this._captureAnimationsTime) {
  96844. _this._animationsTime.beginMonitoring();
  96845. }
  96846. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96847. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96848. });
  96849. // After render
  96850. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96851. if (_this._captureFrameTime) {
  96852. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96853. _this._frameTime.endMonitoring();
  96854. }
  96855. if (_this._captureRenderTime) {
  96856. _this._renderTime.endMonitoring(false);
  96857. }
  96858. if (_this._captureInterFrameTime) {
  96859. _this._interFrameTime.beginMonitoring();
  96860. }
  96861. });
  96862. }
  96863. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96864. // Properties
  96865. /**
  96866. * Gets the perf counter used for active meshes evaluation time
  96867. */
  96868. get: function () {
  96869. return this._activeMeshesEvaluationTime;
  96870. },
  96871. enumerable: true,
  96872. configurable: true
  96873. });
  96874. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96875. /**
  96876. * Gets the active meshes evaluation time capture status
  96877. */
  96878. get: function () {
  96879. return this._captureActiveMeshesEvaluationTime;
  96880. },
  96881. /**
  96882. * Enable or disable the active meshes evaluation time capture
  96883. */
  96884. set: function (value) {
  96885. var _this = this;
  96886. if (value === this._captureActiveMeshesEvaluationTime) {
  96887. return;
  96888. }
  96889. this._captureActiveMeshesEvaluationTime = value;
  96890. if (value) {
  96891. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96892. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96893. _this._activeMeshesEvaluationTime.beginMonitoring();
  96894. });
  96895. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96896. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96897. _this._activeMeshesEvaluationTime.endMonitoring();
  96898. });
  96899. }
  96900. else {
  96901. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96902. this._onBeforeActiveMeshesEvaluationObserver = null;
  96903. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96904. this._onAfterActiveMeshesEvaluationObserver = null;
  96905. }
  96906. },
  96907. enumerable: true,
  96908. configurable: true
  96909. });
  96910. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96911. /**
  96912. * Gets the perf counter used for render targets render time
  96913. */
  96914. get: function () {
  96915. return this._renderTargetsRenderTime;
  96916. },
  96917. enumerable: true,
  96918. configurable: true
  96919. });
  96920. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96921. /**
  96922. * Gets the render targets render time capture status
  96923. */
  96924. get: function () {
  96925. return this._captureRenderTargetsRenderTime;
  96926. },
  96927. /**
  96928. * Enable or disable the render targets render time capture
  96929. */
  96930. set: function (value) {
  96931. var _this = this;
  96932. if (value === this._captureRenderTargetsRenderTime) {
  96933. return;
  96934. }
  96935. this._captureRenderTargetsRenderTime = value;
  96936. if (value) {
  96937. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96938. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96939. _this._renderTargetsRenderTime.beginMonitoring();
  96940. });
  96941. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96942. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96943. _this._renderTargetsRenderTime.endMonitoring(false);
  96944. });
  96945. }
  96946. else {
  96947. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96948. this._onBeforeRenderTargetsRenderObserver = null;
  96949. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96950. this._onAfterRenderTargetsRenderObserver = null;
  96951. }
  96952. },
  96953. enumerable: true,
  96954. configurable: true
  96955. });
  96956. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96957. /**
  96958. * Gets the perf counter used for particles render time
  96959. */
  96960. get: function () {
  96961. return this._particlesRenderTime;
  96962. },
  96963. enumerable: true,
  96964. configurable: true
  96965. });
  96966. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96967. /**
  96968. * Gets the particles render time capture status
  96969. */
  96970. get: function () {
  96971. return this._captureParticlesRenderTime;
  96972. },
  96973. /**
  96974. * Enable or disable the particles render time capture
  96975. */
  96976. set: function (value) {
  96977. var _this = this;
  96978. if (value === this._captureParticlesRenderTime) {
  96979. return;
  96980. }
  96981. this._captureParticlesRenderTime = value;
  96982. if (value) {
  96983. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96984. BABYLON.Tools.StartPerformanceCounter("Particles");
  96985. _this._particlesRenderTime.beginMonitoring();
  96986. });
  96987. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96988. BABYLON.Tools.EndPerformanceCounter("Particles");
  96989. _this._particlesRenderTime.endMonitoring(false);
  96990. });
  96991. }
  96992. else {
  96993. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96994. this._onBeforeParticlesRenderingObserver = null;
  96995. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96996. this._onAfterParticlesRenderingObserver = null;
  96997. }
  96998. },
  96999. enumerable: true,
  97000. configurable: true
  97001. });
  97002. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97003. /**
  97004. * Gets the perf counter used for sprites render time
  97005. */
  97006. get: function () {
  97007. return this._spritesRenderTime;
  97008. },
  97009. enumerable: true,
  97010. configurable: true
  97011. });
  97012. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97013. /**
  97014. * Gets the sprites render time capture status
  97015. */
  97016. get: function () {
  97017. return this._captureSpritesRenderTime;
  97018. },
  97019. /**
  97020. * Enable or disable the sprites render time capture
  97021. */
  97022. set: function (value) {
  97023. var _this = this;
  97024. if (value === this._captureSpritesRenderTime) {
  97025. return;
  97026. }
  97027. this._captureSpritesRenderTime = value;
  97028. if (value) {
  97029. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  97030. BABYLON.Tools.StartPerformanceCounter("Sprites");
  97031. _this._spritesRenderTime.beginMonitoring();
  97032. });
  97033. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  97034. BABYLON.Tools.EndPerformanceCounter("Sprites");
  97035. _this._spritesRenderTime.endMonitoring(false);
  97036. });
  97037. }
  97038. else {
  97039. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97040. this._onBeforeSpritesRenderingObserver = null;
  97041. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97042. this._onAfterSpritesRenderingObserver = null;
  97043. }
  97044. },
  97045. enumerable: true,
  97046. configurable: true
  97047. });
  97048. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  97049. /**
  97050. * Gets the perf counter used for physics time
  97051. */
  97052. get: function () {
  97053. return this._physicsTime;
  97054. },
  97055. enumerable: true,
  97056. configurable: true
  97057. });
  97058. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  97059. /**
  97060. * Gets the physics time capture status
  97061. */
  97062. get: function () {
  97063. return this._capturePhysicsTime;
  97064. },
  97065. /**
  97066. * Enable or disable the physics time capture
  97067. */
  97068. set: function (value) {
  97069. var _this = this;
  97070. if (value === this._capturePhysicsTime) {
  97071. return;
  97072. }
  97073. this._capturePhysicsTime = value;
  97074. if (value) {
  97075. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  97076. BABYLON.Tools.StartPerformanceCounter("Physics");
  97077. _this._physicsTime.beginMonitoring();
  97078. });
  97079. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  97080. BABYLON.Tools.EndPerformanceCounter("Physics");
  97081. _this._physicsTime.endMonitoring();
  97082. });
  97083. }
  97084. else {
  97085. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  97086. this._onBeforePhysicsObserver = null;
  97087. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  97088. this._onAfterPhysicsObserver = null;
  97089. }
  97090. },
  97091. enumerable: true,
  97092. configurable: true
  97093. });
  97094. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  97095. /**
  97096. * Gets the perf counter used for animations time
  97097. */
  97098. get: function () {
  97099. return this._animationsTime;
  97100. },
  97101. enumerable: true,
  97102. configurable: true
  97103. });
  97104. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  97105. /**
  97106. * Gets the animations time capture status
  97107. */
  97108. get: function () {
  97109. return this._captureAnimationsTime;
  97110. },
  97111. /**
  97112. * Enable or disable the animations time capture
  97113. */
  97114. set: function (value) {
  97115. var _this = this;
  97116. if (value === this._captureAnimationsTime) {
  97117. return;
  97118. }
  97119. this._captureAnimationsTime = value;
  97120. if (value) {
  97121. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  97122. _this._animationsTime.endMonitoring();
  97123. });
  97124. }
  97125. else {
  97126. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  97127. this._onAfterAnimationsObserver = null;
  97128. }
  97129. },
  97130. enumerable: true,
  97131. configurable: true
  97132. });
  97133. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  97134. /**
  97135. * Gets the perf counter used for frame time capture
  97136. */
  97137. get: function () {
  97138. return this._frameTime;
  97139. },
  97140. enumerable: true,
  97141. configurable: true
  97142. });
  97143. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  97144. /**
  97145. * Gets the frame time capture status
  97146. */
  97147. get: function () {
  97148. return this._captureFrameTime;
  97149. },
  97150. /**
  97151. * Enable or disable the frame time capture
  97152. */
  97153. set: function (value) {
  97154. this._captureFrameTime = value;
  97155. },
  97156. enumerable: true,
  97157. configurable: true
  97158. });
  97159. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  97160. /**
  97161. * Gets the perf counter used for inter-frames time capture
  97162. */
  97163. get: function () {
  97164. return this._interFrameTime;
  97165. },
  97166. enumerable: true,
  97167. configurable: true
  97168. });
  97169. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  97170. /**
  97171. * Gets the inter-frames time capture status
  97172. */
  97173. get: function () {
  97174. return this._captureInterFrameTime;
  97175. },
  97176. /**
  97177. * Enable or disable the inter-frames time capture
  97178. */
  97179. set: function (value) {
  97180. this._captureInterFrameTime = value;
  97181. },
  97182. enumerable: true,
  97183. configurable: true
  97184. });
  97185. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  97186. /**
  97187. * Gets the perf counter used for render time capture
  97188. */
  97189. get: function () {
  97190. return this._renderTime;
  97191. },
  97192. enumerable: true,
  97193. configurable: true
  97194. });
  97195. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  97196. /**
  97197. * Gets the render time capture status
  97198. */
  97199. get: function () {
  97200. return this._captureRenderTime;
  97201. },
  97202. /**
  97203. * Enable or disable the render time capture
  97204. */
  97205. set: function (value) {
  97206. var _this = this;
  97207. if (value === this._captureRenderTime) {
  97208. return;
  97209. }
  97210. this._captureRenderTime = value;
  97211. if (value) {
  97212. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  97213. _this._renderTime.beginMonitoring();
  97214. BABYLON.Tools.StartPerformanceCounter("Main render");
  97215. });
  97216. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  97217. _this._renderTime.endMonitoring(false);
  97218. BABYLON.Tools.EndPerformanceCounter("Main render");
  97219. });
  97220. }
  97221. else {
  97222. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  97223. this._onBeforeDrawPhaseObserver = null;
  97224. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  97225. this._onAfterDrawPhaseObserver = null;
  97226. }
  97227. },
  97228. enumerable: true,
  97229. configurable: true
  97230. });
  97231. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  97232. /**
  97233. * Gets the perf counter used for draw calls
  97234. */
  97235. get: function () {
  97236. return this.scene.getEngine()._drawCalls;
  97237. },
  97238. enumerable: true,
  97239. configurable: true
  97240. });
  97241. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  97242. /**
  97243. * Gets the perf counter used for texture collisions
  97244. */
  97245. get: function () {
  97246. return this.scene.getEngine()._textureCollisions;
  97247. },
  97248. enumerable: true,
  97249. configurable: true
  97250. });
  97251. SceneInstrumentation.prototype.dispose = function () {
  97252. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97253. this._onAfterRenderObserver = null;
  97254. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97255. this._onBeforeActiveMeshesEvaluationObserver = null;
  97256. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97257. this._onAfterActiveMeshesEvaluationObserver = null;
  97258. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97259. this._onBeforeRenderTargetsRenderObserver = null;
  97260. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97261. this._onAfterRenderTargetsRenderObserver = null;
  97262. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  97263. this._onBeforeAnimationsObserver = null;
  97264. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97265. this._onBeforeParticlesRenderingObserver = null;
  97266. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97267. this._onAfterParticlesRenderingObserver = null;
  97268. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97269. this._onBeforeSpritesRenderingObserver = null;
  97270. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97271. this._onAfterSpritesRenderingObserver = null;
  97272. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  97273. this._onBeforeDrawPhaseObserver = null;
  97274. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  97275. this._onAfterDrawPhaseObserver = null;
  97276. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  97277. this._onBeforePhysicsObserver = null;
  97278. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  97279. this._onAfterPhysicsObserver = null;
  97280. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  97281. this._onAfterAnimationsObserver = null;
  97282. this.scene = null;
  97283. };
  97284. return SceneInstrumentation;
  97285. }());
  97286. BABYLON.SceneInstrumentation = SceneInstrumentation;
  97287. })(BABYLON || (BABYLON = {}));
  97288. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  97289. var BABYLON;
  97290. (function (BABYLON) {
  97291. /**
  97292. * @hidden
  97293. **/
  97294. var _TimeToken = /** @class */ (function () {
  97295. function _TimeToken() {
  97296. this._timeElapsedQueryEnded = false;
  97297. }
  97298. return _TimeToken;
  97299. }());
  97300. BABYLON._TimeToken = _TimeToken;
  97301. })(BABYLON || (BABYLON = {}));
  97302. //# sourceMappingURL=babylon.timeToken.js.map
  97303. var BABYLON;
  97304. (function (BABYLON) {
  97305. /**
  97306. * Background material defines definition.
  97307. * @hidden Mainly internal Use
  97308. */
  97309. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  97310. __extends(BackgroundMaterialDefines, _super);
  97311. /**
  97312. * Constructor of the defines.
  97313. */
  97314. function BackgroundMaterialDefines() {
  97315. var _this = _super.call(this) || this;
  97316. /**
  97317. * True if the diffuse texture is in use.
  97318. */
  97319. _this.DIFFUSE = false;
  97320. /**
  97321. * The direct UV channel to use.
  97322. */
  97323. _this.DIFFUSEDIRECTUV = 0;
  97324. /**
  97325. * True if the diffuse texture is in gamma space.
  97326. */
  97327. _this.GAMMADIFFUSE = false;
  97328. /**
  97329. * True if the diffuse texture has opacity in the alpha channel.
  97330. */
  97331. _this.DIFFUSEHASALPHA = false;
  97332. /**
  97333. * True if you want the material to fade to transparent at grazing angle.
  97334. */
  97335. _this.OPACITYFRESNEL = false;
  97336. /**
  97337. * True if an extra blur needs to be added in the reflection.
  97338. */
  97339. _this.REFLECTIONBLUR = false;
  97340. /**
  97341. * True if you want the material to fade to reflection at grazing angle.
  97342. */
  97343. _this.REFLECTIONFRESNEL = false;
  97344. /**
  97345. * True if you want the material to falloff as far as you move away from the scene center.
  97346. */
  97347. _this.REFLECTIONFALLOFF = false;
  97348. /**
  97349. * False if the current Webgl implementation does not support the texture lod extension.
  97350. */
  97351. _this.TEXTURELODSUPPORT = false;
  97352. /**
  97353. * True to ensure the data are premultiplied.
  97354. */
  97355. _this.PREMULTIPLYALPHA = false;
  97356. /**
  97357. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  97358. */
  97359. _this.USERGBCOLOR = false;
  97360. /**
  97361. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  97362. * stays aligned with the desired configuration.
  97363. */
  97364. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  97365. /**
  97366. * True to add noise in order to reduce the banding effect.
  97367. */
  97368. _this.NOISE = false;
  97369. /**
  97370. * is the reflection texture in BGR color scheme?
  97371. * Mainly used to solve a bug in ios10 video tag
  97372. */
  97373. _this.REFLECTIONBGR = false;
  97374. _this.IMAGEPROCESSING = false;
  97375. _this.VIGNETTE = false;
  97376. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  97377. _this.VIGNETTEBLENDMODEOPAQUE = false;
  97378. _this.TONEMAPPING = false;
  97379. _this.CONTRAST = false;
  97380. _this.COLORCURVES = false;
  97381. _this.COLORGRADING = false;
  97382. _this.COLORGRADING3D = false;
  97383. _this.SAMPLER3DGREENDEPTH = false;
  97384. _this.SAMPLER3DBGRMAP = false;
  97385. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97386. _this.EXPOSURE = false;
  97387. // Reflection.
  97388. _this.REFLECTION = false;
  97389. _this.REFLECTIONMAP_3D = false;
  97390. _this.REFLECTIONMAP_SPHERICAL = false;
  97391. _this.REFLECTIONMAP_PLANAR = false;
  97392. _this.REFLECTIONMAP_CUBIC = false;
  97393. _this.REFLECTIONMAP_PROJECTION = false;
  97394. _this.REFLECTIONMAP_SKYBOX = false;
  97395. _this.REFLECTIONMAP_EXPLICIT = false;
  97396. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97397. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97398. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97399. _this.INVERTCUBICMAP = false;
  97400. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97401. _this.LODINREFLECTIONALPHA = false;
  97402. _this.GAMMAREFLECTION = false;
  97403. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97404. // Default BJS.
  97405. _this.MAINUV1 = false;
  97406. _this.MAINUV2 = false;
  97407. _this.UV1 = false;
  97408. _this.UV2 = false;
  97409. _this.CLIPPLANE = false;
  97410. _this.POINTSIZE = false;
  97411. _this.FOG = false;
  97412. _this.NORMAL = false;
  97413. _this.NUM_BONE_INFLUENCERS = 0;
  97414. _this.BonesPerMesh = 0;
  97415. _this.INSTANCES = false;
  97416. _this.SHADOWFLOAT = false;
  97417. _this.rebuild();
  97418. return _this;
  97419. }
  97420. return BackgroundMaterialDefines;
  97421. }(BABYLON.MaterialDefines));
  97422. /**
  97423. * Background material used to create an efficient environement around your scene.
  97424. */
  97425. var BackgroundMaterial = /** @class */ (function (_super) {
  97426. __extends(BackgroundMaterial, _super);
  97427. /**
  97428. * Instantiates a Background Material in the given scene
  97429. * @param name The friendly name of the material
  97430. * @param scene The scene to add the material to
  97431. */
  97432. function BackgroundMaterial(name, scene) {
  97433. var _this = _super.call(this, name, scene) || this;
  97434. /**
  97435. * Key light Color (multiply against the environement texture)
  97436. */
  97437. _this.primaryColor = BABYLON.Color3.White();
  97438. _this._primaryColorShadowLevel = 0;
  97439. _this._primaryColorHighlightLevel = 0;
  97440. /**
  97441. * Reflection Texture used in the material.
  97442. * Should be author in a specific way for the best result (refer to the documentation).
  97443. */
  97444. _this.reflectionTexture = null;
  97445. /**
  97446. * Reflection Texture level of blur.
  97447. *
  97448. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97449. * texture twice.
  97450. */
  97451. _this.reflectionBlur = 0;
  97452. /**
  97453. * Diffuse Texture used in the material.
  97454. * Should be author in a specific way for the best result (refer to the documentation).
  97455. */
  97456. _this.diffuseTexture = null;
  97457. _this._shadowLights = null;
  97458. /**
  97459. * Specify the list of lights casting shadow on the material.
  97460. * All scene shadow lights will be included if null.
  97461. */
  97462. _this.shadowLights = null;
  97463. /**
  97464. * Helps adjusting the shadow to a softer level if required.
  97465. * 0 means black shadows and 1 means no shadows.
  97466. */
  97467. _this.shadowLevel = 0;
  97468. /**
  97469. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97470. * It is usually zero but might be interesting to modify according to your setup.
  97471. */
  97472. _this.sceneCenter = BABYLON.Vector3.Zero();
  97473. /**
  97474. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97475. * This helps ensuring a nice transition when the camera goes under the ground.
  97476. */
  97477. _this.opacityFresnel = true;
  97478. /**
  97479. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97480. * This helps adding a mirror texture on the ground.
  97481. */
  97482. _this.reflectionFresnel = false;
  97483. /**
  97484. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97485. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97486. */
  97487. _this.reflectionFalloffDistance = 0.0;
  97488. /**
  97489. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97490. */
  97491. _this.reflectionAmount = 1.0;
  97492. /**
  97493. * This specifies the weight of the reflection at grazing angle.
  97494. */
  97495. _this.reflectionReflectance0 = 0.05;
  97496. /**
  97497. * This specifies the weight of the reflection at a perpendicular point of view.
  97498. */
  97499. _this.reflectionReflectance90 = 0.5;
  97500. /**
  97501. * Helps to directly use the maps channels instead of their level.
  97502. */
  97503. _this.useRGBColor = true;
  97504. /**
  97505. * This helps reducing the banding effect that could occur on the background.
  97506. */
  97507. _this.enableNoise = false;
  97508. _this._fovMultiplier = 1.0;
  97509. /**
  97510. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97511. */
  97512. _this.useEquirectangularFOV = false;
  97513. _this._maxSimultaneousLights = 4;
  97514. /**
  97515. * Number of Simultaneous lights allowed on the material.
  97516. */
  97517. _this.maxSimultaneousLights = 4;
  97518. /**
  97519. * Keep track of the image processing observer to allow dispose and replace.
  97520. */
  97521. _this._imageProcessingObserver = null;
  97522. /**
  97523. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97524. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97525. */
  97526. _this.switchToBGR = false;
  97527. // Temp values kept as cache in the material.
  97528. _this._renderTargets = new BABYLON.SmartArray(16);
  97529. _this._reflectionControls = BABYLON.Vector4.Zero();
  97530. _this._white = BABYLON.Color3.White();
  97531. _this._primaryShadowColor = BABYLON.Color3.Black();
  97532. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97533. // Setup the default processing configuration to the scene.
  97534. _this._attachImageProcessingConfiguration(null);
  97535. _this.getRenderTargetTextures = function () {
  97536. _this._renderTargets.reset();
  97537. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97538. _this._renderTargets.push(_this._diffuseTexture);
  97539. }
  97540. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97541. _this._renderTargets.push(_this._reflectionTexture);
  97542. }
  97543. return _this._renderTargets;
  97544. };
  97545. return _this;
  97546. }
  97547. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97548. /**
  97549. * Experimental Internal Use Only.
  97550. *
  97551. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97552. * This acts as a helper to set the primary color to a more "human friendly" value.
  97553. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97554. * output color as close as possible from the chosen value.
  97555. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97556. * part of lighting setup.)
  97557. */
  97558. get: function () {
  97559. return this.__perceptualColor;
  97560. },
  97561. set: function (value) {
  97562. this.__perceptualColor = value;
  97563. this._computePrimaryColorFromPerceptualColor();
  97564. this._markAllSubMeshesAsLightsDirty();
  97565. },
  97566. enumerable: true,
  97567. configurable: true
  97568. });
  97569. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97570. /**
  97571. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97572. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97573. */
  97574. get: function () {
  97575. return this._primaryColorShadowLevel;
  97576. },
  97577. set: function (value) {
  97578. this._primaryColorShadowLevel = value;
  97579. this._computePrimaryColors();
  97580. this._markAllSubMeshesAsLightsDirty();
  97581. },
  97582. enumerable: true,
  97583. configurable: true
  97584. });
  97585. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97586. /**
  97587. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97588. * The primary color is used at the level chosen to define what the white area would look.
  97589. */
  97590. get: function () {
  97591. return this._primaryColorHighlightLevel;
  97592. },
  97593. set: function (value) {
  97594. this._primaryColorHighlightLevel = value;
  97595. this._computePrimaryColors();
  97596. this._markAllSubMeshesAsLightsDirty();
  97597. },
  97598. enumerable: true,
  97599. configurable: true
  97600. });
  97601. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97602. /**
  97603. * Sets the reflection reflectance fresnel values according to the default standard
  97604. * empirically know to work well :-)
  97605. */
  97606. set: function (value) {
  97607. var reflectionWeight = value;
  97608. if (reflectionWeight < 0.5) {
  97609. reflectionWeight = reflectionWeight * 2.0;
  97610. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97611. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97612. }
  97613. else {
  97614. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97615. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97616. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97617. }
  97618. },
  97619. enumerable: true,
  97620. configurable: true
  97621. });
  97622. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97623. /**
  97624. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97625. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97626. * Recommended to be keep at 1.0 except for special cases.
  97627. */
  97628. get: function () {
  97629. return this._fovMultiplier;
  97630. },
  97631. set: function (value) {
  97632. if (isNaN(value)) {
  97633. value = 1.0;
  97634. }
  97635. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97636. },
  97637. enumerable: true,
  97638. configurable: true
  97639. });
  97640. /**
  97641. * Attaches a new image processing configuration to the PBR Material.
  97642. * @param configuration (if null the scene configuration will be use)
  97643. */
  97644. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97645. var _this = this;
  97646. if (configuration === this._imageProcessingConfiguration) {
  97647. return;
  97648. }
  97649. // Detaches observer.
  97650. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97651. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97652. }
  97653. // Pick the scene configuration if needed.
  97654. if (!configuration) {
  97655. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97656. }
  97657. else {
  97658. this._imageProcessingConfiguration = configuration;
  97659. }
  97660. // Attaches observer.
  97661. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97662. _this._computePrimaryColorFromPerceptualColor();
  97663. _this._markAllSubMeshesAsImageProcessingDirty();
  97664. });
  97665. };
  97666. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97667. /**
  97668. * Gets the image processing configuration used either in this material.
  97669. */
  97670. get: function () {
  97671. return this._imageProcessingConfiguration;
  97672. },
  97673. /**
  97674. * Sets the Default image processing configuration used either in the this material.
  97675. *
  97676. * If sets to null, the scene one is in use.
  97677. */
  97678. set: function (value) {
  97679. this._attachImageProcessingConfiguration(value);
  97680. // Ensure the effect will be rebuilt.
  97681. this._markAllSubMeshesAsTexturesDirty();
  97682. },
  97683. enumerable: true,
  97684. configurable: true
  97685. });
  97686. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97687. /**
  97688. * Gets wether the color curves effect is enabled.
  97689. */
  97690. get: function () {
  97691. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97692. },
  97693. /**
  97694. * Sets wether the color curves effect is enabled.
  97695. */
  97696. set: function (value) {
  97697. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97698. },
  97699. enumerable: true,
  97700. configurable: true
  97701. });
  97702. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97703. /**
  97704. * Gets wether the color grading effect is enabled.
  97705. */
  97706. get: function () {
  97707. return this.imageProcessingConfiguration.colorGradingEnabled;
  97708. },
  97709. /**
  97710. * Gets wether the color grading effect is enabled.
  97711. */
  97712. set: function (value) {
  97713. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97714. },
  97715. enumerable: true,
  97716. configurable: true
  97717. });
  97718. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97719. /**
  97720. * Gets wether tonemapping is enabled or not.
  97721. */
  97722. get: function () {
  97723. return this._imageProcessingConfiguration.toneMappingEnabled;
  97724. },
  97725. /**
  97726. * Sets wether tonemapping is enabled or not
  97727. */
  97728. set: function (value) {
  97729. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97730. },
  97731. enumerable: true,
  97732. configurable: true
  97733. });
  97734. ;
  97735. ;
  97736. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97737. /**
  97738. * The camera exposure used on this material.
  97739. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97740. * This corresponds to a photographic exposure.
  97741. */
  97742. get: function () {
  97743. return this._imageProcessingConfiguration.exposure;
  97744. },
  97745. /**
  97746. * The camera exposure used on this material.
  97747. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97748. * This corresponds to a photographic exposure.
  97749. */
  97750. set: function (value) {
  97751. this._imageProcessingConfiguration.exposure = value;
  97752. },
  97753. enumerable: true,
  97754. configurable: true
  97755. });
  97756. ;
  97757. ;
  97758. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97759. /**
  97760. * Gets The camera contrast used on this material.
  97761. */
  97762. get: function () {
  97763. return this._imageProcessingConfiguration.contrast;
  97764. },
  97765. /**
  97766. * Sets The camera contrast used on this material.
  97767. */
  97768. set: function (value) {
  97769. this._imageProcessingConfiguration.contrast = value;
  97770. },
  97771. enumerable: true,
  97772. configurable: true
  97773. });
  97774. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97775. /**
  97776. * Gets the Color Grading 2D Lookup Texture.
  97777. */
  97778. get: function () {
  97779. return this._imageProcessingConfiguration.colorGradingTexture;
  97780. },
  97781. /**
  97782. * Sets the Color Grading 2D Lookup Texture.
  97783. */
  97784. set: function (value) {
  97785. this.imageProcessingConfiguration.colorGradingTexture = value;
  97786. },
  97787. enumerable: true,
  97788. configurable: true
  97789. });
  97790. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97791. /**
  97792. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97793. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97794. * 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;
  97795. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97796. */
  97797. get: function () {
  97798. return this.imageProcessingConfiguration.colorCurves;
  97799. },
  97800. /**
  97801. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97802. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97803. * 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;
  97804. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97805. */
  97806. set: function (value) {
  97807. this.imageProcessingConfiguration.colorCurves = value;
  97808. },
  97809. enumerable: true,
  97810. configurable: true
  97811. });
  97812. /**
  97813. * The entire material has been created in order to prevent overdraw.
  97814. * @returns false
  97815. */
  97816. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97817. return true;
  97818. };
  97819. /**
  97820. * The entire material has been created in order to prevent overdraw.
  97821. * @returns true if blending is enable
  97822. */
  97823. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97824. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97825. };
  97826. /**
  97827. * Checks wether the material is ready to be rendered for a given mesh.
  97828. * @param mesh The mesh to render
  97829. * @param subMesh The submesh to check against
  97830. * @param useInstances Specify wether or not the material is used with instances
  97831. * @returns true if all the dependencies are ready (Textures, Effects...)
  97832. */
  97833. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97834. var _this = this;
  97835. if (useInstances === void 0) { useInstances = false; }
  97836. if (subMesh.effect && this.isFrozen) {
  97837. if (this._wasPreviouslyReady) {
  97838. return true;
  97839. }
  97840. }
  97841. if (!subMesh._materialDefines) {
  97842. subMesh._materialDefines = new BackgroundMaterialDefines();
  97843. }
  97844. var scene = this.getScene();
  97845. var defines = subMesh._materialDefines;
  97846. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97847. if (defines._renderId === scene.getRenderId()) {
  97848. return true;
  97849. }
  97850. }
  97851. var engine = scene.getEngine();
  97852. // Lights
  97853. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97854. defines._needNormals = true;
  97855. // Textures
  97856. if (defines._areTexturesDirty) {
  97857. defines._needUVs = false;
  97858. if (scene.texturesEnabled) {
  97859. if (scene.getEngine().getCaps().textureLOD) {
  97860. defines.TEXTURELODSUPPORT = true;
  97861. }
  97862. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97863. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97864. return false;
  97865. }
  97866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97867. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97868. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97869. defines.OPACITYFRESNEL = this._opacityFresnel;
  97870. }
  97871. else {
  97872. defines.DIFFUSE = false;
  97873. defines.DIFFUSEHASALPHA = false;
  97874. defines.GAMMADIFFUSE = false;
  97875. defines.OPACITYFRESNEL = false;
  97876. }
  97877. var reflectionTexture = this._reflectionTexture;
  97878. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97879. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97880. return false;
  97881. }
  97882. defines.REFLECTION = true;
  97883. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97884. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97885. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97886. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97887. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97888. defines.REFLECTIONBGR = this.switchToBGR;
  97889. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97890. defines.INVERTCUBICMAP = true;
  97891. }
  97892. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97893. switch (reflectionTexture.coordinatesMode) {
  97894. case BABYLON.Texture.EXPLICIT_MODE:
  97895. defines.REFLECTIONMAP_EXPLICIT = true;
  97896. break;
  97897. case BABYLON.Texture.PLANAR_MODE:
  97898. defines.REFLECTIONMAP_PLANAR = true;
  97899. break;
  97900. case BABYLON.Texture.PROJECTION_MODE:
  97901. defines.REFLECTIONMAP_PROJECTION = true;
  97902. break;
  97903. case BABYLON.Texture.SKYBOX_MODE:
  97904. defines.REFLECTIONMAP_SKYBOX = true;
  97905. break;
  97906. case BABYLON.Texture.SPHERICAL_MODE:
  97907. defines.REFLECTIONMAP_SPHERICAL = true;
  97908. break;
  97909. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97910. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97911. break;
  97912. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97913. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97914. break;
  97915. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97916. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97917. break;
  97918. case BABYLON.Texture.CUBIC_MODE:
  97919. case BABYLON.Texture.INVCUBIC_MODE:
  97920. default:
  97921. defines.REFLECTIONMAP_CUBIC = true;
  97922. break;
  97923. }
  97924. if (this.reflectionFresnel) {
  97925. defines.REFLECTIONFRESNEL = true;
  97926. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97927. this._reflectionControls.x = this.reflectionAmount;
  97928. this._reflectionControls.y = this.reflectionReflectance0;
  97929. this._reflectionControls.z = this.reflectionReflectance90;
  97930. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97931. }
  97932. else {
  97933. defines.REFLECTIONFRESNEL = false;
  97934. defines.REFLECTIONFALLOFF = false;
  97935. }
  97936. }
  97937. else {
  97938. defines.REFLECTION = false;
  97939. defines.REFLECTIONFRESNEL = false;
  97940. defines.REFLECTIONFALLOFF = false;
  97941. defines.REFLECTIONBLUR = false;
  97942. defines.REFLECTIONMAP_3D = false;
  97943. defines.REFLECTIONMAP_SPHERICAL = false;
  97944. defines.REFLECTIONMAP_PLANAR = false;
  97945. defines.REFLECTIONMAP_CUBIC = false;
  97946. defines.REFLECTIONMAP_PROJECTION = false;
  97947. defines.REFLECTIONMAP_SKYBOX = false;
  97948. defines.REFLECTIONMAP_EXPLICIT = false;
  97949. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97950. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97951. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97952. defines.INVERTCUBICMAP = false;
  97953. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97954. defines.LODINREFLECTIONALPHA = false;
  97955. defines.GAMMAREFLECTION = false;
  97956. }
  97957. }
  97958. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97959. defines.USERGBCOLOR = this._useRGBColor;
  97960. defines.NOISE = this._enableNoise;
  97961. }
  97962. if (defines._areLightsDirty) {
  97963. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97964. }
  97965. if (defines._areImageProcessingDirty) {
  97966. if (!this._imageProcessingConfiguration.isReady()) {
  97967. return false;
  97968. }
  97969. this._imageProcessingConfiguration.prepareDefines(defines);
  97970. }
  97971. // Misc.
  97972. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97973. // Values that need to be evaluated on every frame
  97974. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97975. // Attribs
  97976. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97977. if (mesh) {
  97978. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97979. mesh.createNormals(true);
  97980. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97981. }
  97982. }
  97983. }
  97984. // Get correct effect
  97985. if (defines.isDirty) {
  97986. defines.markAsProcessed();
  97987. scene.resetCachedMaterial();
  97988. // Fallbacks
  97989. var fallbacks = new BABYLON.EffectFallbacks();
  97990. if (defines.FOG) {
  97991. fallbacks.addFallback(0, "FOG");
  97992. }
  97993. if (defines.POINTSIZE) {
  97994. fallbacks.addFallback(1, "POINTSIZE");
  97995. }
  97996. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97997. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97998. fallbacks.addCPUSkinningFallback(0, mesh);
  97999. }
  98000. //Attributes
  98001. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98002. if (defines.NORMAL) {
  98003. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98004. }
  98005. if (defines.UV1) {
  98006. attribs.push(BABYLON.VertexBuffer.UVKind);
  98007. }
  98008. if (defines.UV2) {
  98009. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98010. }
  98011. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98012. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98013. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98014. "vFogInfos", "vFogColor", "pointSize",
  98015. "vClipPlane", "mBones",
  98016. "vPrimaryColor", "vPrimaryColorShadow",
  98017. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98018. "shadowLevel", "alpha",
  98019. "vBackgroundCenter", "vReflectionControl",
  98020. "vDiffuseInfos", "diffuseMatrix",
  98021. ];
  98022. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98023. var uniformBuffers = ["Material", "Scene"];
  98024. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  98025. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  98026. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  98027. uniformsNames: uniforms,
  98028. uniformBuffersNames: uniformBuffers,
  98029. samplers: samplers,
  98030. defines: defines,
  98031. maxSimultaneousLights: this._maxSimultaneousLights
  98032. });
  98033. var onCompiled = function (effect) {
  98034. if (_this.onCompiled) {
  98035. _this.onCompiled(effect);
  98036. }
  98037. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  98038. };
  98039. var join = defines.toString();
  98040. subMesh.setEffect(scene.getEngine().createEffect("background", {
  98041. attributes: attribs,
  98042. uniformsNames: uniforms,
  98043. uniformBuffersNames: uniformBuffers,
  98044. samplers: samplers,
  98045. defines: join,
  98046. fallbacks: fallbacks,
  98047. onCompiled: onCompiled,
  98048. onError: this.onError,
  98049. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  98050. }, engine), defines);
  98051. this.buildUniformLayout();
  98052. }
  98053. if (!subMesh.effect || !subMesh.effect.isReady()) {
  98054. return false;
  98055. }
  98056. defines._renderId = scene.getRenderId();
  98057. this._wasPreviouslyReady = true;
  98058. return true;
  98059. };
  98060. /**
  98061. * Compute the primary color according to the chosen perceptual color.
  98062. */
  98063. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  98064. if (!this.__perceptualColor) {
  98065. return;
  98066. }
  98067. this._primaryColor.copyFrom(this.__perceptualColor);
  98068. // Revert gamma space.
  98069. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  98070. // Revert image processing configuration.
  98071. if (this._imageProcessingConfiguration) {
  98072. // Revert Exposure.
  98073. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  98074. }
  98075. this._computePrimaryColors();
  98076. };
  98077. /**
  98078. * Compute the highlights and shadow colors according to their chosen levels.
  98079. */
  98080. BackgroundMaterial.prototype._computePrimaryColors = function () {
  98081. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  98082. return;
  98083. }
  98084. // Find the highlight color based on the configuration.
  98085. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  98086. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  98087. // Find the shadow color based on the configuration.
  98088. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  98089. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  98090. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  98091. };
  98092. /**
  98093. * Build the uniform buffer used in the material.
  98094. */
  98095. BackgroundMaterial.prototype.buildUniformLayout = function () {
  98096. // Order is important !
  98097. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  98098. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  98099. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  98100. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  98101. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  98102. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  98103. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  98104. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  98105. this._uniformBuffer.addUniform("pointSize", 1);
  98106. this._uniformBuffer.addUniform("shadowLevel", 1);
  98107. this._uniformBuffer.addUniform("alpha", 1);
  98108. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  98109. this._uniformBuffer.addUniform("vReflectionControl", 4);
  98110. this._uniformBuffer.create();
  98111. };
  98112. /**
  98113. * Unbind the material.
  98114. */
  98115. BackgroundMaterial.prototype.unbind = function () {
  98116. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  98117. this._uniformBuffer.setTexture("diffuseSampler", null);
  98118. }
  98119. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  98120. this._uniformBuffer.setTexture("reflectionSampler", null);
  98121. }
  98122. _super.prototype.unbind.call(this);
  98123. };
  98124. /**
  98125. * Bind only the world matrix to the material.
  98126. * @param world The world matrix to bind.
  98127. */
  98128. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  98129. this._activeEffect.setMatrix("world", world);
  98130. };
  98131. /**
  98132. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  98133. * @param world The world matrix to bind.
  98134. * @param subMesh The submesh to bind for.
  98135. */
  98136. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  98137. var scene = this.getScene();
  98138. var defines = subMesh._materialDefines;
  98139. if (!defines) {
  98140. return;
  98141. }
  98142. var effect = subMesh.effect;
  98143. if (!effect) {
  98144. return;
  98145. }
  98146. this._activeEffect = effect;
  98147. // Matrices
  98148. this.bindOnlyWorldMatrix(world);
  98149. // Bones
  98150. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  98151. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  98152. if (mustRebind) {
  98153. this._uniformBuffer.bindToEffect(effect, "Material");
  98154. this.bindViewProjection(effect);
  98155. var reflectionTexture = this._reflectionTexture;
  98156. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  98157. // Texture uniforms
  98158. if (scene.texturesEnabled) {
  98159. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98160. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  98161. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  98162. }
  98163. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98164. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  98165. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  98166. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  98167. }
  98168. }
  98169. if (this.shadowLevel > 0) {
  98170. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  98171. }
  98172. this._uniformBuffer.updateFloat("alpha", this.alpha);
  98173. // Point size
  98174. if (this.pointsCloud) {
  98175. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  98176. }
  98177. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  98178. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  98179. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  98180. }
  98181. else {
  98182. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  98183. }
  98184. }
  98185. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  98186. // Textures
  98187. if (scene.texturesEnabled) {
  98188. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98189. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  98190. }
  98191. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98192. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  98193. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  98194. }
  98195. else if (!defines.REFLECTIONBLUR) {
  98196. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  98197. }
  98198. else {
  98199. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  98200. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  98201. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  98202. }
  98203. if (defines.REFLECTIONFRESNEL) {
  98204. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  98205. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  98206. }
  98207. }
  98208. }
  98209. // Clip plane
  98210. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  98211. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  98212. }
  98213. if (mustRebind || !this.isFrozen) {
  98214. if (scene.lightsEnabled) {
  98215. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  98216. }
  98217. // View
  98218. this.bindView(effect);
  98219. // Fog
  98220. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  98221. // image processing
  98222. this._imageProcessingConfiguration.bind(this._activeEffect);
  98223. }
  98224. this._uniformBuffer.update();
  98225. this._afterBind(mesh);
  98226. };
  98227. /**
  98228. * Dispose the material.
  98229. * @param forceDisposeEffect Force disposal of the associated effect.
  98230. * @param forceDisposeTextures Force disposal of the associated textures.
  98231. */
  98232. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  98233. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  98234. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  98235. if (forceDisposeTextures) {
  98236. if (this.diffuseTexture) {
  98237. this.diffuseTexture.dispose();
  98238. }
  98239. if (this.reflectionTexture) {
  98240. this.reflectionTexture.dispose();
  98241. }
  98242. }
  98243. this._renderTargets.dispose();
  98244. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98245. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98246. }
  98247. _super.prototype.dispose.call(this, forceDisposeEffect);
  98248. };
  98249. /**
  98250. * Clones the material.
  98251. * @param name The cloned name.
  98252. * @returns The cloned material.
  98253. */
  98254. BackgroundMaterial.prototype.clone = function (name) {
  98255. var _this = this;
  98256. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  98257. };
  98258. /**
  98259. * Serializes the current material to its JSON representation.
  98260. * @returns The JSON representation.
  98261. */
  98262. BackgroundMaterial.prototype.serialize = function () {
  98263. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98264. serializationObject.customType = "BABYLON.BackgroundMaterial";
  98265. return serializationObject;
  98266. };
  98267. /**
  98268. * Gets the class name of the material
  98269. * @returns "BackgroundMaterial"
  98270. */
  98271. BackgroundMaterial.prototype.getClassName = function () {
  98272. return "BackgroundMaterial";
  98273. };
  98274. /**
  98275. * Parse a JSON input to create back a background material.
  98276. * @param source The JSON data to parse
  98277. * @param scene The scene to create the parsed material in
  98278. * @param rootUrl The root url of the assets the material depends upon
  98279. * @returns the instantiated BackgroundMaterial.
  98280. */
  98281. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  98282. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  98283. };
  98284. /**
  98285. * Standard reflectance value at parallel view angle.
  98286. */
  98287. BackgroundMaterial.StandardReflectance0 = 0.05;
  98288. /**
  98289. * Standard reflectance value at grazing angle.
  98290. */
  98291. BackgroundMaterial.StandardReflectance90 = 0.5;
  98292. __decorate([
  98293. BABYLON.serializeAsColor3()
  98294. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  98295. __decorate([
  98296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98297. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  98298. __decorate([
  98299. BABYLON.serializeAsColor3()
  98300. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  98301. __decorate([
  98302. BABYLON.serialize()
  98303. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  98304. __decorate([
  98305. BABYLON.serialize()
  98306. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  98307. __decorate([
  98308. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98309. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  98310. __decorate([
  98311. BABYLON.serializeAsTexture()
  98312. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  98313. __decorate([
  98314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98315. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  98316. __decorate([
  98317. BABYLON.serialize()
  98318. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  98319. __decorate([
  98320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98321. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  98322. __decorate([
  98323. BABYLON.serializeAsTexture()
  98324. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  98325. __decorate([
  98326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98327. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  98328. __decorate([
  98329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98330. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  98331. __decorate([
  98332. BABYLON.serialize()
  98333. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  98334. __decorate([
  98335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98336. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  98337. __decorate([
  98338. BABYLON.serializeAsVector3()
  98339. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  98340. __decorate([
  98341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98342. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  98343. __decorate([
  98344. BABYLON.serialize()
  98345. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  98346. __decorate([
  98347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98348. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  98349. __decorate([
  98350. BABYLON.serialize()
  98351. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  98352. __decorate([
  98353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98354. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  98355. __decorate([
  98356. BABYLON.serialize()
  98357. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  98358. __decorate([
  98359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98360. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  98361. __decorate([
  98362. BABYLON.serialize()
  98363. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  98364. __decorate([
  98365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98366. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  98367. __decorate([
  98368. BABYLON.serialize()
  98369. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  98370. __decorate([
  98371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98372. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  98373. __decorate([
  98374. BABYLON.serialize()
  98375. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  98376. __decorate([
  98377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98378. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  98379. __decorate([
  98380. BABYLON.serialize()
  98381. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  98382. __decorate([
  98383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98384. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98385. __decorate([
  98386. BABYLON.serialize()
  98387. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98388. __decorate([
  98389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98390. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98391. __decorate([
  98392. BABYLON.serialize()
  98393. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98394. __decorate([
  98395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98396. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98397. __decorate([
  98398. BABYLON.serializeAsImageProcessingConfiguration()
  98399. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98400. return BackgroundMaterial;
  98401. }(BABYLON.PushMaterial));
  98402. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98403. })(BABYLON || (BABYLON = {}));
  98404. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98405. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98406. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98407. s = arguments[i];
  98408. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98409. t[p] = s[p];
  98410. }
  98411. return t;
  98412. };
  98413. var BABYLON;
  98414. (function (BABYLON) {
  98415. /**
  98416. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98417. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98418. * It also helps with the default setup of your imageProcessing configuration.
  98419. */
  98420. var EnvironmentHelper = /** @class */ (function () {
  98421. /**
  98422. * constructor
  98423. * @param options
  98424. * @param scene The scene to add the material to
  98425. */
  98426. function EnvironmentHelper(options, scene) {
  98427. var _this = this;
  98428. this._errorHandler = function (message, exception) {
  98429. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98430. };
  98431. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98432. this._scene = scene;
  98433. this.onErrorObservable = new BABYLON.Observable();
  98434. this._setupBackground();
  98435. this._setupImageProcessing();
  98436. }
  98437. /**
  98438. * Creates the default options for the helper.
  98439. */
  98440. EnvironmentHelper._getDefaultOptions = function () {
  98441. return {
  98442. createGround: true,
  98443. groundSize: 15,
  98444. groundTexture: this._groundTextureCDNUrl,
  98445. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98446. groundOpacity: 0.9,
  98447. enableGroundShadow: true,
  98448. groundShadowLevel: 0.5,
  98449. enableGroundMirror: false,
  98450. groundMirrorSizeRatio: 0.3,
  98451. groundMirrorBlurKernel: 64,
  98452. groundMirrorAmount: 1,
  98453. groundMirrorFresnelWeight: 1,
  98454. groundMirrorFallOffDistance: 0,
  98455. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98456. groundYBias: 0.00001,
  98457. createSkybox: true,
  98458. skyboxSize: 20,
  98459. skyboxTexture: this._skyboxTextureCDNUrl,
  98460. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98461. backgroundYRotation: 0,
  98462. sizeAuto: true,
  98463. rootPosition: BABYLON.Vector3.Zero(),
  98464. setupImageProcessing: true,
  98465. environmentTexture: this._environmentTextureCDNUrl,
  98466. cameraExposure: 0.8,
  98467. cameraContrast: 1.2,
  98468. toneMappingEnabled: true,
  98469. };
  98470. };
  98471. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98472. /**
  98473. * Gets the root mesh created by the helper.
  98474. */
  98475. get: function () {
  98476. return this._rootMesh;
  98477. },
  98478. enumerable: true,
  98479. configurable: true
  98480. });
  98481. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98482. /**
  98483. * Gets the skybox created by the helper.
  98484. */
  98485. get: function () {
  98486. return this._skybox;
  98487. },
  98488. enumerable: true,
  98489. configurable: true
  98490. });
  98491. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98492. /**
  98493. * Gets the skybox texture created by the helper.
  98494. */
  98495. get: function () {
  98496. return this._skyboxTexture;
  98497. },
  98498. enumerable: true,
  98499. configurable: true
  98500. });
  98501. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98502. /**
  98503. * Gets the skybox material created by the helper.
  98504. */
  98505. get: function () {
  98506. return this._skyboxMaterial;
  98507. },
  98508. enumerable: true,
  98509. configurable: true
  98510. });
  98511. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98512. /**
  98513. * Gets the ground mesh created by the helper.
  98514. */
  98515. get: function () {
  98516. return this._ground;
  98517. },
  98518. enumerable: true,
  98519. configurable: true
  98520. });
  98521. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98522. /**
  98523. * Gets the ground texture created by the helper.
  98524. */
  98525. get: function () {
  98526. return this._groundTexture;
  98527. },
  98528. enumerable: true,
  98529. configurable: true
  98530. });
  98531. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98532. /**
  98533. * Gets the ground mirror created by the helper.
  98534. */
  98535. get: function () {
  98536. return this._groundMirror;
  98537. },
  98538. enumerable: true,
  98539. configurable: true
  98540. });
  98541. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98542. /**
  98543. * Gets the ground mirror render list to helps pushing the meshes
  98544. * you wish in the ground reflection.
  98545. */
  98546. get: function () {
  98547. if (this._groundMirror) {
  98548. return this._groundMirror.renderList;
  98549. }
  98550. return null;
  98551. },
  98552. enumerable: true,
  98553. configurable: true
  98554. });
  98555. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98556. /**
  98557. * Gets the ground material created by the helper.
  98558. */
  98559. get: function () {
  98560. return this._groundMaterial;
  98561. },
  98562. enumerable: true,
  98563. configurable: true
  98564. });
  98565. /**
  98566. * Updates the background according to the new options
  98567. * @param options
  98568. */
  98569. EnvironmentHelper.prototype.updateOptions = function (options) {
  98570. var newOptions = __assign({}, this._options, options);
  98571. if (this._ground && !newOptions.createGround) {
  98572. this._ground.dispose();
  98573. this._ground = null;
  98574. }
  98575. if (this._groundMaterial && !newOptions.createGround) {
  98576. this._groundMaterial.dispose();
  98577. this._groundMaterial = null;
  98578. }
  98579. if (this._groundTexture) {
  98580. if (this._options.groundTexture != newOptions.groundTexture) {
  98581. this._groundTexture.dispose();
  98582. this._groundTexture = null;
  98583. }
  98584. }
  98585. if (this._skybox && !newOptions.createSkybox) {
  98586. this._skybox.dispose();
  98587. this._skybox = null;
  98588. }
  98589. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98590. this._skyboxMaterial.dispose();
  98591. this._skyboxMaterial = null;
  98592. }
  98593. if (this._skyboxTexture) {
  98594. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98595. this._skyboxTexture.dispose();
  98596. this._skyboxTexture = null;
  98597. }
  98598. }
  98599. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98600. this._groundMirror.dispose();
  98601. this._groundMirror = null;
  98602. }
  98603. if (this._scene.environmentTexture) {
  98604. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98605. this._scene.environmentTexture.dispose();
  98606. }
  98607. }
  98608. this._options = newOptions;
  98609. this._setupBackground();
  98610. this._setupImageProcessing();
  98611. };
  98612. /**
  98613. * Sets the primary color of all the available elements.
  98614. * @param color the main color to affect to the ground and the background
  98615. */
  98616. EnvironmentHelper.prototype.setMainColor = function (color) {
  98617. if (this.groundMaterial) {
  98618. this.groundMaterial.primaryColor = color;
  98619. }
  98620. if (this.skyboxMaterial) {
  98621. this.skyboxMaterial.primaryColor = color;
  98622. }
  98623. if (this.groundMirror) {
  98624. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98625. }
  98626. };
  98627. /**
  98628. * Setup the image processing according to the specified options.
  98629. */
  98630. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98631. if (this._options.setupImageProcessing) {
  98632. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98633. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98634. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98635. this._setupEnvironmentTexture();
  98636. }
  98637. };
  98638. /**
  98639. * Setup the environment texture according to the specified options.
  98640. */
  98641. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98642. if (this._scene.environmentTexture) {
  98643. return;
  98644. }
  98645. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98646. this._scene.environmentTexture = this._options.environmentTexture;
  98647. return;
  98648. }
  98649. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98650. this._scene.environmentTexture = environmentTexture;
  98651. };
  98652. /**
  98653. * Setup the background according to the specified options.
  98654. */
  98655. EnvironmentHelper.prototype._setupBackground = function () {
  98656. if (!this._rootMesh) {
  98657. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98658. }
  98659. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98660. var sceneSize = this._getSceneSize();
  98661. if (this._options.createGround) {
  98662. this._setupGround(sceneSize);
  98663. this._setupGroundMaterial();
  98664. this._setupGroundDiffuseTexture();
  98665. if (this._options.enableGroundMirror) {
  98666. this._setupGroundMirrorTexture(sceneSize);
  98667. }
  98668. this._setupMirrorInGroundMaterial();
  98669. }
  98670. if (this._options.createSkybox) {
  98671. this._setupSkybox(sceneSize);
  98672. this._setupSkyboxMaterial();
  98673. this._setupSkyboxReflectionTexture();
  98674. }
  98675. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98676. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98677. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98678. };
  98679. /**
  98680. * Get the scene sizes according to the setup.
  98681. */
  98682. EnvironmentHelper.prototype._getSceneSize = function () {
  98683. var _this = this;
  98684. var groundSize = this._options.groundSize;
  98685. var skyboxSize = this._options.skyboxSize;
  98686. var rootPosition = this._options.rootPosition;
  98687. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98688. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98689. }
  98690. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98691. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98692. });
  98693. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98694. if (this._options.sizeAuto) {
  98695. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98696. this._scene.activeCamera.upperRadiusLimit) {
  98697. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98698. skyboxSize = groundSize;
  98699. }
  98700. var sceneDiagonalLenght = sceneDiagonal.length();
  98701. if (sceneDiagonalLenght > groundSize) {
  98702. groundSize = sceneDiagonalLenght * 2;
  98703. skyboxSize = groundSize;
  98704. }
  98705. // 10 % bigger.
  98706. groundSize *= 1.1;
  98707. skyboxSize *= 1.5;
  98708. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98709. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98710. }
  98711. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98712. };
  98713. /**
  98714. * Setup the ground according to the specified options.
  98715. */
  98716. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98717. var _this = this;
  98718. if (!this._ground) {
  98719. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98720. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98721. this._ground.parent = this._rootMesh;
  98722. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98723. }
  98724. this._ground.receiveShadows = this._options.enableGroundShadow;
  98725. };
  98726. /**
  98727. * Setup the ground material according to the specified options.
  98728. */
  98729. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98730. if (!this._groundMaterial) {
  98731. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98732. }
  98733. this._groundMaterial.alpha = this._options.groundOpacity;
  98734. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98735. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98736. this._groundMaterial.primaryColor = this._options.groundColor;
  98737. this._groundMaterial.useRGBColor = false;
  98738. this._groundMaterial.enableNoise = true;
  98739. if (this._ground) {
  98740. this._ground.material = this._groundMaterial;
  98741. }
  98742. };
  98743. /**
  98744. * Setup the ground diffuse texture according to the specified options.
  98745. */
  98746. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98747. if (!this._groundMaterial) {
  98748. return;
  98749. }
  98750. if (this._groundTexture) {
  98751. return;
  98752. }
  98753. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98754. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98755. return;
  98756. }
  98757. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98758. diffuseTexture.gammaSpace = false;
  98759. diffuseTexture.hasAlpha = true;
  98760. this._groundMaterial.diffuseTexture = diffuseTexture;
  98761. };
  98762. /**
  98763. * Setup the ground mirror texture according to the specified options.
  98764. */
  98765. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98766. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98767. if (!this._groundMirror) {
  98768. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98769. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98770. this._groundMirror.anisotropicFilteringLevel = 1;
  98771. this._groundMirror.wrapU = wrapping;
  98772. this._groundMirror.wrapV = wrapping;
  98773. this._groundMirror.gammaSpace = false;
  98774. if (this._groundMirror.renderList) {
  98775. for (var i = 0; i < this._scene.meshes.length; i++) {
  98776. var mesh = this._scene.meshes[i];
  98777. if (mesh !== this._ground &&
  98778. mesh !== this._skybox &&
  98779. mesh !== this._rootMesh) {
  98780. this._groundMirror.renderList.push(mesh);
  98781. }
  98782. }
  98783. }
  98784. }
  98785. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98786. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98787. };
  98788. /**
  98789. * Setup the ground to receive the mirror texture.
  98790. */
  98791. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98792. if (this._groundMaterial) {
  98793. this._groundMaterial.reflectionTexture = this._groundMirror;
  98794. this._groundMaterial.reflectionFresnel = true;
  98795. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98796. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98797. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98798. }
  98799. };
  98800. /**
  98801. * Setup the skybox according to the specified options.
  98802. */
  98803. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98804. var _this = this;
  98805. if (!this._skybox) {
  98806. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98807. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98808. }
  98809. this._skybox.parent = this._rootMesh;
  98810. };
  98811. /**
  98812. * Setup the skybox material according to the specified options.
  98813. */
  98814. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98815. if (!this._skybox) {
  98816. return;
  98817. }
  98818. if (!this._skyboxMaterial) {
  98819. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98820. }
  98821. this._skyboxMaterial.useRGBColor = false;
  98822. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98823. this._skyboxMaterial.enableNoise = true;
  98824. this._skybox.material = this._skyboxMaterial;
  98825. };
  98826. /**
  98827. * Setup the skybox reflection texture according to the specified options.
  98828. */
  98829. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98830. if (!this._skyboxMaterial) {
  98831. return;
  98832. }
  98833. if (this._skyboxTexture) {
  98834. return;
  98835. }
  98836. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98837. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98838. return;
  98839. }
  98840. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98841. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98842. this._skyboxTexture.gammaSpace = false;
  98843. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98844. };
  98845. /**
  98846. * Dispose all the elements created by the Helper.
  98847. */
  98848. EnvironmentHelper.prototype.dispose = function () {
  98849. if (this._groundMaterial) {
  98850. this._groundMaterial.dispose(true, true);
  98851. }
  98852. if (this._skyboxMaterial) {
  98853. this._skyboxMaterial.dispose(true, true);
  98854. }
  98855. this._rootMesh.dispose(false);
  98856. };
  98857. /**
  98858. * Default ground texture URL.
  98859. */
  98860. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98861. /**
  98862. * Default skybox texture URL.
  98863. */
  98864. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98865. /**
  98866. * Default environment texture URL.
  98867. */
  98868. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98869. return EnvironmentHelper;
  98870. }());
  98871. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98872. })(BABYLON || (BABYLON = {}));
  98873. //# sourceMappingURL=babylon.environmentHelper.js.map
  98874. var BABYLON;
  98875. (function (BABYLON) {
  98876. /**
  98877. * This class is made for on one-liner static method to help creating particle systems.
  98878. */
  98879. var ParticleHelper = /** @class */ (function () {
  98880. function ParticleHelper() {
  98881. }
  98882. /**
  98883. * This is the main static method (one-liner) of this helper to create different particle systems.
  98884. * @param type This string represents the type to the particle system to create
  98885. * @param emitter The object where the particle system will start to emit from.
  98886. * @param scene The scene where the particle system should live.
  98887. * @param gpu If the system will use gpu.
  98888. * @returns the ParticleSystem created.
  98889. */
  98890. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98891. var _this = this;
  98892. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98893. if (gpu === void 0) { gpu = false; }
  98894. return new Promise(function (resolve, reject) {
  98895. if (scene) {
  98896. _this._scene = scene;
  98897. }
  98898. else {
  98899. return reject("A particle system need a scene.");
  98900. }
  98901. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98902. return reject("Particle system with GPU is not supported.");
  98903. }
  98904. _this._emitter = emitter;
  98905. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98906. var newData = JSON.parse(data.toString());
  98907. return resolve(_this._createSystem(newData));
  98908. }, undefined, undefined, undefined, function (req, exception) {
  98909. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98910. });
  98911. });
  98912. };
  98913. ParticleHelper._createSystem = function (data) {
  98914. // Create a particle system
  98915. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98916. // Texture of each particle
  98917. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98918. // Where the particles come from
  98919. system.emitter = this._emitter; // the starting object, the emitter
  98920. // Colors of all particles
  98921. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98922. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98923. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98924. // Size of each particle (random between...
  98925. system.minSize = data.minSize;
  98926. system.maxSize = data.maxSize;
  98927. // Life time of each particle (random between...
  98928. system.minLifeTime = data.minLifeTime;
  98929. system.maxLifeTime = data.maxLifeTime;
  98930. // Emission rate
  98931. system.emitRate = data.emitRate;
  98932. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98933. system.blendMode = data.blendMode;
  98934. // Set the gravity of all particles
  98935. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98936. // Angular speed, in radians
  98937. system.minAngularSpeed = data.minAngularSpeed;
  98938. system.maxAngularSpeed = data.maxAngularSpeed;
  98939. // Speed
  98940. system.minEmitPower = data.minEmitPower;
  98941. system.maxEmitPower = data.maxEmitPower;
  98942. system.updateSpeed = data.updateSpeed;
  98943. switch (data.emitterType) {
  98944. case "box":
  98945. if (!data.direction1 || !data.direction2) {
  98946. throw new Error("Directions are missing in this particle system.");
  98947. }
  98948. if (!data.minEmitBox || !data.maxEmitBox) {
  98949. throw new Error("EmitBox is missing in this particle system.");
  98950. }
  98951. 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));
  98952. break;
  98953. case "sphere":
  98954. system.createSphereEmitter(data.radius);
  98955. break;
  98956. case "directed_sphere":
  98957. if (!data.direction1 || !data.direction2) {
  98958. throw new Error("Directions are missing in this particle system.");
  98959. }
  98960. 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));
  98961. break;
  98962. case "cone":
  98963. system.createConeEmitter(data.radius, data.angle);
  98964. break;
  98965. default:
  98966. break;
  98967. }
  98968. return system;
  98969. };
  98970. /**
  98971. * Base Assets URL.
  98972. */
  98973. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98974. return ParticleHelper;
  98975. }());
  98976. BABYLON.ParticleHelper = ParticleHelper;
  98977. })(BABYLON || (BABYLON = {}));
  98978. //# sourceMappingURL=babylon.particleHelper.js.map
  98979. var BABYLON;
  98980. (function (BABYLON) {
  98981. /**
  98982. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98983. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98984. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98985. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98986. */
  98987. var VideoDome = /** @class */ (function (_super) {
  98988. __extends(VideoDome, _super);
  98989. /**
  98990. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98991. * @param name Element's name, child elements will append suffixes for their own names.
  98992. * @param urlsOrVideo
  98993. * @param options An object containing optional or exposed sub element properties:
  98994. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98995. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98996. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98997. * @param options **loop=true** Automatically loop video on end.
  98998. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98999. */
  99000. function VideoDome(name, urlsOrVideo, options, scene) {
  99001. var _this = _super.call(this, name, scene) || this;
  99002. // set defaults and manage values
  99003. name = name || "videoDome";
  99004. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99005. options.clickToPlay = Boolean(options.clickToPlay);
  99006. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  99007. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  99008. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99009. // create
  99010. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  99011. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99012. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  99013. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99014. flat: false,
  99015. radius: options.size,
  99016. subdivisions: options.resolution,
  99017. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99018. }, scene);
  99019. // configure material
  99020. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  99021. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  99022. material.reflectionTexture = _this._videoTexture;
  99023. material.useEquirectangularFOV = true;
  99024. material.fovMultiplier = 1.0;
  99025. // configure mesh
  99026. _this._mesh.material = material;
  99027. _this._mesh.parent = _this;
  99028. // optional configuration
  99029. if (options.clickToPlay) {
  99030. scene.onPointerUp = function () {
  99031. _this._videoTexture.video.play();
  99032. };
  99033. }
  99034. return _this;
  99035. }
  99036. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  99037. /**
  99038. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99039. * Also see the options.resolution property.
  99040. */
  99041. get: function () {
  99042. return this._material.fovMultiplier;
  99043. },
  99044. set: function (value) {
  99045. this._material.fovMultiplier = value;
  99046. },
  99047. enumerable: true,
  99048. configurable: true
  99049. });
  99050. /**
  99051. * Releases resources associated with this node.
  99052. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  99053. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  99054. */
  99055. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  99056. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  99057. this._videoTexture.dispose();
  99058. this._mesh.dispose();
  99059. this._material.dispose();
  99060. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  99061. };
  99062. return VideoDome;
  99063. }(BABYLON.Node));
  99064. BABYLON.VideoDome = VideoDome;
  99065. })(BABYLON || (BABYLON = {}));
  99066. //# sourceMappingURL=babylon.videoDome.js.map
  99067. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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 float 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;\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 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 float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float 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=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=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\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\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  99068. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};